Launch a subagent to handle complex, multi-step tasks autonomously.

Each task spawns a delegated LLM session that makes its own tool calls and returns a single result message when done.

# Delegation Decision Rules

Stay local when:
- The next step is a simple read/edit/run action you can do directly
- Your immediate next action is blocked on the result, and delegation would only add latency
- The work is tightly coupled to nearby edits you are already making
- Routing is merely uncertain — do not delegate just to compensate for that uncertainty

Delegate when:
- The work needs multiple tool calls plus autonomous reasoning
- The work is self-contained enough to brief clearly
- The work can proceed in parallel without racing your current critical path

# Fresh Session vs Forked Context vs Continued Session

- New `task` calls start with fresh context by default. The subagent does NOT see your parent conversation unless you summarize it in the prompt.
- Set `execution_mode="fork_context"` when the delegated task should start from a fork of the current parent session transcript. Use this for sidecar research, audits, or follow-up verification that materially benefits from current context.
- `fork_context` is reserved for **read-only sidecar work**. If the delegated slice needs implementation or file mutation, prefer `fresh_agent`.
- Use `session_id` only to continue an existing delegated session that already has the needed context.
- `fork_context` inherits transcript context, but it does NOT change the parent/child result contract: the parent agent still owns synthesis and must wait for the child result instead of assuming it succeeded.
- For implementation-heavy work, prefer a fresh task brief with explicit file scope. For follow-up questions or incremental continuation on the same delegated slice, continue the same `session_id`.
- `isolation="worktree"` creates a **local detached git worktree** for isolated sidecar execution. This MVP is local-only and currently intended for background delegated runs.

# Brief Writing Rules

Every delegated prompt should include:
- Objective: the concrete outcome to produce
- Why: the context or decision pressure behind the task
- Write scope: whether to mutate files or stay read-only
- Starting points: relevant paths, symbols, tests, or commands
- Constraints: architectural boundaries, forbidden edits, or safety rules
- Deliverable: what the subagent should return (summary, patch, review findings, etc.)

Never delegate understanding:
- Do not hand off the core synthesis step with prompts like “based on your findings, fix it”
- Parent agent owns synthesis, judgment, and final claims
- Forked/background delegates report results; they do not authorize the parent to guess

kkcode also accepts structured brief fields for these sections (`objective`, `why`, `write_scope`, `starting_points`, `constraints`, `deliverable`) and will synthesize the directive brief when `prompt` is omitted.

## Execution contract

Whether the brief is handwritten or synthesized, delegated work must follow this contract:
- Stay local if a direct read/edit/run action would finish the next step faster
- Do not delegate to compensate for routing uncertainty on a bounded local task
- Avoid suggesting LongAgent-style escalation unless heavy multi-file evidence is actually present
- Do not fabricate completion or present unfinished work as done
- Do not peek at unfinished sibling work and convert guesses into facts
- Background delegates cannot ask interactive questions; keep them self-contained
- `isolation="worktree"` is local-only and must not be treated as a remote execution surface

Good delegation briefs are directive and self-contained. The subagent should not need to infer hidden context.

# Available subagent types

- **explore** — Fast codebase exploration specialist. Use for: finding files by patterns, searching code for keywords, understanding project structure, tracing import/export chains, answering questions about the codebase. Read-only. (Tools: read, glob, grep, list, bash)
- **architect** — Feature architecture designer. Use for: analyzing codebase patterns and conventions, designing implementation blueprints with specific files to create/modify, component designs, data flows, and build sequences. Read-only. (Tools: read, glob, grep, list, bash)
- **reviewer** — Code review specialist. Use for: finding bugs, logic errors, security vulnerabilities, code quality issues, and adherence to project conventions. Read-only. (Tools: read, glob, grep, list, bash)
- **researcher** — Deep research agent. Use for: investigating unfamiliar libraries, combining local code analysis with web search, producing research reports with sources. Read-only with web access. (Tools: read, glob, grep, list, bash, websearch, codesearch, webfetch)
- **guide** — kkcode self-help guide. Use when the user asks "How do I...", "Can kkcode...", "What tool should I use for..." questions about kkcode itself. Searches kkcode source code for accurate answers. Read-only. (Tools: read, glob, grep, list, webfetch, websearch)
- **security-reviewer** — Security audit specialist. Use for: OWASP Top 10 checks, hardcoded secret scans, dependency audits, authentication/authorization reviews. Read-only. (Tools: read, glob, grep, list, bash)
- **tdd-guide** — TDD specialist. Use for: guiding test-driven development workflows (scaffold→RED→GREEN→REFACTOR), writing failing tests first, targeting 80%+ coverage. Full access. (Tools: read, write, edit, bash, glob, grep, list)
- **build-fixer** — Build error resolver. Use for: diagnosing build failures, identifying root causes (type errors, missing imports, dependency conflicts), applying fixes, verifying builds. Full access. (Tools: read, write, edit, bash, glob, grep, list)
- **(default)** — Full-capability build agent. Use for: complex multi-file changes, refactoring, test writing, any task requiring file mutations.

# When to Use This Tool

Use `task` when the work:
- Requires multiple tool calls and autonomous reasoning (e.g. "refactor module X", "write tests for Y")
- Benefits from an independent context window (protects main conversation from result noise)
- Involves code review, deep research, or broad codebase exploration
- Can be parallelized — launch multiple independent tasks simultaneously
- Is safe to hand off without racing another agent on the same files

<example>
User: "Please investigate how authentication works in this project"
→ Launch task with subagent_type="explore", prompt="Trace the authentication flow..."

Reasoning: Open-ended exploration that may require many file reads. Subagent keeps main context clean.
</example>

<example>
User: "Refactor the database module and update all tests"
→ Launch task with default subagent, prompt="Refactor src/db/... and update test/db/..."

Reasoning: Complex multi-file change requiring autonomous execution.
</example>

<example>
User: "Review this PR for security issues"
→ Launch task with subagent_type="reviewer", prompt="Review all changed files for..."

Reasoning: Code review benefits from dedicated context and structured output.
</example>

# When NOT to Use — use the appropriate tool directly instead

Do NOT use `task` as a wrapper for simple operations:
- Reading a specific file → use `read` directly
- Searching for a specific class/function → use `grep` or `glob` directly
- Running a shell command → use `bash` directly
- Making a small file edit → use `edit` directly
- Creating a file → use `write` directly
- Any single-step operation → use the appropriate tool directly

<example>
BAD: task(prompt="Read the file src/config.mjs and tell me what it exports")
GOOD: read(path="src/config.mjs") — then analyze the content yourself

BAD: task(prompt="Search for all files named *.test.js")
GOOD: glob(pattern="**/*.test.js")
</example>

# Parameters

- **prompt** (required unless `objective` is provided for a new run): Detailed task description with ALL necessary context. The subagent starts fresh — it cannot see your conversation history. Include:
  - What to do (specific instructions)
  - Why (context for decision-making)
  - Whether to write code or just research
  - Key file paths or patterns to start with

- **subagent_type** (optional): One of "explore", "architect", "reviewer", "researcher", or omit for default build agent.

- **session_id** (optional): Continue an existing delegated session when you need follow-up work on the same slice. Do NOT use this as a substitute for briefing a new task.
- **execution_mode** (optional): `fresh_agent` (default) or `fork_context`. Use `fork_context` only when inheriting the parent transcript is genuinely useful and the delegated slice stays read-only.
- **isolation** (optional): `default` (normal workspace) or `worktree` (local detached git worktree). `worktree` is currently meant for isolated background sidecar execution only.

- **run_in_background** (optional): Set to true only for sidecar work that can continue while you do other things. Returns a task_id immediately — use `background_output` to check results later. Background delegates must be self-contained and cannot use `question`.

# Important Behaviors

- Each `task` call spawns a full LLM session — it is expensive and slow. Use it deliberately.
- The subagent's result is NOT visible to the user. You MUST send a text message summarizing the result.
- You can launch multiple tasks in parallel for independent work — this is a key advantage.
- Avoid duplicating work that subagents are already doing. If you delegated research, don't also search yourself.
- Provide clear, self-contained prompts. The subagent has no access to your conversation context.
- Clearly state whether you expect the agent to write code or just do research, since it cannot infer your intent.
- Do NOT launch overlapping delegates on the same file set unless coordination is explicit.
- Do NOT "peek" at unfinished delegated work and present it as done. Wait for the result, then summarize it accurately.
- Do NOT fabricate completion. If a background delegate is still running or blocked, report that truthfully.
- If you launch background work, keep moving on non-overlapping tasks and report progress when the delegate finishes or blocks.
