feat: subprocess subagents with worktree isolation (#4)
* fix(interrupt): ESC cancels turn preserving partial response, arrow keys no longer cancel
- ESC during a turn stops the LLM, preserves any partial streamed text in
history with an interrupt stub appended so the LLM retains context
- Multi-byte ESC sequences (arrow keys, function keys) no longer trigger cancel;
only a lone ESC byte (0x1B) is treated as cancel
- Ctrl+C always exits the process (never routes through interrupt path)
- SIGINT no longer hijacked by watchForCancel; falls through to the default
registerCleanup handler (exit 130)
- Ralph mode no longer forcibly disabled on interrupt
- session-runner: removed wasAborted flag, errorStubSaved guard, and all
abort-specific branching; renderTurn now returns partial messages on abort
and throws on real errors for a single clean code path
- ESC_BYTE and CTRL_C_BYTE now derived from their string counterparts via
charCodeAt(0) to make the relationship explicit
- Docs: idea file updated to reflect ESC as cancel key with correct behaviour;
stale TODO entry removed
* docs: plan subprocess subagents, consolidate TODO items
* docs: revise plan with subprocess details, prompt chain, worktree model
* docs: add phased implementation plan for subprocess subagents
* Phase 1: headless mc mode (--subagent, --agent, --output-fd)
- Add --subagent, --agent <name>, --output-fd <n> CLI flags
- Add HeadlessReporter: no-op AgentReporter that tracks tokens silently
- Add headless path in runAgent: single processUserInput call, returns SubagentSummary
- Define SubagentSummary { result, inputTokens, outputTokens, worktreeBranch? }
- Write SubagentSummary JSON to --output-fd before exit; write { error } on failure
- Extract buildAbortMessages() helper, used by both HeadlessReporter and stream-render
* phase 2: system prompt chain, subagent delegation, HeadlessReporter fix
- loadContextFile split into loadGlobalContextFile (~/.agents/) and
loadLocalContextFile (.agents/AGENTS.md > CLAUDE.md > AGENTS.md);
both compose under a single # Project context section, global first
- delegation guideline updated: subagent tool sparingly, prefer direct work
- buildSystemPrompt gains isSubagent param; appends stronger no-delegation
wording when running as a subprocess
- SessionRunner / agent.ts plumbed through isSubagent (= headless flag)
- getConfigDir unexported (only used internally in connection.ts)
- HeadlessReporter: track text-delta accumulation and pass to
buildAbortMessages so partial streamed text is not dropped on abort
- Remove dead SubagentSummary.worktreeBranch field (Phase 4 placeholder)
- Unit tests for buildSystemPrompt and loadLocalContextFile (12 tests)
* Phase 3: replace in-process subagent runner with subprocess launcher
- Spawn mc --subagent as a real subprocess instead of running in-process
- Communicate via --output-fd 1 (captured stdout); parse SubagentSummary JSON
- Remove worktree lifecycle, merge lock, depth parameter, and subagent filter
- Add MC_SUBAGENT_DEPTH env-var guard (max 10) to cap runaway recursion
- Guard JSON.parse with a descriptive error including raw subprocess output
- Track active subprocess PIDs for Phase 5 interrupt propagation
- Remove unused formatSubagentLabel export (was only used by old runner)
* Phase 4: new worktree model for subprocess subagents
Subprocess creates and owns its worktree; parent owns all merging.
- Subprocess (index.ts headless mode): on git repos, creates a worktree
on branch mc-sub-<laneId> before running the agent, removes the
worktree directory after, and includes worktreeBranch in the fd result.
SIGTERM handler cleans up both the worktree directory and the branch.
- Parent (subagent-runner.ts): after the subprocess exits, merges the
reported branch into the parent cwd via a serialising merge lock, cleans
up the branch on success, or surfaces mergeConflicts on failure.
- SubagentSummary gains worktreeBranch; SubagentOutput replaces the old
mergeConflict/mergeBlocked structs with a single mergeConflicts field.
* Phase 5: cleanup, output, and ESC propagation
- Subagent tool call display: two lines only
- tool-call-start: ⇢ [callId] — <prompt ~60 chars>
- tool-result: ← [callId] done (Nin / Nout tokens)
- toolCallId threaded through renderToolCall/renderToolResult in stream-render
- ESC interrupt propagation to subprocesses
- createSubagentRunner returns { runSubagent, killAll }
- SessionRunner accepts killSubprocesses option, registers abort listener
- ESC SIGTERMs all active subprocess PIDs before returning to prompt
- Remove execution: inline
- Removed from docs/custom-commands.md
- Removed from .agents/commands/release.md
- Remove dead code
- renderSubagentEvent, renderToolResultInline, stripAnsiSgr,
normalizeParentLaneLabel, formatSubagentLabel, laneBuffers (tool-render.ts)
- splitNullSeparated, applyPatch, copyUntrackedPath (worktree.ts)
- gitStatusLines (worktree.test.ts)
- _reporter and _getThinkingEffort params from createSubagentRunner
- currentThinkingEffort local in agent.ts
- Deduplicate assertSubagentMerged into tools/subagent.ts
(was copy-pasted identically in tools.ts and commands.ts)
* fix: address five subagent subprocess review gaps
Bug 1: remove contradictory delegation guideline
The 'use subagents to achieve this' tail of the guidelines bullet
directly negated the new 'sparingly' directive above it. Removed.
Bug 2: use fd 3 instead of stdout for subprocess communication
Switch Bun.spawn to stdio array so fd 3 is a dedicated pipe.
Parent reads via Bun.file(proc.stdio[3]).text(); subprocess writes
to fd 3. Stdout is now free — an accidental console.log can no
longer silently corrupt the JSON summary.
Bug 3: SIGTERM handler must not delete the branch
The subprocess SIGTERM handler was deleting both the worktree dir
and the branch. Per plan, it should only remove the worktree dir;
the branch is left for the parent to discard.
Bug 4: parent-side cleanup of interrupted branches
Parent now generates the branch name and passes it via
--worktree-branch so it knows what to clean up if the subprocess
is killed. activeProcs (Map<pid, branch>) replaces the old
activePids Set; killAll() calls cleanupBranch() best-effort for
each tracked branch after sending SIGTERM.
Bug 5: test coverage for global+local context composition
Added homeDir param to buildSystemPrompt (forwarded to
loadGlobalContextFile) so tests can inject an isolated home
directory. All existing buildSystemPrompt tests now pass fakeHome
to prevent real ~/.agents from leaking in. Added three new tests:
global only, global+local ordered correctly, neither present.
* fix subagent runner: race in killAll, completion glyph, system prompt wording
- killAll: track proc objects instead of PIDs so branch cleanup can await
proc.exited before calling git branch -D; previously the branch was still
checked out when cleanupBranch ran, causing silent git failures and orphaned
mc-sub-* branches on interrupt
- stdio: keep inherit for stdout/stderr so subprocess crashes surface in the
parent terminal; silencing them left 'no output' as the only diagnostic
- completion line: use c.cyan('←') + 'subagent done' instead of G.read (wrong
glyph, dimmed) — matches the plan's intended return-arrow format
- system prompt: add 'that benefit from a fresh context window' to main agent
guideline; strengthen subagent delegation block to 'you have been given' /
'unambiguously separable' per plan
- plan: document MC_SUBAGENT_DEPTH cap as an intentional safety rail
xonecas2026-03-10
d8b26d2fe9b2a965d8c7e5df852e4303d261becb
parent 12721b7