EN 中文

# Subagent & Worktree

# 子代理 & Worktree

Parallel research, planning, and isolated experimentation — v5 柱 G (shipped v0.6.0).

并行调研、起方案、隔离试方案——v5 柱 G（v0.6.0 已 ship）。

seek's main agent runs your conversation in one thread. When a task needs parallel work (read 50 files at once, propose three approaches simultaneously, try a refactor in isolation), the model spawns subagents — each with its own session, its own token budget, optionally its own git worktree. Results condense into a single summary fed back to the parent.

seek 的主 agent 在一个线程里跑你的对话。需要并行工作时（一次读 50 个文件、同时起 3 个方案、隔离试一次 refactor），模型派生子代理——各自独立 session、独立 token 账户，可选独立 git worktree。结果浓缩成单个 summary 回到父。

## Why it exists

## 为什么

Three concrete problems the parent agent can't solve on its own:

父 agent 单线程解决不了三件事：

- Context window protection — "read 50 files and summarize" would bloat the parent transcript past the prefix-cache reuse threshold. A subagent absorbs the 50 files; only the summary crosses back.
- 上下文保护——「读 50 个文件归纳风格」会让父 transcript 膨胀到失去 prefix-cache 复用价值。子代理吞掉这 50 个文件，只把 summary 塞回父。
- Real parallelism — three independent research questions take min(t1,t2,t3) wall-clock, not t1+t2+t3.
- 真正的并行——三个独立调研花 min(t1,t2,t3) 墙钟时间，而不是 t1+t2+t3。
- Safe experimentation — worktree-isolated subagents can try a refactor without touching your working tree. Discard or keep on completion.
- 安全试验——worktree 隔离的子代理可以试 refactor 而不动你的工作树，结束时丢弃或保留。

## The shape

## 形状

    parent agent
       ├─→ subagent · explore  → read 3 directories → summary
       ├─→ subagent · plan     → draft an approach → summary
       └─→ subagent · worktree → try refactor in isolation → summary
            │
            ▼
       father reads summaries → continues conversation

## LLM-facing tools

## LLM 调用的工具

The model spawns subagents through the `agent` tool; worktree isolation is opt-in via `enter_worktree` / `exit_worktree`:

模型通过 `agent` 工具派生子代理；worktree 隔离通过 `enter_worktree` / `exit_worktree` 选用：

Tool | 工具 | Purpose | 用途
--- | --- | --- | ---
agent | Spawn a subagent (explore / plan / general-purpose). Returns a single summary. ReadOnly-marked → multiple `agent` calls in one assistant turn dispatch in parallel. | 派生子代理（explore / plan / general-purpose）。返回单个 summary。标 ReadOnly → 一轮多个 `agent` 调用并行分派。
enter_worktree | Create an isolated git worktree under `~/.seek/projects/<pid>/worktrees/<id>`. Subsequent edits go there, not your working tree. | 在 `~/.seek/projects/<pid>/worktrees/<id>` 创建隔离 worktree。后续编辑在那里发生，不动你的工作树。
exit_worktree | Leave the worktree. Disposition: `discard` (default; stashed to `refs/seek/discarded/<ts>` for accidental-recovery), `keep` (file stays for later inspection), `merge` (manual — model prints suggested commands). | 离开 worktree。处置：`discard`（默认；stash 到 `refs/seek/discarded/<ts>` 防误删）、`keep`（保留待后续检查）、`merge`（手动——模型打印推荐命令）。

## User-facing surfaces

## 用户面

    $ seek
    > /agents                    # TUI panel: live + completed subagents
    > /worktrees                 # TUI panel: seek-managed git worktrees

    $ seek worktree list         # CLI: same data as /worktrees
    $ seek worktree gc           # reap orphans from crashed sessions

## Safety contracts

## 安全约定

- Permission单调收紧 — a subagent's permissions can only be tighter than the parent's, never looser. `PrefYolo` parent can spawn `PrefAsk` child; the reverse never happens. `PlanAnalyze` parent forces all children to `PlanAnalyze` (no escape via spawn).
- 权限单调收紧——子代理权限只能更严，永远不能更松。`PrefYolo` 父可以派生 `PrefAsk` 子；反向永不发生。`PlanAnalyze` 父强制所有子也是 `PlanAnalyze`（spawn 不能绕过）。
- Cost rolled up to parent — subagent token usage adds to the parent's status-bar cost via `cache.Tracker.AdoptChild`. No hidden bill.
- 成本累加到父——子代理的 token 通过 `cache.Tracker.AdoptChild` 累加到父状态栏。无隐藏账单。
- Spawn depth = 1 — subagents cannot themselves spawn subagents. Prevents runaway fan-out. `AdoptChild` panics if called on a child with children.
- 派生深度 = 1——子代理不能再派生子代理。防止失控 fan-out。`AdoptChild` 在子已有 children 时 panic。
- Worktree ≠ sandbox — worktree isolates file conflicts for parallel work; it does NOT sandbox bash (`../outside` paths and absolute paths still resolve normally). Don't run untrusted code in a worktree expecting containment.
- Worktree ≠ 沙箱——worktree 隔离的是文件冲突，不是 bash 沙箱（`../outside` 和绝对路径仍正常解析）。别在 worktree 里跑不可信代码当沙箱。

## What lives where

## 文件位置

Path | 路径 | Contents | 内容
--- | --- | --- | ---
`~/.seek/projects/<pid>/sessions/<sid>/subagents/<sub-sid>/transcript.jsonl` | Subagent full message history — resumable via `seek -resume <sub-sid>`. | 子代理完整消息历史——可通过 `seek -resume <sub-sid>` 续传。
`~/.seek/projects/<pid>/sessions/<sid>/subagents.jsonl` | Per-parent-session subagent index (started/completed/failed/orphaned events) — drives `/agents` rendering. | 每个父 session 的子代理索引（started/completed/failed/orphaned 事件）——驱动 `/agents` 渲染。
`~/.seek/projects/<pid>/worktrees/<wt-id>/` | Active worktree filesystem (per `git worktree add`). | 活跃 worktree 文件系统（由 `git worktree add` 创建）。
`refs/seek/discarded/<timestamp>` | Git ref where `exit_worktree if_dirty=discard` stashes work for accidental-recovery (not in default refspec; GC'd by `seek worktree gc`). | `exit_worktree if_dirty=discard` 时 stash 到这里防误删（不在默认 refspec 中；由 `seek worktree gc` 清理）。

## Limits

## 限制

- MaxConcurrent — at most N (default 3) active subagents at once. Excess spawn returns `[agent: failed reason=too_many_subagents]`; the parent model decides whether to retry or switch strategy.
- MaxConcurrent——最多同时 N 个（默认 3）活跃子代理。超出的 spawn 返回 `[agent: failed reason=too_many_subagents]`；父模型自行决定 retry 或换策略。
- MaxTurns inherited — child inherits parent's `MaxTurns` (default 200). Exhaustion → `[agent: failed reason=max_turns_exceeded]`.
- MaxTurns 继承——子继承父的 `MaxTurns`（默认 200）。耗尽 → `[agent: failed reason=max_turns_exceeded]`。
- No streaming surface yet — subagent output is opaque until the summary fires. Live streaming into a collapsible region is a v0.6.x dot follow-up.
- 暂无流式回显——子代理输出对父不可见，直到 summary 落地。流式回显到可折叠区域是 v0.6.x dot 跟进项。

📖 Full design rationale: feature-subagent.md + book chapter 21. Worktree GC + orphan recovery details in §3.8. 📖 完整设计原理：feature-subagent.md + book 第 21 章。Worktree GC + 孤儿恢复详见 §3.8。