xonecas.io
64875
Mc

mini-coder / commit 7be2016

chore: remove impl/plan docs, update TODO post-merge cleanup

xonecas2026-03-10 7be2016fd0ae64c4a82b29c1ae2cb2c23fd4c4e9 parent d8b26d2

3 files changed

IMPL-subprocess-subagents.md+0−172
@@ -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
PLAN-subprocess-subagents.md+0−153
@@ -1,153 +0,0 @@
1-# Plan: Subagents as Subprocess mc Sessions
2-
3-## Problem
4-
5-The current in-process subagent runner is a second-class implementation of the agent loop:
6-
7-- Subagents are less capable than the main agent (different system prompt path, tools stripped)
8-- Subagents don't reliably know their working directory — they guess, causing cascading failures
9-- Subagents can't spawn subagents (the tool is stripped at depth > 0)
10-- Ralph mode is broken inside subagents (the loop logic behaves differently in the stripped-down runner)
11-- The runner duplicates agent bootstrap logic: system prompt building, model resolution, tool set assembly
12-- Worktree lifecycle is fragile — changes can be lost when merge or cleanup ordering goes wrong
13-
14-## Goal
15-
16-Replace `subagent-runner.ts` with a subprocess that launches a fresh `mc` process. A subagent becomes a real mini-coder session, not a stripped-down approximation of one.
17-
18----
19-
20-## Behaviour Changes
21-
22-### What stays the same (user-visible)
23-
24-- `@agent-name` in a prompt delegates to a custom agent — same syntax, same config format
25-- Custom agent frontmatter (`model`, system prompt body) is still respected
26-- Custom commands fan out to subagents
27-- Git isolation per subagent is preserved
28-- Token counts are still aggregated and shown
29-
30-### What improves (user-visible)
31-
32-- **Subagents are fully capable** — same system prompt, same tools, same loop as the main agent
33-- **Subagents can spawn subagents** — no artificial nesting limit
34-- **Working directory is always correct** — the subprocess is launched with an explicit `--cwd`
35-- **Ralph mode works inside subagents** — it's just a full session flag
36-- **ESC kills the whole chain** — the interrupt signal propagates to every active subprocess
37-
38-### What gets removed
39-
40-- `execution: inline` on custom commands — this was a workaround for worktree issues which the new model resolves. All commands run as subprocesses. Community configs that used `execution: inline` will fall back to subprocess execution.
41-
42----
43-
44-## Prompt Chain
45-
46-Each mc subprocess assembles its system prompt in this order:
47-
48-1. **Internal prompt** — mini-coder's own instructions (tools, guidelines, date/cwd)
49-2. **Global context file** — `~/.agents/AGENTS.md` (or `CLAUDE.md`)
50-3. **Local context file** — `.agents/AGENTS.md` (or `CLAUDE.md`, or `AGENTS.md` at repo root)
51-4. **Custom agent prompt** — the markdown body from the agent config file (if `--agent <name>` was passed)
52-
53-The **command prompt** (expanded template from e.g. `/review` or a custom command) becomes the first user message — it is not part of the system prompt.
54-
55-Note: the current `loadContextFile` only loads the first file it finds. It must be fixed to load both global and local, composing them in order, so project-level context does not silently shadow global context.
56-
57----
58-
59-## System Prompt: Avoiding Infinite Delegation
60-
61-The current guidelines actively encourage delegation:
62-
63-> "Use subagents for all tasks that require a lot of context..."
64-> "Keep your context clean and focused on the user request, use subagents to achieve this."
65-
66-This causes models to delegate continuously without doing any actual work. The guidelines need to be rebalanced:
67-
68-- **Main agent**: "Use the `subagent` tool sparingly — only for clearly separable, self-contained subtasks that benefit from a fresh context window. Prefer doing the work directly."
69-- **Subagent sessions** (detected via a `--subagent` flag): stronger wording — "You are running as a subagent. Complete the task you have been given directly using your tools. Do not spawn further subagents unless the subtask is unambiguously separable and self-contained."
70-
71----
72-
73-## Communication Protocol
74-
75-The parent needs structured data back from the subprocess. A **dedicated pipe on fd 3** is used — this keeps stdout/stderr free and avoids temp file lifecycle issues.
76-
77-The parent opens the write end and passes it as fd 3 to the subprocess. Before exiting, the subprocess writes a single JSON line:
78-
79-```ts
80-interface SubagentSummary {
81- result: string; // final assistant text from the session
82- inputTokens: number;
83- outputTokens: number;
84- worktreeBranch?: string; // git branch the subprocess worked on
85-}
86-```
87-
88-Merge conflict/blocked status is no longer part of the subprocess result — see Worktrees below.
89-
90----
91-
92-## Output / UI
93-
94-The current subagent output is noisy and not useful. New model:
95-
96-- **On launch**: one line — `⇢ subagent [laneId] — <truncated prompt>`
97-- **While running**: spinner in the parent ("thinking...")
98-- **On completion**: one line — `← subagent [laneId] done (Nin / Nout tokens)`
99-- **Subprocess's own terminal output is suppressed** — the subprocess runs in headless mode (no spinner, no status bar). Its `result` text is returned to the calling LLM via the fd 3 pipe.
100-
101----
102-
103-## Worktrees
104-
105-### Model
106-
107-Every subprocess creates and owns its own worktree:
108-
109-1. Subprocess is launched with `--cwd <parentCwd>`
110-2. Subprocess creates a git worktree from `parentCwd` on a new branch (`mc-sub-<laneId>`)
111-3. Subprocess does its work inside the worktree
112-4. Before exit, subprocess removes the worktree directory and writes the branch name in the fd 3 summary
113-5. Parent receives the branch name, **merges it into its own working tree**, then deletes the branch
114-
115-The subprocess never merges — it only creates and cleans up its own worktree directory. The parent owns all merging. This eliminates the merge-lock complexity inside subprocesses and makes merge ordering deterministic in the parent.
116-
117-### Merge conflicts
118-
119-If the parent's merge produces conflicts, it surfaces them to the LLM as it does today (conflict file list in the tool result). The LLM can resolve them or report to the user.
120-
121-### Non-git projects
122-
123-Unchanged — no worktree is created and the subprocess works directly on the `cwd`.
124-
125----
126-
127-## Interrupt Propagation
128-
129-When the user hits `ESC`:
130-
131-- The parent sends `SIGTERM` to all active subprocess PIDs it is tracking
132-- Each subprocess, on receiving `SIGTERM`, cleans up its own worktree directory (branch is left for the parent to handle or discard), then exits
133-- The parent discards any pending merge for interrupted subagents and cleans up their branches
134-
135----
136-
137-## What Gets Removed
138-
139-| Item | Reason |
140-|---|---|
141-| `subagent-runner.ts` | Replaced by a thin subprocess launcher |
142-| `depth` parameter | No longer needed — subagents are full sessions |
143-| `.filter(tool => tool.name !== "subagent")` guard | Subagents have the full tool set |
144-| Manual `buildSystemPrompt` / `buildToolSet` in runner | Done by the subprocess itself |
145-| Manual model resolution in runner | Passed as `--model` CLI flag |
146-| `execution: inline` in custom commands | Removed — all commands use subprocess execution |
147-| Merge lock in runner | Merges happen in the parent only, sequentially per-lane |
148-
149----
150-
151-## Recursion Cap
152-
153-An env-var based cap (`MC_SUBAGENT_DEPTH`, max 10) is retained as a safety rail against runaway delegation chains. Unlike the old in-process `depth` parameter it is not a first-class concern of the runner — it is a background guard. Subagents that hit the cap receive a clear error. In practice the cap is generous enough that it should never be reached in normal use.
TODO.md+9−3
@@ -70,11 +70,14 @@ error: script "dev" exited with code 1
7070
7171 ---
7272
73-## Usbaility issues:
73+## Audit language to models
7474
75-- **Rewrite subagents as subprocess `mc` sessions** — see `PLAN-subprocess-subagents.md`. The in-process runner is a second-class agent: it guesses paths, can't recurse, breaks Ralph mode, and produces lower-quality output than the main agent. Spawning a real `mc` subprocess fixes all of this in one move while keeping custom agent/command configs fully compatible.
75+I want to improve some aspects of the agents behaviour in mini-coder.
7676
77-- All models: constant reading almost no action, lot's of wasted tokens, using opencode or claude code is a much more action oriented workflow.
77+- More responsible token usage. API costs are escalating in 2026 so it's more important than ever to use as little tokens as possible whithout impacting efficiency.
78+- Evaluate our tools descriptions and wording to make sure they are efficient in token usage and clear to the llm (we see some errors of duplicating code by accident for example).
79+- Evaluate the output of our tools for token usage considerations.
80+- Ensure the system prompts are correct and use up to date wording based on context engineering optimization (check online for latest practices, check opencode, codex and oh-my-pi for context)
7881
7982 ---
8083
@@ -92,6 +95,8 @@ error: script "dev" exited with code 1
9295 Let's clean things up:
9396
9497 - `/review` command should use the same code as a custom-commands, consolidate the two. We can create the global `/review` command in `~/.agents/commands` at app start if it doesn't exist. That way it can be a pure custom command and the users are encouraged to edit it for their own custom reviews. Never overwrite the file if it exists. Print a line notifying the user that the command was created.
98+- Ensure we are correctly implementing commands, skills and agents. Use the claude code and opencode documentation online to audit our implementations, identify gaps and inconsistencies. We should support both of these types of configs, as well as our .agents.
99+- Now that we have subagents as subprocesses, let's review how it impacted these features.
95100
96101 ---
97102
@@ -109,3 +114,4 @@ We need to do research first, but maybe we can leverage the hooks feature to ach
109114
110115 - model-info: in `resolveFromProviderRow`, when canonical capability exists but `contextWindow` is null, fall back to provider row context (`capability.contextWindow ?? row.contextWindow`).
111116 - Worktrees share bun lockfile and node_modules. Question this choice, is this really a good idea, or just an opportunity for things to go wrong?
117+- `subagent-runner.ts`: `Bun.file(proc.stdio[3] as unknown as number).text()` — the double-cast signals a type mismatch. Investigate whether `new Response(proc.stdio[3]).text()` is more correct and whether the current form breaks silently across Bun versions.