@@ -1,172 +0,0 @@
1-# Implementation Plan: Subprocess Subagents
2-
3-> Design spec: `PLAN-subprocess-subagents.md`
4-
5-Five sequential phases. Each phase leaves the repo in a working, tested state.
6-Phases 1, 2, and 5 are good ralph candidates. Phases 3 and 4 touch the core
7-subprocess/worktree boundary and require manual oversight.
8-
9----
10-
11-## Phase 1 — Headless mc mode
12-
13-**Goal:** `mc` can be launched as a non-interactive subprocess that runs a single
14-prompt and writes a structured result to a file descriptor before exiting.
15-
16-**New CLI flags:**
17-
18-| Flag | Description |
19-|---|---|
20-| `--subagent` | Headless mode: no banner, no interactive loop, no spinner, no status bar |
21-| `--agent <name>` | Load a custom agent config (system prompt + optional model override) |
22-| `--output-fd <n>` | File descriptor to write the JSON result to before exit |
23-
24-`--cwd`, `--model`, and positional prompt already exist and work unchanged.
25-
26-**Changes:**
27-
28-- Add `--subagent`, `--agent`, `--output-fd` to `parseArgs` in `src/index.ts`
29-- Add a `HeadlessReporter` (implements `AgentReporter`) that no-ops all UI methods
30-- When `--subagent` is set: use `HeadlessReporter`, skip banner, skip input loop,
31- run a single `runner.processUserInput(prompt)` then exit
32-- Before exit, write `SubagentSummary` JSON to the specified fd:
33- ```ts
34- interface SubagentSummary {
35- result: string;
36- inputTokens: number;
37- outputTokens: number;
38- worktreeBranch?: string; // Phase 4
39- }
40- ```
41-- `--agent` loads the agent config from `.agents/agents/` (reuse `loadAgents`),
42- passes its `systemPrompt` and `model` override into `runAgent`
43-
44-**Exit criteria:**
45-- `bun run src/index.ts --subagent --prompt "say hello" --output-fd 1` prints
46- valid JSON to stdout
47-- All existing tests pass
48-- No interactive mode regressions
49-
50----
51-
52-## Phase 2 — Prompt chain + system prompt
53-
54-**Goal:** Correct context file composition and balanced delegation language.
55-
56-**Changes:**
57-
58-- Fix `loadContextFile` in `src/agent/system-prompt.ts`:
59- - Load global (`~/.agents/AGENTS.md` / `CLAUDE.md`) **and** local
60- (`.agents/AGENTS.md`, `CLAUDE.md`, `AGENTS.md` at repo root) independently
61- - Compose both into the system prompt in order: global first, then local
62- - Neither silently shadows the other
63-- Update delegation guidelines in the system prompt:
64- - Main agent: *"Use the `subagent` tool sparingly — only for clearly separable,
65- self-contained subtasks. Prefer doing the work directly."*
66- - Subagent mode (`--subagent` flag): stronger wording appended — *"You are
67- running as a subagent. Complete the task directly using your tools. Do not
68- delegate to further subagents unless the subtask is clearly separable and
69- self-contained."*
70-- Custom agent system prompt (from `--agent`) appended after local context file,
71- before the user message
72-
73-**Exit criteria:**
74-- Unit tests for `buildSystemPrompt` covering: no context files, global only,
75- local only, both, and subagent mode
76-- All existing tests pass
77-
78----
79-
80-## Phase 3 — Subprocess launcher (replaces subagent-runner)
81-
82-**Goal:** The `subagent` tool spawns a real `mc` subprocess instead of running
83-in-process. Worktrees are temporarily disabled in this phase to keep the diff
84-focused. Non-git projects are unaffected.
85-
86-**Changes:**
87-
88-- Replace `src/agent/subagent-runner.ts` with a subprocess launcher:
89- - Create a pipe pair; pass the write end as `--output-fd <n>` to the child
90- - Spawn `mc --subagent --cwd <cwd> --model <model> [--agent <name>] <prompt>`
91- - Read the write end after the child exits; parse `SubagentSummary`
92- - Return `SubagentOutput` from the parsed summary
93-- Remove `depth` parameter from `runSubagent` signature
94-- Remove `.filter(tool => tool.name !== "subagent")` guard — subagents get the
95- full tool set
96-- Track active subprocess PIDs for interrupt propagation (Phase 5)
97-- Worktrees: skipped in this phase — subprocess receives the parent `cwd` directly.
98- Any worktree code in the old runner is removed but not yet replaced.
99-
100-**⚠ Manual phase** — don't ralph this. Verify by running a real subagent task
101-end-to-end and checking the result comes back correctly.
102-
103-**Exit criteria:**
104-- `@writer` (or any custom agent) delegates correctly via subprocess
105-- A custom command runs correctly via subprocess
106-- Token counts are reported in the completion line
107-- All tests pass (worktree-specific tests may need updating/removal)
108-
109----
110-
111-## Phase 4 — New worktree model
112-
113-**Goal:** Subprocess creates and owns its worktree; parent owns all merging.
114-Fixes the fragile lifecycle that could lose changes.
115-
116-**New model:**
117-1. Subprocess creates a git worktree from `parentCwd` on branch `mc-sub-<laneId>`
118-2. Subprocess works inside the worktree
119-3. Before exit, subprocess removes the worktree *directory* (keeps the branch)
120- and includes `worktreeBranch` in the fd result
121-4. Parent receives the branch name and merges it into its own working tree
122-5. Parent deletes the branch after a successful merge
123-6. On merge conflict: parent returns conflict file list in the tool result (same
124- UX as today)
125-7. Merge lock lives in the parent only — sequential per active lane, no lock
126- needed inside subprocesses
127-
128-**Changes:**
129-
130-- Add worktree lifecycle into the subprocess (create on start, remove dir on exit)
131-- Add `worktreeBranch` to `SubagentSummary`
132-- Move merge + branch cleanup into the subprocess launcher (parent side)
133-- Remove the old merge lock from `subagent-runner.ts` (already gone after Phase 3)
134-- Update `SubagentOutput` — remove `mergeConflict` / `mergeBlocked` structs;
135- replace with a single `mergeConflicts?: string[]` returned from the parent's
136- merge call
137-
138-**⚠ Manual phase** — worktree bugs are silent and destructive. Test with a
139-real multi-file edit subagent task and verify changes land in the working tree.
140-
141-**Exit criteria:**
142-- Subagent edits appear in the parent's working tree after the tool call completes
143-- A parallel subagent pair (two concurrent tool calls) both merge cleanly
144-- Merge conflict case surfaces the right file list to the LLM
145-- All tests pass
146-
147----
148-
149-## Phase 5 — Cleanup, output, and ESC propagation
150-
151-**Goal:** Remove dead code, simplify UI output, wire up interrupt.
152-
153-**Changes:**
154-
155-- **Output**: subagent tool call display becomes two lines only:
156- - `⇢ subagent [laneId] — <prompt truncated to ~60 chars>`
157- - `← subagent [laneId] done (Nin / Nout tokens)` or `✖ failed`
158- - All intermediate subprocess output is suppressed (headless reporter handles this)
159-- **ESC interrupt**: when the user hits ESC during a turn, send `SIGTERM` to all
160- tracked active subprocess PIDs before returning to the prompt; subprocesses clean
161- up their worktree directory on receipt
162-- **Remove `execution: inline`**: delete the field from `CustomCommand`, remove
163- the branch in the command handler, update `loadCustomCommands` and docs
164-- **Remove dead code**: `getSubagentMergeError`, `mergeConflict`/`mergeBlocked`
165- fields from old `SubagentOutput`, `syncDirtyStateToWorktree` call in old runner
166-
167-**Exit criteria:**
168-- `bun run jscpd && bun run knip && bun run typecheck && bun run format && bun run lint && bun test`
169- all pass clean
170-- ESC during a subagent task kills the subprocess and returns to prompt without
171- leaving orphan worktree directories
172-- No `execution: inline` references remain in source or docs