Repository navigation
Description
Paths updated after #56 merged (2026-10-06). Sources now live in
packages/;plugins/sage/is build output (never edit it;npm run checkfails on a hand edit). Hook:packages/sage-claude/hooks/sage-hook.mjs. State tool logic:packages/sage-core/state.mjs(the Claude wrapper ispackages/sage-claude/skills/sage/sage.mjs). Skills and agents:packages/sage-claude/skills/,packages/sage-claude/agents/. Line numbers in this issue are from before the move.
Task: T181, step 1 of 4 (the lead build) · large · risk flag: auth (needs 2 clean review cycles)
Where this fits
The owner decided that every pull request gets its own lead: a background Claude Code subagent (sage:lead) that the sage starts for one task. The lead starts its own implementer, reviewers and QA as nested agents, runs the review cycles and repair rounds, and reports once to the sage. The lead never merges and never asks the user. The build has four steps, each its own pull request:
- This issue: nested spawn rules in the hook.
- The state tool learns the lead role: a lead writes only its own task's rows.
- The hook's write list for leads (what a lead may run with the state tool).
- The
sage:leadagent file and the docs.
Owner limits (decision G81): at most 3 leads per project; each lead runs at most 3 children at once; the project's agent cap (cap.<project>, else max_agents) still holds, and the lower limit wins. There is no total limit across projects as a design rule (cap_total stays as a temporary fuse).
What a spike found (the reason for this step)
In packages/sage-claude/hooks/sage-hook.mjs (about line 201), the brief check and the agent cap run only when main is true, that is for a spawn by the main session. A live test showed that a subagent could start a sage:qa agent with a one-word prompt: no brief check, no cap. The Claude Code hook docs say that agent_id and agent_type are present on every hook event inside a subagent, also a nested one, so the hook can tell who spawns.
Goal
The hook applies the spawn rules to every spawn in sage mode, not only the main session's:
- Brief check and cap for every spawn of a sage agent type (
sage:*), by the main session or by any agent, with the same refusal texts. - Only the main session starts a lead: a spawn of
sage:leadby any agent is refused. - Only a lead starts agents: an agent whose type is not
sage:leadcannot start any agent (any type, not onlysage:*), with a refusal that says to report to the sage instead. - A lead starts only its team:
sage:implementer,sage:code-reviewer,sage:security-reviewer,sage:ux-reviewerandsage:qa, at most 3 at once per lead. A third layer (a child of a lead's child) is refused by rule 3. - At most 3 leads per project, inside the project cap: every running agent, leads and their children, takes one slot of the project cap; the lower limit wins.
Scope
packages/sage-claude/hooks/sage-hook.mjs: the PreToolUse branch for the agent tools (AGENT_TOOLS, about line 201) and the slot store (slots:take,bind,release,reconcile). A child's slot must record its parent lead (the spawning event'sagent_id), so the per-lead count and the release onSubagentStopwork. Keep the hook's existing rules (the main session never edits files; the merge and push rules; the agent rules).- Tests in
scripts/sage-hook.test.mjs: events withagent_idandagent_typefor a lead, a child and a grandchild; the refusal texts; the per-lead and per-project counts, also after aSubagentStopand aPostToolUseFailureof the agent tool. - The hook's header comment and the README's "Rules held in code" table: one line each.
Not in scope
The sage:lead agent file (step 4), the state tool (step 2), the lead's write list (step 3). Do not change packages/sage-core/state.mjs in this step.
Acceptance
- Each rule above has a test that fails on
mainand passes on the branch. - The main session's existing spawn behaviour and refusal texts are unchanged.
npm run build,npm run check,npm testpass.- The pull request says what is not verified: the sage checks the rules live in a Claude Code session with nested agents before step 2 starts (you cannot run Claude Code subagents from Codex).
How this hand-off works
- This issue is a task of sage, the agent kit in this repository. The sage keeps its own record of the task (its logbook) under the id in the title.
- Work on a new branch named
codex/<task id in lower case>-<short name>, for examplecodex/t199-brace-words. - Open a pull request whose title ends with the task id in parentheses, for example
(T199). Start its body withCloses #<this issue>andSage task <id>. - The sage then runs its reviews (code, security when the task has a risk flag, and QA) and merges when the review cycles are clean. Never merge, never push to main, never force-push.
- In the pull request body, give the evidence: the commands you ran and their last lines (the test counts), and say what you did not check.
Rules for every sage task
- Read
AGENTS.mdfirst. Edit only sources; never edit a generated file (a skill marked "Generated", orinstructions/core.md), and never editupstream/pstack/by hand. - Run
npm run build, thennpm run checkandnpm test. All must pass. The full test run can take over 5 minutes. - A rule that matters goes into code with a test. Show that each new test fails on
mainand passes on your branch: check outmainin a separate worktree (git worktree add --detach <tmp> origin/main), never withgit stash. - Never let any code you run read or signal the real process list. Put a fake
ps,pgrepandkillfirst onPATHfor every test run. - Never pass a test string to a real shell (bash, zsh, sh, eval,
child_processwithshell: true). Attack strings go to the hook's parser only. - A flaky test is a bug: fix it or remove it in the same task. Never re-run a test until it passes. No assertion on wall-clock or CPU time unless it has a wide margin and a reason in the test.
- The README graphics come from
scripts/graphics.mjs(npm run graphics); never edit an SVG indocs/assetsby hand. - Write text for people at about 80% of Simplified Technical English (
writing/ste-80.md), with the approved words ofwriting/dictionary.md. - Stop at a product question: write it in the pull request with your recommendation instead of guessing.
Activity
erickb336 commentedon Oct 6, 2026
Design document: the lead-per-PR loop (T181)
This is the text of the sage's design page for the lead build (design A), written 2026-10-06 before the build. The page itself is an HTML file in the sage's local logbook; its flow diagram is not included here.
Updates since the page was written (these win over the page):
cap_totalis only a temporary fuse. The lower of the project cap and the lead limits wins.Lead per PR loop
Design page R654 for task T181, 2026-10-06. Design only: nothing here is built. Sample data is marked SAMPLE.
The lead-per-PR loop (design A)
What this is: the full design of how one PR gets one lead agent, from the framed task to the merge. It names who acts at each step, what you see in chat, every limit, every edge case and every logbook write. What I need from you: approve the flow, and answer the 3 open questions at the end (each has a recommendation).
Where it fits. You decided on 2026-10-06: every PR gets its own lead, and the lead is a background subagent that the sage starts (design A, research R649). Spike R653 proved that a background lead can start children and gets their completion notices. This page is the design that the build task (T181) will follow. Next: the PE checks it, then the build. Naming ("lead") waits for T114; the word is a placeholder here.
1 Flow2 Who acts3 What you see4 Lead report5 Questions loop6 Limits7 Edge cases8 Logbook writes9 Must fix first10 Open questions11 Rejected
1. The flow, from framed task to merged PR
Each row is one actor. Read left to right. Blue boxes run inside the lead; the sage sees only the lead's start and its report. Dashed arrows are the side paths (a product question, a repair round).
Owner
Sage (main session)
Lead (one per PR)
Implementer
Reviewers + QA
1 Requestin chat
2 Frame taskproduct questionslarge: design, PE, OK
3 Start leadrun add --role leadname lead-T181
4 Brief implementerrecords the run
5 Build, checksworktree, push, PR
6 Start cycle nall roles, in parallel
7 Review, QAon the head SHA
8 Record, triageverdicts, findingsclean cycles reached?
Round: repair, re-run
9 Reportready, held, question
10 Mergemerge-tree (order 24)merge-check, thenmerge --match-head
11 Sees result2-3 lines + link
Answers a questionone gate, with a default
yes
fresh lead with the answer
via the sage
repair commit: cycles start again at 1
Investigate tasks have no PR, so they get no lead: the sage runs them as today. For a large task, the sage keeps the design, the PE check and your approval of the design; the lead starts at the build.
2. Who acts at each step
| # | Step | Who acts | What happens | Logbook write by
| 1 | Request | owner | You ask in chat. | none
| 2 | Frame | sage | Frames the task and its route. Asks all product questions in one batch. A large task: design, PE check, your approval. | sage: task add, gate add, log
| 3 | Start lead | sage | Records a lead run. Starts one background sage:lead with a full brief and the name lead-T. The brief gives the target: verified (autopilot off) or merge-ready (autopilot on). | sage: run add --role lead
| 4 | Brief implementer | lead | Records the run. Starts the implementer with a full brief (the hook checks it). | lead: run add, task set state=building
| 5 | Build | implementer | Builds in its worktree, runs the checks, pushes, opens the PR. Never merges. | none (agents never write)
| 6 | Cycle | lead | Starts every role of the route on the head SHA, in parallel, as background children. | lead: run add, task set pr= branch=
| 7 | Review, QA | reviewers + QA | Each reports with the seven fields. | none
| 8 | Record, triage | lead | Records each report, finding and verdict. Fixes or dismisses lows with a reason. Starts a round for a medium or high finding. Runs the clean cycles that the target needs. | lead: run done, finding add, verdict, round
| 9 | Report | lead | Ends with one report: ready, held, question or failed. It must not end while a child runs. | lead: task set state=verified
| 10 | Merge | sage | Autopilot on: merge-tree against every other PR in review (order 24), merge-check, merge with --match-head-commit. Autopilot off: tells you the PR is ready. | sage: run done (the lead's run), task set state=merged, finding move, log
| 11 | Result | owner | Sees a few lines and the link (section 3). | none
3. What you see in chat, per PR event
Target: 1 to 3 lines per event, 3 or 4 events per PR. The cycles, the rounds and each agent's report stay out of the chat; they are in the logbook and the pages folder. Today a PR such as PR 47 put about 26 briefs and 26 reports through the chat (R649).
| Event | When | Example in chat SAMPLE
| Started | The sage starts a lead. | T181 started. A lead builds the lead agent and the hook rules. Next you hear from it at a question or at the end.
| Question | A lead ends with STATUS question. | T181 needs you (G71). When the cap is full, should the refusal name the other project's agents? (a) yes (b) no, only the count. I recommend a. Default a if you do not answer.
| Ready | The lead reports ready (autopilot off). | T181 · PR 52 ready. 1 clean cycle on a1b2c3d, 1 repair round (2 findings fixed, 1 moved to T190). Screenshot: pages/T181/hook-deny.png. Not verified: a real 3-layer run. You merge: PR 52.
| Merged | Autopilot on, the sage merged. | T181 · PR 52 merged after 2 clean cycles. PR 52. Agent time 2.6 h, 3.1 M tokens.
| Held or failed | Max rounds, or 2 lead restarts failed. | T181 · PR 52 held after 3 rounds: QA still fails on the cap test. (a) replan (b) one more round (c) drop. I recommend a.
| Restarted | The sage restarts a lead after a crash or a new session. | T181 lead restarted (the last one stopped with no report). It goes on from round 1, cycle 2.
4. What the lead's report to the sage holds
The lead uses the same seven fields as every agent (the hook checks them). What changes is what each field holds. Size: about 1,500 tokens or fewer; the detail stays in the logbook.
| Field | The lead puts here
| STATUS | done (ready), blocked (held, or a limit), question, or failed.
| RESULT | One line: ready verified, ready to merge, held or question, with the PR, the full head SHA and the clean cycles on it. Then what you can now do or see. Last line: Left: what is not done (for example "cycle 2 when autopilot turns on").
| EVIDENCE | The run ids and their verdicts by SHA and cycle; the merge-check output on the head SHA; the paths of screenshots and pages. Not the children's full reports.
| FINDINGS | Only what the sage must act on: a finding to move to a follow-up task (the lead cannot frame tasks), a medium or high finding the lead wants dismissed, and a high finding still open.
| QUESTIONS | Each product question, with options, a recommendation and a default. The lead never asks you itself.
| NOT VERIFIED | What no child checked, from the children's reports, merged into one list.
| BRANCH | The branch, the head SHA, the worktree and the PR link.
5. Questions: how a lead's question reaches you, and the answer gets back
A subagent has no way to ask you directly. So a question always ends the lead, and the answer always starts a new one.
Lead waits for its children,ends: STATUS question
Sage: run done --status questiongate add (options, default)
Owner answersa choice, in chat
Sage: gate answer, log,run add --role lead
Fresh lead: original brief,earlier report, the answer;reads state from the logbook
Other leads keep running while one waits for you. The sage groups questions that arrive close together into one message. The open question Q3 asks if a resume by name is better than a fresh lead.
6. Limits
| Limit | Rule | Why | Today
| Leads at once | cap.leads per project, default 2 (Q1). The sage starts a lead only when a lead slot is free; other tasks wait in order. | Each lead costs its own context, and your attention at the end. | No such limit.
| Children per lead | At most per_lead = 3 children at once (one cycle: code review, security review, QA). A UX review waits for a free child slot. | The project cap is then cap.leads × per_lead, so a lead never waits for another lead's children: no lead can starve. | None for nested spawns (F1).
| Agent cap | Every lead and every child holds one slot of the project cap and of cap_total (12 across projects). With the defaults: 2 leads + 6 children = 8. | One count for all sage agents, fail closed. | Nested spawns take no slot (F1).
| Cap full | The hook refuses the spawn. The lead waits for a child's completion notice and tries again. A lead with no running child ends with STATUS blocked "cap"; the sage restarts it later. | A lead cannot sleep; it can only wait for a notice. | -
| Brief check | Every spawn of a sage: agent, by the sage or by a lead, needs all ten brief fields. | The children of a lead get the same brief quality as today. | Nested spawns skip it (F1, proof A1 in R649).
| Who may start what | Only the sage starts a sage:lead, and only with the name lead-T of a task with a running lead run. A lead starts only the implementer, the three reviewers and QA. A child starts no agent. Any other spawn by a lead or a child is refused. | No lead of leads, no third layer, no general-purpose helper that writes the logbook. | Not checked.
| Merge | Only the sage (the main session) merges. The hook refuses a merge command from any agent. | Order 24 needs the view across all PRs. | An agent's merge passes when autopilot is on and merge-check passes (F5).
| Slots of dead agents | A child's slot records its lead. The sage's Stop reconcile frees a child's slot only at its own stop, at its lead's end, or after the 1-hour lease. | The reconcile may not list nested agents (F2). | The reconcile reads only the main session's tasks.
| Rounds and restarts | max_rounds (3) as today. A lead restarts at most 2 times per task; the third failure holds the task. | Fail closed; no endless restarts. | -
7. Edge cases
| Case | What happens | Who | You see
| A lead dies or times out | The sage gets a failed notice, or no notice before the lead's budget ends. It records the lead run failed, reads the task's state from the logbook (round, open findings, verdicts, branch), and starts a fresh lead with "go on from here". The new lead first closes the dead lead's open child runs as failed, then uses the same worktree and branch. After 2 restarts: held. | sage, then lead | "restarted" line; "held" after the 2nd restart.
| Two leads touch the same file | Each PR has its own worktree and branch, so the leads never share a file on disk. The overlap shows at the merge: before each merge the sage runs git merge-tree against every other PR in review (order 24). If a merge would make another PR conflict, the sage merges that one first, or accepts the extra merge-main round. | sage | Nothing, unless a round is added: then one line.
| A lead hits max rounds | sage round says held. The lead stops starting agents and ends with STATUS blocked, RESULT held, and its view of the cause. The sage parks a gate: replan, one more round (config), or drop. | lead, then sage, then owner | "held" line with options.
| You send a note for a PR | You tell the sage. A note that does not change the brief: the sage sends it to the running lead by name (SendMessage) and logs it. A note that changes the scope or the acceptance: the sage stops the lead (TaskStop), logs the decision, and starts a fresh lead with the new brief and the earlier report. | sage | One line: "sent to the T181 lead" or "restarted T181 with your change".
| Autopilot is off | The lead's target is verified: 1 clean cycle. It reports ready. The sage tells you; you merge. If you turn autopilot on later, the sage starts a lead for the remaining cycles on the same SHA, then merges. | lead, sage | "ready" line with the PR link.
| Autopilot turns off while a lead runs | The lead finishes its target. The sage does not merge (the hook refuses it anyway). | sage | "ready" line.
| A repair after the sage merged main | Another PR merged, and this PR now conflicts or is behind. If the lead still runs, the sage sends it a note; if not, the sage starts a lead for a merge-main round. The implementer merges main into the branch. This is not a repair round (no finding), but the new commit starts the cycles again at 1. | sage, lead, implementer | Only when it adds a round: "T181 needs a merge-main round after PR 51".
| The sage's session ends while leads run | Leads and their children stop with the session (design A). Pushed commits stay; uncommitted work stays in the worktree. At the next sage session, sage status shows the lead runs still running. The sage marks them failed ("session ended") and restarts each lead, within the restart limit. | sage | "restarted" lines at the start of the next session.
| The sage's context compacts | Leads keep running; their notices arrive after the compaction. The hook gives the sage its instructions again. | sage | Nothing.
| A child of a dead lead still runs | Not known if a child outlives its lead (not tested in R653). The new lead finds the branch's writer run still open; one writer per branch makes run add refuse. The lead closes that run as failed and starts a new one. | lead | Nothing.
| A lead or a child tries to merge, or to start a lead | The hook refuses (section 6). | hook | Nothing; it shows in the lead's report if it matters.
8. Logbook writes
How the hook tells a lead's write from an agent's
The sage records run add T181 --role lead, then starts the lead with the name lead-T181.
At that spawn, the hook checks the name against a running lead run of that task, and writes the task id into the slot's mark.
At SubagentStart, the slot binds to the lead's agent_id (as slots bind today).
When an agent runs the state tool, the hook reads agent_type and agent_id from the event. Claude Code sets them; the agent cannot. Only agent_type sage:lead with a bound slot may write, and only the commands below, and only on its own task (also for run ids and finding keys: the hook looks up their task).
Everything else from an agent is refused, as T83 does today. No slot, no task, an odd command: refused (fail closed).
| Command | Lead, on its own task | Sage | Children
| status, standing, logbook, merge-check, pages | yes | yes | yes (reads)
| run add (implementer, code-reviewer, security-reviewer, ux-reviewer, qa) | yes | yes | no
| run add --role lead; run add for a designer, PE or arena role | no | yes | no
| run done (a run of its task, not its own lead run) | yes | yes | no
| finding add, finding close | yes | yes | no
| finding triage fix; dismiss of a low finding (reason needed) | yes | yes | no
| finding triage dismiss of a medium or high finding; triage ask | no (asks in report) | yes | no
| finding move (frames a new task) | no (asks in report) | yes | no
| verdict (any kind) | yes | yes | no
| round | yes | yes | no
| task set state= building, reviewing, verifying, verified; branch=; pr= | yes | yes | no
| task set state=merged or any other state; task add | no | yes | no
| pages record | yes | yes | no
| gate add, gate answer, log, config, init, standing add, logbook repair | no | yes | no
| any write on another task | no | yes | no
Each write still holds the logbook's lock, so the sage and several leads never write half a file. A lead's engineering defaults go in its report; the sage logs them.
9. What the build must fix first
F1 (high, R649): the brief check and the agent cap apply only to the main session (sage-hook.mjs line 201). Apply both to every spawn of a sage agent, and add the "who may start what" rule.
F2 (medium, R649): the Stop reconcile reads only the main session's background tasks. Children's slots follow their lead (section 6).
F3 (high, R649): T127's origin value "lead" means the Discord bridge's human sage-leads. Rename it (for example "remote") before T181 merges, or the merge check would refuse every autopilot merge of a lead's work.
F4 (R649): "lead" is a word not to say in the dictionary. T114 picks the name; this page and lead.md use it as a placeholder.
F5 (high, new in R654): the merge rule (gitGate, line 439) passes an agent's merge when autopilot is on and merge-check passes. Refuse every merge from an agent; only the main session merges.
F6 (medium, new in R654): T83 (in review) refuses all state tool writes from agents. T181 adds the lead's allow-list of section 8 on top of it, so T83 merges first.
10. Open questions for you
Q1. How many leads at once, per project?
1: one PR at a time. Slow; no merge conflicts between leads.
2 (recommended): 2 leads + up to 6 children = 8 agents. Two PRs move while one waits for you.
3: 12 agents, the whole total cap, so other projects get none.
Cost basis: a lead adds an estimated 0.2 to 0.5 M tokens per PR on top of its runs (R649, no measurement). A PR like T96 took 2.4 h agent time and 3.15 M tokens.
Q2. Which PR events reach your chat?
Start, question, end (recommended): 3 or 4 short lines per PR (section 3).
Only questions and the end: 2 lines per PR; you do not see what runs.
Also each cycle and round: 6 to 10 lines per PR.
Q3. After you answer a lead's question, who goes on?
A fresh lead (recommended) with the original brief, the earlier report and your answer. It reads the state from the logbook. Matches today's rule that a resumed agent drops instructions.
The same lead, resumed by name: keeps its context; cheaper by a few k tokens; lost when the session ends; not tested.
Decisions I took as engineering defaults (say if you want any of them changed): investigate tasks get no lead; the sage keeps design, PE and the design approval; a lead may dismiss only low findings; a lead restarts at most 2 times; a merge-main round is not a repair round.
11. Alternatives considered and rejected
| Alternative | Why rejected
| The lead merges its own PR on autopilot | Order 24 needs the view across all PRs in review; only the sage has it. A merge is also the one step that you cannot undo easily.
| Leads share one project cap with no child limit | Two leads can each hold slots while they wait for more, and neither can finish its cycle. The per-lead limit makes the cap a sum, so no lead starves.
| The lead asks you directly (a teammate, design B) | You decided to talk to leads only through the sage. A subagent also has no AskUserQuestion.
| The hook tells a lead from the brief text (a TASK line) | The brief is text that the sage writes and the lead can quote. The spawn name plus the slot bound to agent_id comes from Claude Code's events, so it is harder to fake, and the name also lets the sage message the lead.
| A new report field "LEFT" | Changes the report skill, the hook's field list and the check for every agent. The last line of RESULT holds it.
Provider note: the loop's rules live in the state tool and the hook (provider-agnostic). Only the spawn mechanics (the Agent tool, nesting, completion notices) are Claude Code's. A later Codex lead could fill the same slot as a process (design C).
erickb336 commentedon Oct 6, 2026
Spike result (2026-10-06): what the hook sees for nested agents
A probe ran three layers: the main session, a child agent, and a grandchild that the child started (foreground and background).
mainis true (sage-hook.mjs, theAGENT_TOOLSbranch). Live: a child startedsage:qawith a one-word prompt, and it was not refused.agent_id?agent_idis "present only when the hook fires inside a subagent call". The live run could not show it, because the session's hook state had sage mode off (fixed by PR #54).session_id?session_id. If a subagent's events carried another id, every agent rule would be off for agents.What this means for step 1: treat every spawn by an agent like the chief's (brief check and cap), as the issue says. Write the code so that the rules do not depend on the open session-id question where you can; say in the PR which rules depend on it. The sage checks both open rows live in a Claude Code session before step 2.
erickb336 commentedon Oct 6, 2026
Draft of the
sage:leadagent file (for step 4, context for step 1)Written with the design page. "lead" is a placeholder name until the naming task picks one. Step 1 implements the hook side of its rules: who may start what, the per-lead limit of 3 children, and the brief check.
Lead run: allow a verified task; refuse only an ended one (T266)
Lead build step 2: the state tool learns the lead role (T266) (#123)
Lead build step 3: the hook's write list for leads (T273) (#124)