匠人学院 JR Academy
  • Position

    Where am I now, and where should I go?

    How your job is changing, where your experience can take you and what you still need for a target role, worked out from what you have actually done. Free, and the full result needs no sign-up.

    Analyse my career and skills

    Look up a career

    Will AI replace my job?AI impact and transition paths for common careersNew jobs in the AI eraWhat they do, what they need, how to move in

    Focused tools

    AI Engineer interview readiness30 timed questions on what you still need before interviewsCareer personality testDirections that suit how you workReturning to China checkJob prospects in China by school, major and graduation date

    AI coach

    Talk to your AI coachStill unsure after your result? Talk through what is holding you back
  • Core courses

    AI Engineer BootcampEngineering bootcamp from LLM apps to agentsAI Engineer Full-Stack Project Class16 weeks · RAG and full-stack AI projectsVibe Coding Masterclass8 weeks · direct agents to build and ship a productAI Essentials10 hours · use AI for email, reports, data and copyAI Office Automation Course8 weeks · help a whole company adopt AIOne-Person Company (OPC) Bootcamp15 weeks in person · build a one-person company with AIAll courses →

    AI engineering

    Machine Learning & Data Engineering Full-Stack ClassAI Agent & MCP Project BootcampAI Engineer Core TechniquesAI Engineer FoundationsAI Engineer Advanced: RAG to Agents and TuningClaude Code TasterAll AI engineering courses →

    AI at work

    AI Coding for everyoneClaude Code One-Day Masterclass (Non-Technical)Enterprise AI Automation BootcampAI Marketing BootcampAI Risk, Governance and Audit CourseOpenClaw 4-Week Personal AI Assistant BootcampAll AI-at-work courses →

    Career development

    AI Product Manager (BA) Bootcamp + InternshipAustralia IT Interview BootcampAustralia IT Technical Interview BootcampAustralia IT Resume BootcampAustralia Big Tech Job Search BootcampAustralia IT Career Planning BootcampAll career courses →

    Learn free first

    Vibe CodingAI for office workPrompt MasterAI EngineerAI data analysisResource centerInstructorsAll learning paths →
  • Evidence

    What will convince an employer?

    Certifications, projects, team work and competition entries, collected into one portfolio.

    See the portfolio

    Certifications

    Cert Master · all certificationsPrep and mock exams for AWS, Azure, GCP, Claude and moreAWS CLF-C02Entry-level AWS cloud certificationAWS SAA-C03Entry certification for cloud architectsClaude certificationsAnthropic Claude certification seriesAll certifications →

    Projects and team work

    P3 team projectsBuild a project with real teammates in a simulated team workflowP3 project experienceThe parts of a P3 project that go on your resumeDemo DayProject showcaseP3 certificatesProof once a project is completeAll of P3 →

    Competitions and work

    HackathonsBuild something against the clockSubmit your workAdd your project to the showcaseCareerOS portfolioDo tasks in the desktop app; your results become portfolio pieces
    Cert MasterBrowser extension, app and mini programScreenshot a question for analysis and practise anywhereAbout Cert Master
  • Connect

    How do I get myself in front of employers?

    Resume, interviews, referrals and mentors. See how far you are from the target role first, then decide what to fix.

    Start with Jobpin

    Resume and openings

    Graduate careersGraduate preparation across Australia, China, Malaysia, Singapore, the US and UKJobpinAI job search workspace: resume, roles, applicationsAI resumeRewrite your resume against a job descriptionReferralsRoles shared by students and mentorsOpportunitiesInternships, projects and collaborationsOffer boardOffers students have received

    Interviews

    AI Engineer interview guideSeven areas, with worked examplesFDE interview guideFive rounds, from scoping to the customer roundAI mock interviewPractise by text or voice and see the gapsInterview storiesReal interview experiencesSystem Design handbookPrepare for system design interviewsAll interview prep →

    Mentors

    1:1 mentorsBook AI, career and technical mentors by the hourGroup tutoringShare a tutor with a few others and pay less eachCareer coachingResume, interview and direction packages
    Jobpin desktopOne workspace for the whole job searchOrganise real experience and refine resume versions for target roles on macOS or Windows.About Jobpin
BusinessMembershipDownload CareerOS
0
匠人学院 JR Academy

Follow Us

linkedinfacebooktwitterinstagramyoutube

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png
Airbotix · AI learning & creation for kids Another Life · AI story game
Products46

CareerOS and tools

  • CareerOS
  • Cert Master
  • Jobpin
  • Jobpin web
  • Jobpin report
  • Jobpin desktop download
  • My job search reports
  • Buy report credits
  • Jobpin billing
  • AI Toolbox
  • AI Skill Marketplace

Membership

  • Membership
  • AI membership

Courses

  • Bootcamps
  • Training Camp
  • Kanban learning
  • AI Builder course
  • MCP course
  • NotebookLM workshop
  • Business Analyst course
  • Web Full-Stack Bootcamp
  • DevOps Bootcamp
  • Data Engineering Bootcamp
  • Data Analysis Bootcamp
  • Coding for Beginners
  • Algorithm Bootcamp

Career services

  • Graduate careers
  • Graduate careers in Australia
  • Graduate careers in China
  • Graduate careers in Malaysia
  • Graduate careers in Singapore
  • Graduate careers in the US
  • Graduate careers in the UK
  • 1:1 coaching
  • Career coaching
  • AI Engineer VIP
  • BA & PM Internship
  • Data Science Internship
  • Data Analysis Internship
  • Marketing Internship
  • Resume Review
  • Interview Coaching
  • Job Application Service
  • Job Monitoring
  • LinkedIn Management
  • LinkedIn Networking
Library57

Learning paths

  • All Learning Paths
  • AI Engineer
  • Context Engineering
  • Vibe Coding
  • Prompt Master
  • AI Builder
  • AI Product Manager
  • Python Basics
  • AI Productivity
  • AI Data Analysis
  • AI Finance
  • AI Content Creation
  • AI Image Creation
  • Frontend Development
  • Hermes Agent
  • OpenClaw Local Agent

Interactive labs

  • Prompt Lab
  • Frontend Lab
  • JavaScript Lab
  • Python Lab
  • AWS Lab
  • Azure Lab
  • LLM Lab
  • Git Lab

Reference and guides

  • Resources
  • Wiki
  • Cheat sheets
  • Roadmaps
  • AI roadmaps
  • Videos
  • Ebooks
  • Blog
  • Interview handbook
  • Mock exams
  • Free resources

Cities

  • Sydney
  • Melbourne
  • Brisbane
  • Adelaide
  • Singapore
  • Kuala Lumpur
  • London
  • New York
  • San Francisco
  • Los Angeles
  • Seattle
  • Toronto
  • Vancouver

Immigration

  • Australia Immigration
  • Skilled Visa 189/190/491
  • Employer Sponsored 482/186/494
  • Business Visa 188/888
  • UK Immigration
  • US Immigration
  • Canada Immigration
  • Singapore immigration
  • Malaysia immigration
Business20

For business

  • AI for Business
  • Business portal sign-in
  • Corporate Training
  • Internship Partnership
  • Recruitment Partnership
  • Enterprise (EN)

Metatree AI Lab

  • Metatree AI Lab (Chinese)
  • AI solutions (Chinese)
  • Digital employees (Chinese)
  • Case studies (Chinese)
  • Metatree AI Lab
  • AI services
  • Digital employees
  • Case studies

AI education for kids

  • Airbotix — AI Learning & Creation for Kids
  • AU Family Resource Hub
  • NAPLAN Report Guide
  • My School Data Guide
  • Sydney Private School Fees 2026
  • Kids Coding Programs
About15

Company

  • About Us
  • Our Mentors
  • Become a Mentor
  • Metaverse Classroom
  • JR Careers
  • Another Life — AI Story Game
  • Contact Us

Help and policies

  • FAQs
  • Terms & Conditions
  • Privacy Policy
  • Cancellation & Refund Policy
  • Site map

Friend links

  • CS Browser

Contact

  • hello@jiangren.com.au
  • 0421-672-555

Offices

Level 10b, 144 Edward Street, Brisbane CBD (Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
45A13, Block B, Oriental Hope Tianxiang Plaza, 500 Tianfu Avenue Middle Section, Wuhou District, Chengdu, Sichuan, China
Business Hub, 155 Waymouth St, Adelaide SA 5000
Disclaimer
footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

All content on the JR Academy website, including course materials, logos, and information provided, is protected under Australian intellectual property laws. Unauthorized use, sale, distribution, reproduction, or modification is strictly prohibited. Violations may result in legal action. By accessing our website, you agree to respect our intellectual property. JR Academy Pty Ltd reserves all rights, including patents, trademarks, and copyrights. Any infringement will be subject to legal prosecution. View Terms of Service

© 2017-2026 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572

HomeLearnCoursesCerts
  1. Home
  2. Learn
  3. Blog
  4. Claude Code 从入门到实战 — Subagent 设计模式:什么时候用、怎么写、如何隔离
JR Academy · BlogCareer insights

Claude Code 从入门到实战 — Subagent 设计模式:什么时候用、怎么写、如何隔离

Subagent 的核心价值是上下文隔离——把大量探索结果关在独立窗口里,主对话只看最终摘要。本章覆盖:何时委托、frontmatter 结构、Prompt 怎么写、worktree 隔离

Published2026-11-30
Reading time4 min
Author

Contents

  • 为什么要用 Subagent
  • Subagent 文件格式
  • 完整 frontmatter 字段
  • 内置 Subagent
  • 怎么写 Subagent 的 Prompt
  • 上下文隔离的好处
  • Worktree 隔离
  • 实战:几个常见的自定义 Subagent
  • 只读代码审查
  • 测试生成器
  • 批量文档更新(worktree 隔离)
  • 用 CLI flag 临时定义 Subagent
  • 禁用特定 Subagent
  • 小结

为什么要用 Subagent

主对话的上下文窗口是有限资源。你让 Claude 扫 200 个文件找一个 bug,那 200 个文件的内容全部堆进同一个窗口——后续每次对话都要携带这些噪音,成本涨、精度降。

Subagent 的价值就一条:把副任务的中间过程关在一个独立窗口里,主对话只收一份摘要。

官方文档对触发时机的描述很直接:

Use one when a side task would flood your main conversation with search results, logs, or file contents you won't reference again.

Subagent 上下文隔离示意

三个具体场景:

  1. 探索型任务:搜代码、读文件、查日志。结果量大但最终只需要一句结论。
  2. 并行独立任务:写测试、格式化代码、更新文档——互不依赖,同时跑省时间。
  3. 工具受限场景:只需要 Read/Grep/Glob,不允许 Write/Edit——把能力限死,防止越权。

Subagent 文件格式

Subagent 定义在 Markdown 文件里,放 .claude/agents/(项目级)或 ~/.claude/agents/(用户级),YAML frontmatter 是配置,正文是系统 Prompt。

---
name: code-reviewer
description: Reviews code for quality and best practices. Use after any code change.
tools: Read, Glob, Grep
model: sonnet
---

You are a senior code reviewer. Analyze the code for:
- Security vulnerabilities (injection, auth bypass, data exposure)
- Performance bottlenecks
- Readability and naming issues

For each issue: show the file + line, the problem, and a concrete fix.

name 是唯一标识,description 是 Claude 决定「要不要委托」的依据——这两个字段是必填项,其余都可选。

完整 frontmatter 字段

字段 说明
name 必填,小写字母加连字符,全局唯一
description 必填,Claude 用这段文字判断何时委托
tools 允许的工具列表,省略则继承主对话所有工具
disallowedTools 明确禁用的工具(从继承列表里剔除)
model haiku / sonnet / opus / fable / 完整 model ID / inherit
permissionMode default / acceptEdits / auto / dontAsk / bypassPermissions / plan
maxTurns 最多跑几轮,防止失控
isolation worktree:给 subagent 一份独立 git worktree
memory user / project / local:跨 session 保留学习内容
background true:默认后台运行
color UI 里的颜色标识(red / blue / green 等)

内置 Subagent

Claude Code 自带三个常用 subagent,不需要任何配置就能用:

Explore — 只读探索,用 Haiku 跑,速度快、成本低。Claude 需要搜代码但不需要修改时自动委托。调用时可以指定深度:quick(单次精准查找)、medium(适度探索)、very thorough(全面扫描多个位置)。

Plan — Plan 模式下的研究 agent。你在 plan 模式里提任务,Claude 把代码库调研丢给 Plan subagent,主对话保持只读等待结果。

General-purpose — 全能型,继承主对话所有工具,用于需要「探索 + 修改 + 多步骤」的复杂任务。

另外还有 claude-code-guide(你问 Claude Code 功能时 Claude 自动用)和 statusline-setup(跑 /statusline 时自动用)。

怎么写 Subagent 的 Prompt

Subagent 的正文(Markdown body)就是它的系统 Prompt。它只收到这段 Prompt 加上基本环境信息(工作目录等),不继承主对话的 Claude Code 系统 Prompt。

这意味着主对话里的 CLAUDE.md 规则、用户设置、历史上下文,subagent 都不知道——除非你明确写进 Prompt 里。

几条实用原则:

1. description 比 prompt 更重要

Claude 是根据 description 决定委托还是自己做,根据 prompt(正文)决定怎么做。description 写得模糊,Claude 就不会用它。要写成「当 X 发生时用我」的形式:

description: >
  Scans any Python file for common security issues: SQL injection,
  hardcoded secrets, unsafe deserialization. Use proactively after
  any change to .py files.

2. 告诉它输出什么格式

Subagent 的输出是主对话唯一能看到的东西。格式不定,主对话很难用结果做后续判断。

Return results as a JSON array:
[{"file": "...", "line": N, "issue": "...", "severity": "high|medium|low"}]
If no issues found, return [].

3. 把约束写死

Subagent 没有主对话的语境,它不知道「不要改生产配置」这种隐性规则。需要限制的就明确写:

NEVER modify files. NEVER run commands that have side effects.
Only read and analyze.

4. 给复杂任务加 maxTurns

没有 maxTurns 的 subagent 可能在遇到意外情况时无限循环。探索型任务通常 maxTurns: 10 够用;复杂实现任务可以到 30-50。

上下文隔离的好处

主对话上下文和 subagent 上下文是完全独立的两个窗口。subagent 做的所有中间工作——tool calls、中间推理、部分结果——全部留在它自己的窗口里。主对话只收一条最终消息。

这个设计有几个实际收益:

成本控制:搜索 100 个文件的 token 消耗,算在 subagent 里。主对话窗口没有膨胀,后续对话的每次推理成本不变。

结果质量:主对话上下文越干净,Claude 越不容易被历史噪音干扰。让 subagent 处理探索,主对话专注决策。

模型优化:用 model: haiku 的 Explore subagent 做文件搜索,用 model: opus 的主对话做架构决策——根据任务选最合适的模型,而不是一刀切。

# 示意:主对话里 Claude 如何自动委托 Explore
用户: 帮我找所有用了 deprecated axios.get 的地方
Claude: → 委托给 Explore subagent(快速,只读)
        Explore: 扫描 47 个 .ts 文件... 找到 12 处
        主对话收到: "找到 12 处,分布在 src/api/ 下的..."

Worktree 隔离

isolation: worktree 给 subagent 一份独立的 git worktree——它读写的是一份代码副本,不会污染主工作目录。

---
name: refactor-agent
description: Refactors code safely in isolation. Use when changes are experimental.
isolation: worktree
tools: Read, Write, Edit, Bash
model: sonnet
---

Perform the requested refactoring. Run tests after each change.
If tests fail, revert and try a different approach.

适合这个模式的场景:

  • 实验性重构,不确定方向对不对
  • 批量格式化或代码迁移(影响范围大,想先看结果再决定要不要合并)
  • 并行处理多个独立功能,各自在独立分支上

Worktree 清理规则:subagent 没有做任何变更时自动删除;有变更时保留,等你决定合并还是丢弃。

实战:几个常见的自定义 Subagent

只读代码审查

---
name: security-reviewer
description: >
  Reviews code for security vulnerabilities. Use after any change
  to authentication, API routes, database queries, or file I/O.
tools: Read, Grep, Glob
model: sonnet
color: red
---

You are a security engineer reviewing code for vulnerabilities.
Focus on: SQL/NoSQL injection, XSS, CSRF, insecure deserialization,
hardcoded secrets, path traversal, broken access control.

For each issue found:
1. File path and line number
2. Vulnerability type (OWASP category)
3. Why it's dangerous
4. Concrete fix with code snippet

If no issues, reply: "No security issues found."

测试生成器

---
name: test-writer
description: Generates unit tests for a given module or function.
tools: Read, Glob, Write, Bash
model: sonnet
maxTurns: 20
---

You write unit tests. When given a file or function:
1. Read the source code
2. Identify edge cases and failure modes
3. Write tests using the project's existing test framework
4. Run the tests and fix failures before returning

Place test files alongside the source (foo.ts → foo.test.ts).
Return a summary: how many tests, pass rate, any known gaps.

批量文档更新(worktree 隔离)

---
name: doc-updater
description: Updates JSDoc/docstring comments across a module. Safe to run on large changes.
tools: Read, Edit, Glob
model: haiku
isolation: worktree
maxTurns: 50
color: blue
---

Update all JSDoc comments in the specified files to accurately reflect
the current implementation. Do not change any logic, only comments.
Flag any functions with no tests as "⚠ untested" in their docstring.

用 CLI flag 临时定义 Subagent

不想写文件?可以在启动 Claude Code 时直接用 --agents 传 JSON,只对当前 session 生效:

claude --agents '{
  "db-migration-checker": {
    "description": "Validates database migrations for safety before applying.",
    "prompt": "Check the migration file for: backwards-incompatible changes, missing rollback, locks on large tables. Return a risk assessment.",
    "tools": ["Read"],
    "model": "sonnet"
  }
}'

适合 CI pipeline 或一次性任务,不需要持久化配置。

禁用特定 Subagent

不想让 Claude 自动委托给某个内置 subagent?在 settings.json 里 deny 它:

{
  "permissions": {
    "deny": ["Agent(explore)", "Agent(plan)"]
  }
}

要完全禁止 subagent 委托,直接 deny Agent 工具本身。

小结

场景 推荐做法
搜代码、读日志、探索文件 用内置 Explore subagent(自动触发)
多个独立任务并行 让 Claude 同时启动多个 subagent
只读审查,不允许修改 tools: Read, Grep, Glob,不加 Write/Edit
实验性修改不想污染工作目录 isolation: worktree
控制成本,探索用便宜模型 model: haiku for Explore,model: opus for 决策
防止 subagent 失控 加 maxTurns: N
跨 session 积累经验 memory: project 或 memory: user

Subagent 不是越多越好——每多一层委托就多一次上下文切换和摘要损耗。判断标准很简单:这个任务的中间过程,主对话以后还需要看吗? 不需要 → 扔给 subagent。需要 → 留在主对话。

Author
Share or copy the link

Related certifications

Start with a few sample questions or a free chapter. The exam guide covers what the exam tests; the question bank lets you practise by exam domain.

Foundational

Claude Certified Architect – Foundations

CCAR-F

Sample questionsExam guide
Foundational

Claude Certified Developer – Foundations

CCDV-F

Question bankExam guide
Associate

Claude Certified Associate – Foundations

CCAO-F

Question bankExam guide

Related learning resources

  • AI Engineer learning path
  • Vibe Coding Hub
  • Prompt engineering
← Previous articleClaude Code 从入门到实战 — 并行开发:Worktree 让多个 Claude 同时干活Next article →匠人学院使用指南 — 快速上手:5 分钟看懂匠人学院

Related articles

🇦🇺测一下:袋鼠国码农能当FDE吗?

2026-12-01

Monash 研究:肠道酸度是膳食纤维降血压的关键;AI 搬运新闻冲击维州选举信息;MPAC 公布 2027 演出季

2026-12-01

Adelaide 物理学家获 $250,000 总理科学奖;全球葡萄酒消费六十年降四分之一;残障师范生实习障碍研究

2026-12-01

DVA-C03今日上线首发 · Google Cloud AI Agent认证完整解析 · AZ-401本月GA替代AZ-400

2026-12-01

Anthropic推迟下一代模型并调百人做安全,AWS推出AI办公三件套,Google让用户单独关掉AI训练

2026-12-01

GitHub Copilot 实战指南 — Copilot AI Code Review:30 秒让 AI 帮你审 PR,三档深度随需切换

2026-11-30
View all articles →

Done reading? Next steps

Not sure what to learn next? Tell us where you are

Tell us what you do now and where you want to go. See your gaps in skills, evidence, experience, expression and positioning, and what to work on first. No sign-in needed.

Compare with my situation
  • SkillAI Engineer Bootcamp13 weeks, 12 Theory + 13 Practice live classes. You build one Agent system across Context, RAG, Tools, Memory and production Evals. Built for Applied AI and Agent Engineer roles.See the program →
  • PositioningLearning roadmaps by roleFrontend, backend, data, AI and more, laid out stage by stage in the order to learn them.All roadmaps →
  • ExpressionTry an AI mock interviewPick a role and run a mock interview to practise explaining your experience and projects.Practise now →

Not sure what to do next?

Take this page's topic with you and see where your gaps are.

Compare with my situation
JR Academy
AI learning for the global Chinese community
BootcampsFree resourcesLearn AICareer coaching
精选推荐
AI Career Impact Map
Assess career exposure and explore transition paths and learning options
Popular tool
AI & Data Bootcamps
Build your skills through structured courses and hands-on projects
Popular courses
1:1 Career Coaching
Work with an experienced mentor on your resume and interview preparation
Career coaching
Custom Corporate Training
AI training tailored to your team
Business services
Popular tags
Vibe CodingAI codingCursorClaudeJob searchPromptFrontend developmentBackend development
Subscribe to updates

Receive AI learning resources, technical tutorials and career advice by email.

We respect your privacy and do not send spam.