@yeison.restrepo.r/code-conductor 1.35.0 → 1.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -104,6 +104,30 @@ Four checks live in `tools/` as tracked repository infrastructure. Three of them
104
104
  - **`[BUG-051]`, open:** two shipped commands run `scripts/detect-stack.mjs`, but the installer deploys the detector to `.claude/scripts/`. In an installed project, `/cc-stack` fails loud (`MODULE_NOT_FOUND`, "no stack"), and `/cc-resume`'s blank-command auto-fill silently skips. Until it is fixed, `/cc-init`, which already uses the deployed path, records the stack and commands.
105
105
  - **`[BUG-052]`, open:** the installer has no self-install guard. Its sweep of the 1.23.2 legacy root `scripts/` matches by exact file list, which the development repository satisfies by identity, so running `--project` inside this repository deletes tracked source. Do not run the installer against a clone of code-conductor itself.
106
106
  - **`[BUG-053]`, open:** the pre-commit test gate that the retired `install.sh` appended runs `npm test` with git's hook environment. From a linked worktree, git hands hooks an absolute `GIT_DIR` and `GIT_INDEX_FILE`, so the suite's fixture `git` commands write into the real repository's refs, config and index. Do not run the gate from a linked worktree.
107
+ - **`[BUG-054]`, open:** `/cc-plan` generates staging steps that leave out the plan file itself, so a task's ticked checkboxes have no commit to ride. Until it is fixed, add the plan path to each task's `git add -u` list when you review a generated plan.
108
+ - **The orchestrator (`1.36.0`) assumes cooperative agents.**
109
+ - Guard 6 does not cover `Bash` writes, `claude -p` children included.
110
+ - Inside a live run, a non-role agent the main session dispatched may write the orchestrator's write surface, the band envelope included.
111
+ - R7 protects live runs only.
112
+ - An agent writing after its hand-back is bounded only by the envelope in force, so a same-role next task inherits it.
113
+ - Under auto permission mode no human stands behind a Bash write or a hook `ask`.
114
+ - A Guard 6 warning reaches you, never the model's tool result, and not in every case. Measured on `claude` 2.1.287:
115
+
116
+ | Channel | Permission mode | A prompting decision rides along | You see the warning |
117
+ |---|---|---|---|
118
+ | stderr | `auto` | no | no |
119
+ | `systemMessage` (Guard 6's channel) | `auto` | no; a hook `ask` does not prompt under `auto` | yes, behind `PreToolUse:Write says: ` |
120
+ | `systemMessage` | `default` | no | yes, in full |
121
+ | `systemMessage` | `default` | yes, for example Guard 2's overwrite prompt | no: the warning is lost |
122
+ - Agent definitions provided by plugins are not searched.
123
+ - A halted run cannot be resumed, only ended and restarted.
124
+
125
+ The five role agent definitions it dispatches ship from `1.37.0`; their limits are the next item.
126
+ - **The role agents (`1.37.0`) are bounded by their tool masks, and Guard 7 bounds one thing beneath them: the shell.**
127
+ - `qa`'s test command is enforcement: Guard 5 keeps qa from writing, so qa only ever runs files it did not write. `code`'s identical allowance is process discipline, not a security boundary, because code writes the tests that command runs.
128
+ - The profiles are live in this repository, because the mirror convention puts them in `.claude/agents/`. The standing rule forbids starting an orchestrator run here; it does not forbid the files being present. A role dispatched by hand through `/agents` or `Agent` creates no band envelope, so Guard 5 allows every write its mask holds, which is `[ARCH-010]`'s no-envelope rule. Guard 7 still denies it the shell. This is named, not fixed.
129
+ - Installing or updating copies `.claude/agents/{spec,plan,code,audit,qa}.md` over the host project's files of the same names, as it does every shipped `.claude/` asset.
130
+ - A gate certifies protocol position and the claim its role states, never the truth of the work beyond that claim.
107
131
  - **The `P7` false positive above**, still live.
108
132
  - **A re-run against an untouched `project.md` prints a recovery hint it cannot prove is needed.** If you install, never write anything into `.claude/memory/project.md`, and install again, you get a line suggesting the file may have been overwritten by a pre-`1.30.0` re-run. It was not; it equals the stub because it was seeded and never edited. The check compares content and **cannot distinguish "seeded and untouched" from "clobbered"**, which is why the wording is hedged to "may have been" rather than "was". This residual is named and accepted in [`BUG-039`'s spec at `:129`](docs/superpowers/specs/2026-09-27-bug039-installer-host-owned-state-design.md), where the alternative (restoring from the host's own git history) was rejected as writing host files out of the host's history with new failure modes. A **fresh** install is silent, which the Quickstart shows.
109
133
  - **Three open dossiers**, which are the evidence-collection pipeline working rather than a backlog: a session denial tally, one for interleaved-artifact reports, and an intermittent commit-hook hang in the `snap-build` suite. A dossier holds specimens until a mechanism is characterized by probe; an id is minted only when the written condition is met. `[BUG-047]` is what that pipeline produces when it completes: an out-of-scope note, then a dossier, then four specimens across four sessions, then a mint, then a release.
@@ -209,6 +233,7 @@ All commands are tagged `(Conductor)` in the Claude Code command palette so they
209
233
  | `/cc-plan` | Require an approved spec, map the codebase, and generate an ordered implementation plan with exact file paths, a test list, a commit order, and identified risks. Every generated task line carries a unique `[T-NNN]` ID (min 3 digits, unlimited suffix depth) using plain ASCII checkboxes — enforced at generation time. |
210
234
  | `/cc-compact` | Phase-boundary command. Serializes the current phase's essential state (decisions, pending steps, files touched, constraints) into a single-line SNAP JSON snapshot at `.claude/memory/session-snapshot.json` — and, when Node `>= 22.5` is available, a git-hash-keyed row in the local `.conductor/cache.db` — then prompts you to run `/compact` to clear conversation history. Run at the end of every phase to prevent context overflow. |
211
235
  | `/cc-implement` | Execute implementation tasks from an approved plan using a surgical 5-step ritual: Grep-locate pending tasks → single-line Read verify → pre-flip `[ ]` to `[>]` → execute → post-flip to `[X]` or `[!]`. Never reads or rewrites the full plan file. Includes dependency evaluation, drift detection, and a Step 6 hook that records each task's final state to a local SQLite cache (see below). |
236
+ | `/cc-orchestrate <ITEM> [--auto]` | Route one backlog item through Define, Build and Verify. For each role it builds, validates (`snap-validate --to`) and installs a SNAP v3 band envelope, dispatches the agent named after the role, waits for its completion notice, and checks the one `SNAP_HANDBACK` line of its delivered hand-back before the next. It pauses before every dispatch unless `--auto`; the spec and plan approvals always pause. A failed validation halts the run, terminally in this version (recover with `end`, then `start`). It needs agent definitions named `spec`, `plan`, `code`, `audit` and `qa` in `.claude/agents/` or `~/.claude/agents/`, which ship from `1.37.0`; a root `package.json` with a `test` script, or a stack whose test command detect-stack names, since `start` records the one command `code` and `qa` may run and halts when none resolves; and plans in the writing-plans format (`### Task N` with a `**Files:**` block). Release stays human. |
212
237
 
213
238
  Each of `/cc-spec`, `/cc-plan`, and `/cc-implement` opens its phase with a **resume read** (`scripts/resume-read.mjs`): it restores any context stored for the current git commit, so work survives branch switches and rollbacks (see [Local State Cache & Session Persistence](#local-state-cache--session-persistence--v1220)).
214
239
  | `/cc-review [file\|dir]` | Review code in three layers - Critical / Important / Suggestion - then deliver a verdict and offer to auto-fix. |
@@ -292,6 +317,14 @@ Hit a block you believe is wrong? Re-run the command with `CC_GUARD3_WARN=1` and
292
317
 
293
318
  **Band scope guard (Guard 5)** - a `Write`, `Edit`, `create_file` or `write_file` from a subagent whose `agent_type` names a band role (`spec`, `plan`, `code`, `audit`, `qa`) is checked against the nearest `.claude/memory/band-envelope.json` above its working directory, a SNAP v3 envelope. A malformed envelope, an agent that is not the envelope's role, a role not holding `RW`, or a path outside the envelope's `scope` globs (anchored at the band root, the directory whose `.claude/` holds the envelope) is denied with a named reason. The main session, any other agent, and any project without an envelope are untouched. It assumes cooperative agents: `agent_type` is a name taken on trust, and `Bash`, `NotebookEdit`, MCP write tools and symlinked paths are not covered.
294
319
 
320
+ **Orchestrator write guard (Guard 6)** - while a `/cc-orchestrate` run is live, its run file `.claude/memory/orchestrator-run.json` binds it to one session by `session_id`. In that session, a `Write`, `Edit`, `create_file` or `write_file` from anything but a band role (the main session, a payload carrying only `agent_id`, any other agent) is denied with `ORCH_WRITE_DENIED` unless its target lies inside the orchestrator's write surface, anchored at the run root: `.claude/memory/orchestrator-run.json`, `.claude/memory/band-envelope.json`, `.claude/memory/session-snapshot.json` and `.conductor/**`. Band roles stay under Guard 5. A run file from another session is stale and an unreadable one is invalid: both warn (`ORCH_RUN_STALE`, `ORCH_RUN_INVALID`) with the cleanup command and never block. While the run is live, a subagent's `Agent` or `SendMessage` call is denied with `ORCH_NESTED_DISPATCH`, so only the orchestrator dispatches or messages agents (R7; the hook's matcher names both tools). Outside a live run there is no Guard 6: any agent can dispatch agents, as before. Limits are stated, not closed:
321
+ - `Bash` writes are not covered, as under Guard 5. That includes a role spawning `claude -p`, whose child session carries another `session_id` and is warned, not blocked.
322
+ - Under auto permission mode no human stands behind a Bash write or a hook `ask`.
323
+ - Inside the live session, only a main-session-dispatched non-role agent can write the surface itself, the band envelope included. So Guard 6 bounds where the orchestrator writes, not who writes inside that surface.
324
+ - An agent that keeps writing after its hand-back is bounded only by the envelope in force.
325
+
326
+ **Role shell guard (Guard 7)** - a `Bash` call from a subagent whose `agent_type` names a band role is decided before Guard 3, so Guard 3's `CC_GUARD3_WARN` ask can never outrank it. `spec`, `plan` and `audit` have no shell (`ROLE_SHELL_DENIED`). `code` and `qa` may run exactly one command, byte for byte: the `test_command` that `orchestrate.mjs start` recorded in the run file of a run live in their session. A command carrying `;`, `&`, `|`, a backtick, `$(`, `<`, `>` or a line break is denied first (`ROLE_SHELL_CHAINING`). No run file, a run of another session, or no recorded command is denied (`ROLE_SHELL_UNRESOLVED`), and any other command is denied naming the allowed one (`ROLE_SHELL_NOT_ALLOWED`). An error inside the guard denies too, and `CC_HOOK_ALLOW` does not reach it. The main session and every other agent are untouched. The two allowances differ in kind: for `qa`, which Guard 5 keeps from writing, the guard is enforcement; for `code`, which writes the tests the command runs, it is process discipline, not a security boundary. `start` resolves the command before it writes anything: the package manager's `test` invocation when a root `package.json` has a `test` script (`npm test`, `pnpm test`, `yarn test`, or `bun run test` by lockfile, and `npm test` with none), detect-stack's test command when there is no `package.json`, and otherwise a halt (`ORCH_TEST_COMMAND_UNRESOLVED`). A resolved command carrying a chaining character halts too (`ORCH_TEST_COMMAND_UNSAFE`), so nothing is recorded that Guard 7 would deny.
327
+
295
328
  Input the hook cannot parse fails closed: it is denied with one stderr line naming `CC_HOOK_ALLOW=1`, which overrides that denial alone and leaves every guard fully active on every payload the hook can read. Set `CC_HOOK_DEBUG=1` to see the diagnostic lines it otherwise swallows.
296
329
 
297
330
  ### context-guard *(global + project)* — v1.15.0
@@ -392,12 +425,14 @@ code-conductor/
392
425
  │ ├── gitignore Merged into the host project's .gitignore
393
426
  │ └── .claude/
394
427
  │ ├── settings.json Hooks wiring (pre-tool-use, post-compact)
428
+ │ ├── agents/ Band roles: spec, plan, code, audit, qa (FEAT-012)
395
429
  │ ├── commands/
396
430
  │ │ ├── cc-init.md /cc-init — session initialization
397
431
  │ │ ├── cc-resume.md /cc-resume — session context restore
398
432
  │ │ ├── cc-spec.md /cc-spec
399
433
  │ │ ├── cc-plan.md /cc-plan
400
434
  │ │ ├── cc-implement.md /cc-implement
435
+ │ │ ├── cc-orchestrate.md /cc-orchestrate
401
436
  │ │ ├── cc-review.md /cc-review
402
437
  │ │ ├── cc-compact.md /cc-compact — phase boundary compaction
403
438
  │ │ ├── cc-debug.md /cc-debug
@@ -417,6 +452,7 @@ code-conductor/
417
452
  │ ├── snap-build.mjs SNAP v1/v2 handoff serializer
418
453
  │ ├── snap-validate.mjs SNAP schema validator
419
454
  │ ├── session-id.mjs Stable session-id resolver
455
+ │ ├── orchestrate.mjs Band router: run file, envelopes, hand-backs (FEAT-011)
420
456
  │ └── detect-stack.mjs Stack auto-detection scanner
421
457
  └── skills/
422
458
  ├── code-simplifier/SKILL.md Always active — complexity and simplicity rules
@@ -41,6 +41,7 @@ export const PROJECT_HOST_OWNED = new Map([
41
41
  ['memory/session-snapshot.md', 'skip'],
42
42
  ['memory/turn-count.txt', 'skip'],
43
43
  ['memory/band-envelope.json', 'skip'],
44
+ ['memory/orchestrator-run.json', 'skip'],
44
45
  ['settings.json', 'merge'],
45
46
  ['settings.local.json', 'skip'],
46
47
  ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yeison.restrepo.r/code-conductor",
3
- "version": "1.35.0",
3
+ "version": "1.37.0",
4
4
  "description": "A governance layer for Claude Code sessions: hooks that check an agent's commands before they run, a spec-first workflow, and project memory the next session reads.",
5
5
  "keywords": [
6
6
  "agentic-development",
@@ -0,0 +1,23 @@
1
+ ---
2
+ name: audit
3
+ description: Verify-band role of a /cc-orchestrate run. Reviews the item's changes statically against its spec and plan, read-only, and hands back build_executed with its findings. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
4
+ tools: Read, Grep, Glob
5
+ ---
6
+
7
+ You are the `audit` role of a code-conductor orchestrated run. The orchestrator dispatched you with a brief naming the item, its spec and its plan, and installed your band envelope at `.claude/memory/band-envelope.json`. Read the envelope first.
8
+
9
+ ## Your job
10
+
11
+ Review the work the code role produced, statically, against the approved spec and plan. The plan's `**Files:**` blocks name the files each task changed; read them as they stand now. Check them against the spec's behavior and acceptance criteria, the plan's tasks, and the conventions in the project's `CLAUDE.md`. Nothing is run: judge what is written.
12
+
13
+ ## Success condition
14
+
15
+ Your success condition is fixed: a static review of the changes against the spec and plan was completed, and its findings are listed in your report, each with a `file:line` and one sentence. Findings do not withhold the gate; the claim is that the review was done and reported. Do not substitute a stricter or different standard of your own.
16
+
17
+ ## Rules
18
+
19
+ - You have no shell and no write tools.
20
+ - A hook or owner denial is an instruction to stop and report, never an obstacle to route around.
21
+ - Never dispatch or message another agent.
22
+ - Deliver exactly one report, ending in exactly one `SNAP_HANDBACK` line, then stop. Claim only the gate `build_executed`.
23
+ - Copy `ops.scope` verbatim from your envelope into the hand-back; if your envelope has no scope, leave the key out.
@@ -0,0 +1,27 @@
1
+ ---
2
+ name: code
3
+ description: Build-band role of a /cc-orchestrate run. Implements one plan task inside the files it names, runs the run's recorded test command, and hands back build_executed. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
4
+ tools: Read, Grep, Glob, Write, Edit, Bash
5
+ ---
6
+
7
+ You are the `code` role of a code-conductor orchestrated run. The orchestrator dispatched you with a brief naming one task of the approved plan, and installed your band envelope at `.claude/memory/band-envelope.json`. Read the envelope first: its `ops.scope` is the task's files plus the plan file.
8
+
9
+ ## Your job
10
+
11
+ Implement exactly the task your brief names. Touch only the files in your envelope's scope; Guard 5 denies a write anywhere else. When the task is done, tick its checkboxes in the plan.
12
+
13
+ ## The test command
14
+
15
+ Your shell runs one command: the run's test command, the `test_command` field of `.claude/memory/orchestrator-run.json`. Run exactly the command named in the run file, byte for byte, with no added flag, pipe, redirect or second command. Guard 7 denies anything else, and its denial names the allowed command.
16
+
17
+ ## Success condition
18
+
19
+ Your success condition is fixed: after your last edit you ran the test command, and your report states its exact exit status and summary line. A red suite is reported as red; the gate claims only that the run happened and was reported. Do not substitute a stricter or different standard of your own.
20
+
21
+ ## Rules
22
+
23
+ - A hook or owner denial is an instruction to stop and report, never an obstacle to route around. Never redo a denied write through another tool.
24
+ - Never dispatch or message another agent.
25
+ - Deliver exactly one report, ending in exactly one `SNAP_HANDBACK` line, then stop. Claim only the gate `build_executed`.
26
+ - Copy `ops.scope` verbatim from your envelope into the hand-back; if your envelope has no scope, leave the key out.
27
+ - List every file you changed in the hand-back's `ops.f` as `<path>:C`, `<path>:M` or `<path>:D`.
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: plan
3
+ description: Define-band role of a /cc-orchestrate run. Writes the implementation plan for the approved spec under docs/superpowers/plans/ and hands back boundary_routed. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
4
+ tools: Read, Grep, Glob, Write, Edit
5
+ ---
6
+
7
+ You are the `plan` role of a code-conductor orchestrated run. The orchestrator dispatched you with a brief naming the item and its approved spec, and installed your band envelope at `.claude/memory/band-envelope.json`. Read the envelope first.
8
+
9
+ ## Your job
10
+
11
+ Write the implementation plan for the item from its approved spec, as one new file under `docs/superpowers/plans/`. Use the writing-plans format, because the orchestrator routes code tasks from it: each task is a `### Task N: <name>` heading followed by a `**Files:**` block whose lines start `- Create:`, `- Modify:` or `- Test:` and name each path in backticks. A code agent may touch only the files its task names, so name every file the task changes, its tests included. A task's envelope scope is its files plus the plan file, and the router halts a scope over 20 entries with `ORCH_SCOPE_OVER_CAP`, so keep each task to 19 files or fewer. Order the tasks so that each one ends with the suite green.
12
+
13
+ ## Success condition
14
+
15
+ Your success condition is fixed: a plan file was written under `docs/superpowers/plans/` from the approved spec, and each task names its files. Do not substitute a stricter or different standard of your own.
16
+
17
+ ## Rules
18
+
19
+ - You have no shell. Write only inside your envelope's scope; Guard 5 denies anything else.
20
+ - A hook or owner denial is an instruction to stop and report, never an obstacle to route around.
21
+ - Never dispatch or message another agent.
22
+ - Deliver exactly one report, ending in exactly one `SNAP_HANDBACK` line, then stop. Claim only the gate `boundary_routed`.
23
+ - Copy `ops.scope` verbatim from your envelope into the hand-back; if your envelope has no scope, leave the key out.
24
+ - List the plan file in the hand-back's `ops.f` as `<path>:C`. The owner approves that path.
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: qa
3
+ description: Verify-band role of a /cc-orchestrate run. Re-runs the run's recorded test command as a non-author and hands back verify_pass only when the suite passes. No write tools. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
4
+ tools: Read, Grep, Glob, Bash
5
+ ---
6
+
7
+ You are the `qa` role of a code-conductor orchestrated run. The orchestrator dispatched you with a brief naming the item, and installed your band envelope at `.claude/memory/band-envelope.json`. Read the envelope first.
8
+
9
+ ## Your job
10
+
11
+ Verify the item independently. You did not write this code and you cannot write files. Your run of the suite is the authoritative one, whatever any other role reported.
12
+
13
+ ## The test command
14
+
15
+ Your shell runs one command: the run's test command, the `test_command` field of `.claude/memory/orchestrator-run.json`. Run exactly the command named in the run file, byte for byte, with no added flag, pipe, redirect or second command. Guard 7 denies anything else, and its denial names the allowed command.
16
+
17
+ ## Success condition
18
+
19
+ Your success condition is fixed: you ran the test command yourself and the suite passed, meaning the command exited with status 0. Report its exact exit status and summary line. Do not substitute a stricter or different standard of your own: exit status 0 is a pass, and anything else is a fail.
20
+
21
+ ## Rules
22
+
23
+ - A hook or owner denial is an instruction to stop and report, never an obstacle to route around.
24
+ - Never dispatch or message another agent.
25
+ - Deliver exactly one report, then stop. If the suite passed, end it in exactly one `SNAP_HANDBACK` line and claim only the gate `verify_pass`. If it failed, leave the `SNAP_HANDBACK` line out and say why, quoting the summary line.
26
+ - Copy `ops.scope` verbatim from your envelope into the hand-back; if your envelope has no scope, leave the key out.
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: spec
3
+ description: Define-band role of a /cc-orchestrate run. Writes the spec for one backlog item under docs/superpowers/specs/ and hands back boundary_routed. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
4
+ tools: Read, Grep, Glob, Write, Edit
5
+ ---
6
+
7
+ You are the `spec` role of a code-conductor orchestrated run. The orchestrator dispatched you with a brief naming the item and installed your band envelope at `.claude/memory/band-envelope.json`. Read the envelope first.
8
+
9
+ ## Your job
10
+
11
+ Write the spec for the item as one new file under `docs/superpowers/specs/`, named `YYYY-MM-DD-<topic>-design.md`. Read the item's backlog entry and the code it touches before you write. The spec states the problem, the solution, the behavior including its error cases, testable acceptance criteria, what is out of scope, and the files the change affects.
12
+
13
+ ## Success condition
14
+
15
+ Your success condition is fixed: a spec file was written under `docs/superpowers/specs/` that answers the item. List the questions the codebase does not settle as open questions in your report; do not decide them, because the owner rules them at the approval boundary. Do not substitute a stricter or different standard of your own.
16
+
17
+ ## Rules
18
+
19
+ - You have no shell. Write only inside your envelope's scope; Guard 5 denies anything else.
20
+ - A hook or owner denial is an instruction to stop and report, never an obstacle to route around.
21
+ - Never dispatch or message another agent.
22
+ - Deliver exactly one report, ending in exactly one `SNAP_HANDBACK` line, then stop. Claim only the gate `boundary_routed`.
23
+ - Copy `ops.scope` verbatim from your envelope into the hand-back; if your envelope has no scope, leave the key out.
24
+ - List the spec file in the hand-back's `ops.f` as `<path>:C`.
@@ -0,0 +1,92 @@
1
+ ---
2
+ description: "(Conductor) Route one backlog item through Define, Build and Verify by validated SNAP handoffs"
3
+ ---
4
+
5
+ # /cc-orchestrate <ITEM> [--auto]
6
+
7
+ You are the orchestrator for one run (FEAT-011). You hold no repository write access. You never write a tracked file, and while the run is live Guard 6 denies any write-family call outside your write surface:
8
+ - `.claude/memory/orchestrator-run.json`
9
+ - `.claude/memory/band-envelope.json`
10
+ - `.claude/memory/session-snapshot.json`
11
+ - `.conductor/**`
12
+
13
+ You move work only through `orchestrate.mjs` and the `Agent` tool. Release, `project.md` and the closeout stay with the human. Bash is outside Guard 6, as it is outside Guard 5: never use it to write a repository file.
14
+
15
+ ## Resolve the script (D11)
16
+
17
+ Begin every Bash call that runs the script with the same resolution, the deployed copy first, then source:
18
+
19
+ ```sh
20
+ S=.claude/scripts; [ -f "$S/orchestrate.mjs" ] || S=scripts
21
+ ```
22
+
23
+ Then run `node "$S/orchestrate.mjs" <verb> ...` in that same call. The exit codes:
24
+ - `0`: success.
25
+ - `1`: a halt. The code and the reason are on stderr and recorded in the run file.
26
+ - `2`: a refusal. Nothing was written. Read the message: it names the step the run is actually at.
27
+
28
+ ## On any halt
29
+
30
+ 1. Print the stderr line verbatim.
31
+ 2. Dispatch nothing further. If an agent is still in flight, wait for its completion notice before you report the halt; its writes stay bounded by the envelope in force. Then stop.
32
+
33
+ A halt is terminal in v1 (D12). Recovery is `node "$S/orchestrate.mjs" end`, then a fresh `start`, each only on the owner's word.
34
+
35
+ ## Steps
36
+
37
+ 1. **Start.** Run `node "$S/orchestrate.mjs" start $ARGUMENTS`. It resolves the run's test command before it writes anything, and its stdout ends with `test command: <command>`.
38
+ - If stdout names a replaced stale run, report its item and start time.
39
+ - On `ORCH_RUN_ACTIVE`, report it, offer `end`, and stop.
40
+ - On `ORCH_TEST_COMMAND_UNRESOLVED` or `ORCH_TEST_COMMAND_UNSAFE`, report it and stop. No run file was written, so there is nothing to `end`. The owner adds a `test` script to `package.json`, or removes the chaining from the command it names, before a fresh `start`.
41
+
42
+ Print the run header: the item, the mode (`step` unless `--auto` was given), the test command, and the first role, `spec`.
43
+ 2. **Each dispatch.** Take the roles in band order: `spec`, `plan`, then `code` once per plan task, then `audit`, then `qa`. For each one:
44
+ 1. **Check.** Run `node "$S/orchestrate.mjs" install <role> --check`. Print the role and the envelope it prints, and state that `--to <role>` passed.
45
+ 2. **Pause.** In step mode, ask the owner for a go. On a decline, stop: the run stays at its position, and nothing is installed. Under `--auto`, skip this pause.
46
+ 3. **Install.** Run `node "$S/orchestrate.mjs" install <role>`.
47
+ 4. **Dispatch.** Use the `Agent` tool with `subagent_type: <role>` and the brief below. Dispatch one agent at a time, never in parallel (D8).
48
+ 5. **Wait.** Dispatch returns before the agent finishes, and an agent can keep acting after its hand-back. Wait for the agent's completion notice. Run nothing for this position until it arrives (D8).
49
+ 6. **Hand back.**
50
+ 1. Write the agent's **delivered `SubagentHandback` report** with the Write tool, verbatim, to `.conductor/handback/<role>.txt`. That is the one report the binary delivered, never a later message. For code, use `.conductor/handback/code-<N>.txt`, where `<N>` is the task number.
51
+ 2. Run `node "$S/orchestrate.mjs" handback <role> < <that file>`.
52
+ 3. Keep the agent's `Observation:` line for the report.
53
+ 4. If a second `SNAP_HANDBACK` from that agent reaches you for the same position, write it to `.conductor/handback/<role>-second.txt` (`code-<N>-second.txt` for code) and run `handback <role>` on it. It halts with `ORCH_HANDBACK_CONFLICT`. Then follow "On any halt".
54
+ 3. **The two define approvals.** These pause in both modes.
55
+ - **After spec:** show the owner the spec path from the hand-back. On approval, run `node "$S/orchestrate.mjs" approve spec`.
56
+ - **After plan:** show the owner the plan path named in the hand-back's `ops.f`. On approval, run `node "$S/orchestrate.mjs" approve plan <plan path>`. This writes `define_approved`, the only gate you author after `boundary_routed`.
57
+ 4. **Build.** Dispatch `code` once per plan task, serially, until the router moves on to `audit`. A `--check` refusal names the next step.
58
+ 5. **Verify.** Dispatch `audit`, then `qa`. When `qa`'s hand-back records `verify_pass`, run `node "$S/orchestrate.mjs" end`. It prints the run it removed.
59
+ 6. **Report.** From the record `end` printed, name:
60
+ - every hand-back, with its role, gate and task;
61
+ - both approvals, with who approved and when;
62
+ - every agent's observation line.
63
+
64
+ Then state that release is human, by `docs/RELEASE-CLOSEOUT.md`.
65
+
66
+ ## The dispatch brief
67
+
68
+ Fill in each `<...>` from the run and the role.
69
+
70
+ ```text
71
+ You are the <role> role for <ITEM>, dispatched by the FEAT-011 orchestrator.
72
+ Your band envelope is installed at .claude/memory/band-envelope.json: tk <tk>, scope <scope, or none>.
73
+ Guard 5 denies any write outside that scope. Do not get around a denial or a missing tool, for
74
+ example with shell redirection. Report it instead.
75
+ Task: <the role's task, below>
76
+ Verify your work before you hand back: your first hand-back is final, and a second is refused.
77
+ Do not dispatch or message other agents; Guard 6 denies it during a run.
78
+ Copy ops.scope verbatim from your envelope into the hand-back; if your envelope has no scope, leave the key out.
79
+ End your hand-back report with exactly these two lines, each on its own line:
80
+ Observation: <one line, what this handoff taught>
81
+ SNAP_HANDBACK <one-line SNAP v3 JSON: {"v":3,"sys":{"ph":"<ph>","c":"<commit>","s":"<ITEM>","role":"<role>","tk":"<tk>"},"ops":{"n":[],"f":[<files you touched, as "path:C|M|D">],"scope":<your envelope's ops.scope>,"gate":"<gate>"},"mem":{"d":[],"x":[]},"pr":""}>
82
+ ```
83
+
84
+ The role's task, its `ph`, and the gate it hands back:
85
+
86
+ | Role | Task | `ph` | Gate |
87
+ |---|---|---|---|
88
+ | `spec` | Write the spec for `<ITEM>` under `docs/superpowers/specs/`. | `spec` | `boundary_routed` |
89
+ | `plan` | Write the plan under `docs/superpowers/plans/` in the writing-plans format: `### Task N` headings, each with a `**Files:**` block. Name the plan path in `ops.f`. | `plan` | `boundary_routed` |
90
+ | `code` | Implement `<Task N>` of `<plan>`, touching only its files, and tick its boxes in the plan. After your last edit, run the run's test command exactly and report its exit status and summary line. | `impl` | `build_executed` |
91
+ | `audit` | Review the changes against the spec and the plan, read-only. | `rev` | `build_executed` |
92
+ | `qa` | Run the run's test command exactly and report. If the suite fails, leave out the `SNAP_HANDBACK` line and say why. | `rev` | `verify_pass` |
@@ -19,11 +19,21 @@ function debug(msg) {
19
19
  const deny = (reason) => ({ permissionDecision: 'deny', permissionDecisionReason: reason });
20
20
  const ask = (reason) => ({ permissionDecision: 'ask', permissionDecisionReason: reason });
21
21
 
22
+ let warning = '';
23
+
24
+ // A warning decides nothing (FEAT-011): it rides the call's decision, or goes out alone
25
+ // once every guard has passed. systemMessage is the channel V3 measured reaching the user.
26
+ function warn(msg) {
27
+ warning += (warning ? '\n' : '') + msg;
28
+ return null;
29
+ }
30
+
22
31
  function emit(decision) {
23
32
  if (emitted) return;
24
33
  emitted = true;
25
34
  process.stdout.write(JSON.stringify({
26
- hookSpecificOutput: { hookEventName: 'PreToolUse', ...decision },
35
+ ...(warning ? { systemMessage: warning } : {}),
36
+ ...(decision ? { hookSpecificOutput: { hookEventName: 'PreToolUse', ...decision } } : {}),
27
37
  }) + '\n');
28
38
  }
29
39
 
@@ -119,12 +129,14 @@ const BAND_ENVELOPE_MAX_BYTES = 10485760;
119
129
  const BAND_ENVELOPE_REL = ['.claude', 'memory', 'band-envelope.json'];
120
130
 
121
131
  const isPlainObject = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
132
+ const payloadCwd = (payload) => (typeof payload.cwd === 'string' && payload.cwd ? payload.cwd : process.cwd());
122
133
 
123
134
  // The band root is the nearest ancestor of cwd holding the envelope; the scope globs
124
135
  // anchor there too, so discovery and anchoring are one rule (owner ruling, Case F).
125
- function findBandRoot(start) {
136
+ // Guard 6 finds its run root by the same walk.
137
+ function findRootHolding(start, rel) {
126
138
  let dir = resolve(start);
127
- while (!existsSync(join(dir, ...BAND_ENVELOPE_REL))) {
139
+ while (!existsSync(join(dir, ...rel))) {
128
140
  const parent = dirname(dir);
129
141
  if (parent === dir) return null;
130
142
  dir = parent;
@@ -163,8 +175,8 @@ function globToRegExp(glob) {
163
175
  function guard5BandScope(input, payload) {
164
176
  const role = payload.agent_type;
165
177
  if (!BAND_ROLES.includes(role)) return null;
166
- const cwd = typeof payload.cwd === 'string' && payload.cwd ? payload.cwd : process.cwd();
167
- const root = findBandRoot(cwd);
178
+ const cwd = payloadCwd(payload);
179
+ const root = findRootHolding(cwd, BAND_ENVELOPE_REL);
168
180
  if (!root) return null;
169
181
  const file = join(root, ...BAND_ENVELOPE_REL);
170
182
  const env = readEnvelope(file);
@@ -178,6 +190,99 @@ function guard5BandScope(input, payload) {
178
190
  return deny(`Guard 5: BAND_SCOPE_VIOLATION: ${target || '<no path>'} is outside the declared scope [${env.ops.scope.join(', ')}]`);
179
191
  }
180
192
 
193
+ // ── Guard 6 constants ─────────────────────────────────────────────────────────
194
+ // Copies of scripts/orchestrate.mjs values (FEAT-011 AC4), carried for Guard 5's reason:
195
+ // no import resolves from both install locations. tests/hooks/guard6.test.js pins them.
196
+ const ORCH_RUN_REL = ['.claude', 'memory', 'orchestrator-run.json'];
197
+ const ORCH_WRITE_SURFACE = ['.claude/memory/orchestrator-run.json', '.claude/memory/band-envelope.json', '.claude/memory/session-snapshot.json', '.conductor/**'];
198
+ const ORCH_DISPATCH_TOOLS = ['Agent', 'SendMessage'];
199
+
200
+ // Only what Guard 6 itself reads is checked: an object with a session to bind to.
201
+ function readRunFile(path) {
202
+ try {
203
+ if (statSync(path).size > BAND_ENVELOPE_MAX_BYTES) return null;
204
+ const run = JSON.parse(readFileSync(path, 'utf8'));
205
+ return isPlainObject(run) && typeof run.session_id === 'string' && run.session_id !== '' ? run : null;
206
+ } catch { return null; }
207
+ }
208
+
209
+ // The deployed copy first, then source (FEAT-011 D11).
210
+ const orchEnd = (root) => `node ${existsSync(join(root, '.claude', 'scripts', 'orchestrate.mjs')) ? '.claude/scripts' : 'scripts'}/orchestrate.mjs end`;
211
+
212
+ // R7: on claude 2.1.287 a subagent can dispatch and message agents (FEAT-011 V1), so a role
213
+ // could reach the envelope through a helper in two hops. During a live run only the main
214
+ // session, which carries no agent_type, dispatches. Silent outside a live run: no warning.
215
+ function guard6NestedDispatch(payload) {
216
+ if (payload.agent_type == null) return null;
217
+ const root = findRootHolding(payloadCwd(payload), ORCH_RUN_REL);
218
+ if (!root) return null;
219
+ const run = readRunFile(join(root, ...ORCH_RUN_REL));
220
+ if (!run || payload.session_id !== run.session_id) return null;
221
+ return deny(`Guard 6: ORCH_NESTED_DISPATCH: ${payload.tool_name} from agent ${payload.agent_type} is denied while run ${run.item} is live; only the orchestrator dispatches or messages agents during a run.`);
222
+ }
223
+
224
+ // Guard 6: while a run is live in this session, nothing but a band role writes outside the
225
+ // orchestrator's write surface (FEAT-011 D3). Identity cannot mark the main session, so the
226
+ // run's session_id is the key. Another session's run is stale: warned about, never enforced,
227
+ // so a crashed run cannot lock a later session out. R7 precedes the role skip, because a
228
+ // role's dispatch is exactly what it closes.
229
+ function guard6OrchestratorRun(input, payload) {
230
+ if (ORCH_DISPATCH_TOOLS.includes(payload.tool_name)) return guard6NestedDispatch(payload);
231
+ if (BAND_ROLES.includes(payload.agent_type)) return null;
232
+ const cwd = payloadCwd(payload);
233
+ const root = findRootHolding(cwd, ORCH_RUN_REL);
234
+ if (!root) return null;
235
+ const file = join(root, ...ORCH_RUN_REL);
236
+ const run = readRunFile(file);
237
+ if (!run) return warn(`Guard 6: ORCH_RUN_INVALID: ${file} is unreadable or not a valid run file, so writes are not restricted. Clear it with: ${orchEnd(root)}`);
238
+ if (payload.session_id !== run.session_id) {
239
+ return warn(`Guard 6: ORCH_RUN_STALE: run ${run.item} (started ${run.started}) belongs to another session, so writes are not restricted. Clear it with: ${orchEnd(root)}`);
240
+ }
241
+ const target = targetPath(input);
242
+ const rel = relative(root, resolve(cwd, target)).split(sep).join('/');
243
+ if (target !== '' && ORCH_WRITE_SURFACE.some((g) => globToRegExp(g).test(rel))) return null;
244
+ return deny(`Guard 6: ORCH_WRITE_DENIED: ${target || '<no path>'} is outside the orchestrator's write surface while run ${run.item} is live; repository writes during a run go through a band role (Guard 5).`);
245
+ }
246
+
247
+ // ── Guard 7 constants ─────────────────────────────────────────────────────────
248
+ // A copy of scripts/orchestrate.mjs SHELL_METACHARACTERS (FEAT-012 D10), carried for Guard
249
+ // 5's reason: no import resolves from both install locations. tests/hooks/guard7.test.js pins it.
250
+ const ROLE_SHELL_METACHARACTERS = [';', '&', '|', '`', '$(', '<', '>', '\n', '\r'];
251
+ const ROLE_SHELL_ROLES = ['code', 'qa'];
252
+
253
+ // R3: the test command a live run of this session recorded, or null. The run root is found
254
+ // by Guard 5's walk and the file read by Guard 6's reader.
255
+ function liveTestCommand(payload) {
256
+ const root = findRootHolding(payloadCwd(payload), ORCH_RUN_REL);
257
+ if (!root) return null;
258
+ const run = readRunFile(join(root, ...ORCH_RUN_REL));
259
+ if (!run || payload.session_id !== run.session_id) return null;
260
+ return typeof run.test_command === 'string' && run.test_command !== '' ? run.test_command : null;
261
+ }
262
+
263
+ // R1-R5, the first match decides. The match is exact: a prefix allowlist is walked around by
264
+ // chaining, which is the T-003 vector.
265
+ function roleShellDecision(role, input, payload) {
266
+ if (!ROLE_SHELL_ROLES.includes(role)) return deny(`Guard 7: ROLE_SHELL_DENIED: ${role} has no shell.`);
267
+ const command = typeof input.command === 'string' ? input.command : '';
268
+ const found = ROLE_SHELL_METACHARACTERS.find((m) => command.includes(m));
269
+ if (found !== undefined) return deny(`Guard 7: ROLE_SHELL_CHAINING: the command contains ${JSON.stringify(found)}; a role runs one command, never a chain.`);
270
+ const allowed = liveTestCommand(payload);
271
+ if (allowed === null) return deny(`Guard 7: ROLE_SHELL_UNRESOLVED: no live run in this session records a test command, so ${role} has no shell.`);
272
+ if (command !== allowed) return deny(`Guard 7: ROLE_SHELL_NOT_ALLOWED: allowed command is ${allowed}`);
273
+ return null;
274
+ }
275
+
276
+ // Guard 7: a band role's Bash (FEAT-012). The tool mask is the authority and this is the layer
277
+ // beneath it: in FEAT-011's T-003 a declined Write was completed through Bash, so a prompt is
278
+ // not enough. Fail-closed: a throw denies here, where CC_HOOK_ALLOW cannot reach it.
279
+ function guard7RoleShell(input, payload) {
280
+ const role = payload.agent_type;
281
+ if (!BAND_ROLES.includes(role)) return null;
282
+ try { return roleShellDecision(role, input, payload); }
283
+ catch (e) { return deny(`Guard 7: ROLE_SHELL_UNRESOLVED: the guard could not decide (${e && e.message}), so the call is denied.`); }
284
+ }
285
+
181
286
  // ── Guard 3 constants ─────────────────────────────────────────────────────────
182
287
  // POSIX ERE fragments from tests/fixtures/guard3-reference.sh, translated class by
183
288
  // class. [[:space:]] in the C locale is EXACTLY [ \t\n\r\f\v]; JavaScript \s also
@@ -633,8 +738,14 @@ const DISPATCH = {
633
738
  Edit: [],
634
739
  Bash: [guard3BashScan],
635
740
  };
636
- // Guard 5 runs first on every write-family tool: a scope deny outranks Guard 2's ask.
637
- for (const tool of BAND_WRITE_TOOLS) DISPATCH[tool].unshift(guard5BandScope);
741
+ // Guards 5 and 6 run first on every write-family tool, in that order: a scope deny
742
+ // outranks Guard 2's ask, and Guard 6 steps aside for the band roles Guard 5 governs.
743
+ for (const tool of BAND_WRITE_TOOLS) DISPATCH[tool].unshift(guard5BandScope, guard6OrchestratorRun);
744
+ // R7 sees dispatch only where settings.json routes it: the matcher names Agent and SendMessage.
745
+ for (const tool of ORCH_DISPATCH_TOOLS) DISPATCH[tool] = [guard6OrchestratorRun];
746
+ // Guard 7 runs before Guard 3 on Bash: under CC_GUARD3_WARN Guard 3 asks instead of denying,
747
+ // and an ask must never outrank a role's shell deny.
748
+ DISPATCH.Bash.unshift(guard7RoleShell);
638
749
 
639
750
  // Case B. Unparseable input is not "nothing to verify", it is "the verifier could not
640
751
  // run", which is the condition that fails closed. CC_HOOK_ALLOW bypasses THIS denial only;
@@ -675,6 +786,7 @@ function main() {
675
786
  const decision = guard(input, payload);
676
787
  if (decision) { emit(decision); return; }
677
788
  }
789
+ if (warning) emit(null);
678
790
  }
679
791
 
680
792
  try { main(); } catch (e) { unreadable(`the hook threw (${e && e.message})`); }
@@ -2,7 +2,7 @@
2
2
  "hooks": {
3
3
  "PreToolUse": [
4
4
  {
5
- "matcher": "Read|Write|Edit|create_file|write_file|Bash",
5
+ "matcher": "Read|Write|Edit|create_file|write_file|Bash|Agent|SendMessage",
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",
@@ -3,3 +3,5 @@
3
3
  *.installer-backup.*
4
4
  *.installer-tmp.*
5
5
  .claude/memory/band-envelope.json
6
+ .claude/memory/orchestrator-run.json
7
+ .conductor/
@@ -0,0 +1,388 @@
1
+ #!/usr/bin/env node
2
+ // scripts/orchestrate.mjs
3
+ // The band router (FEAT-011). It builds, validates and installs SNAP v3 envelopes and
4
+ // records a run's position in a host-owned run file. It never edits a tracked file, and
5
+ // it is the only writer of the run file. Zero dependencies, node: builtins only.
6
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { spawnSync } from 'node:child_process';
8
+ import { homedir, tmpdir } from 'node:os';
9
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
+ import { GATES, ROLE_BAND, V3_CAPS } from './snap-contract.mjs';
12
+
13
+ const HERE = dirname(fileURLToPath(import.meta.url));
14
+
15
+ export const RUN_FILE = '.claude/memory/orchestrator-run.json';
16
+ export const ENVELOPE_FILE = '.claude/memory/band-envelope.json';
17
+ // The orchestrator's whole write surface (D4). Guard 6 carries a copy pinned to this one.
18
+ export const WRITE_SURFACE = [RUN_FILE, ENVELOPE_FILE, '.claude/memory/session-snapshot.json', '.conductor/**'];
19
+ // Where /cc-orchestrate writes each agent's final message for `handback` to read: inside
20
+ // the surface, and cleared with the run so file names never collide across runs.
21
+ export const HANDBACK_DIR = '.conductor/handback';
22
+
23
+ // D5: the reviewed role-artifact table. Code's scope comes from its plan task instead.
24
+ export const ROLE_ARTIFACTS = {
25
+ spec: { tk: 'RW', scope: ['docs/superpowers/specs/**'] },
26
+ plan: { tk: 'RW', scope: ['docs/superpowers/plans/**'] },
27
+ code: { tk: 'RW', scope: null },
28
+ audit: { tk: 'R', scope: null },
29
+ qa: { tk: 'X', scope: null },
30
+ };
31
+ // The router table's "may hand back" column.
32
+ export const MAY_HAND_BACK = {
33
+ spec: ['boundary_routed'], plan: ['boundary_routed'], code: ['build_executed'],
34
+ audit: ['build_executed'], qa: ['verify_pass'],
35
+ };
36
+ const PHASE = { spec: 'spec', plan: 'plan', code: 'impl', audit: 'rev', qa: 'rev' };
37
+ // Guard 7's chaining set (FEAT-012 D7). The hook carries a copy pinned to this one (D10).
38
+ export const SHELL_METACHARACTERS = [';', '&', '|', '`', '$(', '<', '>', '\n', '\r'];
39
+ // D6: each package manager's invocation of the owner's `test` script. `bun test` would run
40
+ // Bun's own test runner and ignore the script, so bun goes through `run`.
41
+ export const PM_TEST_COMMAND = { npm: 'npm test', pnpm: 'pnpm test', yarn: 'yarn test', bun: 'bun run test' };
42
+
43
+ // A halt stops the run and is recorded in it (D12). A refusal is a misuse of the CLI:
44
+ // nothing is written and nothing is recorded.
45
+ export class Halt extends Error {
46
+ constructor(code, reason) { super(`${code}: ${reason}`); this.code = code; this.reason = reason; }
47
+ }
48
+ export class Refusal extends Error {}
49
+
50
+ const isPlainObject = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
51
+
52
+ // The run root is the nearest ancestor of cwd holding the run file, the walk Guard 6
53
+ // makes; before a run exists, it is the nearest one holding .claude/.
54
+ export function findRunRoot(start) {
55
+ for (const marker of [RUN_FILE, '.claude']) {
56
+ for (let dir = resolve(start); ; dir = dirname(dir)) {
57
+ if (existsSync(join(dir, marker))) return dir;
58
+ if (dirname(dir) === dir) break;
59
+ }
60
+ }
61
+ return resolve(start);
62
+ }
63
+
64
+ function writeAtomic(path, text) {
65
+ mkdirSync(dirname(path), { recursive: true });
66
+ const tmp = `${path}.${process.pid}.tmp`;
67
+ writeFileSync(tmp, text);
68
+ renameSync(tmp, path);
69
+ }
70
+
71
+ const scriptRef = (root) => relative(root, join(HERE, 'orchestrate.mjs')).split('\\').join('/');
72
+
73
+ export function isValidRun(run) {
74
+ return isPlainObject(run) && run.v === 1 && typeof run.session_id === 'string' && run.session_id !== ''
75
+ && typeof run.item === 'string' && GATES.includes(run.gate) && isPlainObject(run.approvals)
76
+ && Array.isArray(run.handbacks) && Array.isArray(run.tasks?.ids) && Number.isInteger(run.tasks?.done);
77
+ }
78
+
79
+ function readRun(root) {
80
+ const path = join(root, RUN_FILE);
81
+ if (!existsSync(path)) return null;
82
+ let run = null;
83
+ try { run = JSON.parse(readFileSync(path, 'utf8')); } catch { /* judged below */ }
84
+ if (!isValidRun(run)) {
85
+ throw new Halt('ORCH_RUN_INVALID', `${path} is unreadable or not a v1 run file; clear it with: node ${scriptRef(root)} end`);
86
+ }
87
+ return run;
88
+ }
89
+
90
+ const saveRun = (root, run) => writeAtomic(join(root, RUN_FILE), JSON.stringify(run, null, 2) + '\n');
91
+
92
+ // Every verb but start and end drives a run that must exist, be this session's, and not be halted.
93
+ function liveRun(root, sessionId) {
94
+ const run = readRun(root);
95
+ if (!run) throw new Refusal(`no run file at ${join(root, RUN_FILE)}; start one first`);
96
+ if (run.session_id !== sessionId) {
97
+ throw new Refusal(`run ${run.item} belongs to another session; end it, or start to replace it`);
98
+ }
99
+ if (run.halt) throw new Refusal(`run ${run.item} halted with ${run.halt.code}; recover with end, then start (D12)`);
100
+ return run;
101
+ }
102
+
103
+ const handedBack = (run, role) => run.handbacks.some((h) => h.role === role);
104
+
105
+ // The band sequence, read off the run's record.
106
+ export function nextStep(run) {
107
+ if (!handedBack(run, 'spec')) return { role: 'spec' };
108
+ if (!run.approvals.spec) return { await: 'spec' };
109
+ if (!handedBack(run, 'plan')) return { role: 'plan' };
110
+ if (!run.approvals.plan) return { await: 'plan' };
111
+ if (run.tasks.done < run.tasks.ids.length) return { role: 'code', task: run.tasks.ids[run.tasks.done] };
112
+ if (!handedBack(run, 'audit')) return { role: 'audit' };
113
+ if (!handedBack(run, 'qa')) return { role: 'qa' };
114
+ return { end: true };
115
+ }
116
+
117
+ const describeStep = (s) => (s.role ? `install ${s.role}` : s.await ? `approve ${s.await}` : 'end');
118
+
119
+ // D6: a gate crosses only a band boundary; inside a band the entry gate is re-issued.
120
+ export function forwardGate(run, role, gate) {
121
+ if (role === 'code') return run.tasks.done + 1 === run.tasks.ids.length ? gate : run.gate;
122
+ if (role === 'qa') return gate;
123
+ return run.gate;
124
+ }
125
+
126
+ // writing-plans tasks: `### Task N` opens one; its **Files:** block lists the paths.
127
+ export function extractTasks(planText) {
128
+ const tasks = [];
129
+ let current = null;
130
+ let inFiles = false;
131
+ for (const line of planText.split(/\r?\n/)) {
132
+ const head = line.match(/^### (Task \d+)\b/);
133
+ if (head) { current = { id: head[1], files: [] }; tasks.push(current); inFiles = false; continue; }
134
+ if (/^#{1,3} /.test(line)) { current = null; continue; }
135
+ if (!current) continue;
136
+ if (line.trim() === '**Files:**') { inFiles = true; continue; }
137
+ const entry = inFiles && line.match(/^\s*- (?:Create|Modify|Test): (.*)$/);
138
+ if (!entry) { inFiles = false; continue; }
139
+ for (const m of entry[1].matchAll(/`([^`]+)`/g)) current.files.push(m[1].replace(/:\d+(-\d+)?$/, '').replace(/^\.\//, ''));
140
+ }
141
+ return tasks;
142
+ }
143
+
144
+ // D9: an empty scope is a plan defect, never a read-only fallback; scopes are never truncated.
145
+ export function taskScope(task, planRel) {
146
+ if (task.files.length === 0) throw new Halt('ORCH_EMPTY_SCOPE', `${task.id} declares no files`);
147
+ const scope = [...new Set([...task.files, planRel])];
148
+ const [cap, elemCap] = V3_CAPS['ops.scope'];
149
+ if (scope.length > cap) throw new Halt('ORCH_SCOPE_OVER_CAP', `${task.id} needs ${scope.length} scope entries; the cap is ${cap}`);
150
+ const long = scope.find((p) => p.length > elemCap);
151
+ if (long) throw new Halt('ORCH_SCOPE_OVER_CAP', `${task.id} has a ${long.length}-character path; the cap is ${elemCap}`);
152
+ return scope;
153
+ }
154
+
155
+ function readPlan(root, planRel) {
156
+ if (!planRel || isAbsolute(planRel) || planRel.split(/[\\/]/).includes('..')) {
157
+ throw new Refusal('usage: orchestrate.mjs approve plan <plan path relative to the run root>');
158
+ }
159
+ try { return readFileSync(join(root, planRel), 'utf8'); } catch { throw new Refusal(`cannot read ${planRel}`); }
160
+ }
161
+
162
+ // ORCH_AGENT_MISSING's search. Plugin-provided agents are not searched, a stated limit.
163
+ export function findAgent(role, root, home = homedir()) {
164
+ for (const dir of [join(root, '.claude', 'agents'), join(home, '.claude', 'agents')]) {
165
+ let names = [];
166
+ try { names = readdirSync(dir).filter((n) => n.endsWith('.md')); } catch { continue; }
167
+ for (const n of names) {
168
+ const front = readFileSync(join(dir, n), 'utf8').match(/^---\r?\n([\s\S]*?)\r?\n---/);
169
+ if (front && new RegExp(`^name:[ \\t]*${role}[ \\t]*$`, 'm').test(front[1])) return join(dir, n);
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+
175
+ function runScript(name, args, input = '') {
176
+ const r = spawnSync(process.execPath, [join(HERE, name), ...args], { input, encoding: 'utf8' });
177
+ return { status: r.status, out: r.stdout, err: (r.stderr || '').trim() };
178
+ }
179
+
180
+ // detect-stack installs process-wide error handlers when imported, so it is spawned. It prints
181
+ // {} on any failure, which answers nothing either way.
182
+ function detectStack(root) {
183
+ let out = null;
184
+ try { out = JSON.parse(runScript('detect-stack.mjs', [root]).out); } catch { /* judged below */ }
185
+ if (isPlainObject(out) && Object.keys(out).length > 0) return out;
186
+ throw new Halt('ORCH_TEST_COMMAND_UNRESOLVED', `detect-stack returned no result for ${root}`);
187
+ }
188
+
189
+ // Only a non-blank string is the owner's test script.
190
+ function hasTestScript(pkgPath) {
191
+ let pkg;
192
+ try { pkg = JSON.parse(readFileSync(pkgPath, 'utf8').replace(/^\uFEFF/, '')); } catch {
193
+ throw new Halt('ORCH_TEST_COMMAND_UNRESOLVED', `${pkgPath} does not parse, so its test script cannot be read`);
194
+ }
195
+ const script = pkg?.scripts?.test;
196
+ return typeof script === 'string' && script.trim() !== '';
197
+ }
198
+
199
+ // D6: the one command code and qa may run, resolved before anything is recorded. The script
200
+ // is checked before detect-stack runs, because a non-string script makes detect-stack fail
201
+ // whole and the halt would then name the wrong cause.
202
+ export function resolveTestCommand(root) {
203
+ const pkgPath = join(root, 'package.json');
204
+ if (existsSync(pkgPath)) {
205
+ if (!hasTestScript(pkgPath)) {
206
+ throw new Halt('ORCH_TEST_COMMAND_UNRESOLVED', 'package.json has no scripts.test; add a test script, the run does not guess a runner');
207
+ }
208
+ return PM_TEST_COMMAND[detectStack(root).packageManager] ?? PM_TEST_COMMAND.npm;
209
+ }
210
+ const { test } = detectStack(root);
211
+ if (typeof test === 'string' && test.trim() !== '') return test;
212
+ throw new Halt('ORCH_TEST_COMMAND_UNRESOLVED', `detect-stack names no test command for ${root}`);
213
+ }
214
+
215
+ // D7: no command is recorded that Guard 7 would not pass.
216
+ export function checkTestCommand(command) {
217
+ const found = SHELL_METACHARACTERS.find((m) => command.includes(m));
218
+ if (found === undefined) return command;
219
+ throw new Halt('ORCH_TEST_COMMAND_UNSAFE', `${JSON.stringify(command)} contains ${JSON.stringify(found)}, which Guard 7 denies; nothing was recorded`);
220
+ }
221
+
222
+ // The validator reads a file, so the candidate goes through a private temp dir. Returns
223
+ // the validator's error text, or '' when it passes.
224
+ function validate(text, role) {
225
+ const dir = mkdtempSync(join(tmpdir(), 'cc-orch-'));
226
+ try {
227
+ writeFileSync(join(dir, 'snap.json'), text);
228
+ const r = runScript('snap-validate.mjs', [join(dir, 'snap.json'), ...(role ? ['--to', role] : [])]);
229
+ return r.status === 0 ? '' : r.err || `snap-validate exited ${r.status}`;
230
+ } finally { rmSync(dir, { recursive: true, force: true }); }
231
+ }
232
+
233
+ function gitValue(root, args, fallback) {
234
+ const r = spawnSync('git', args, { cwd: root, encoding: 'utf8' });
235
+ return (r.status === 0 && r.stdout.trim()) || fallback;
236
+ }
237
+
238
+ function envelopeFields(run, root, step) {
239
+ const head = gitValue(root, ['rev-parse', 'HEAD'], '0000000').toLowerCase();
240
+ const { tk, scope } = ROLE_ARTIFACTS[step.role];
241
+ const fields = {
242
+ ph: PHASE[step.role], c: /^[0-9a-f]{7,40}$/.test(head) ? head : '0000000', s: run.item,
243
+ n: [], f: [], d: [], x: [], role: step.role, tk, gate: run.gate,
244
+ };
245
+ if (step.role === 'code') {
246
+ const task = extractTasks(readPlan(root, run.plan)).find((t) => t.id === step.task);
247
+ fields.scope = taskScope(task ?? { id: step.task, files: [] }, run.plan);
248
+ } else if (scope) fields.scope = scope;
249
+ return fields;
250
+ }
251
+
252
+ // Builds and validates the next envelope with --to; installs it unless only checking.
253
+ function install(root, sessionId, role, check) {
254
+ const run = liveRun(root, sessionId);
255
+ const step = nextStep(run);
256
+ if (step.role !== role) throw new Refusal(`install ${role}: the next step is ${describeStep(step)}`);
257
+ if (!findAgent(role, root)) {
258
+ throw new Halt('ORCH_AGENT_MISSING', `no agent definition named ${role} in .claude/agents/ or ~/.claude/agents/`);
259
+ }
260
+ const built = runScript('snap-build.mjs', [], JSON.stringify(envelopeFields(run, root, step)));
261
+ if (built.status !== 0) throw new Halt('SNAP_ERROR', built.err);
262
+ const error = validate(built.out, role);
263
+ if (error) throw new Halt(error.includes('SNAP_GATE_MISMATCH') ? 'SNAP_GATE_MISMATCH' : 'SNAP_ERROR', error);
264
+ if (check) return built.out.trim();
265
+ writeAtomic(join(root, ENVELOPE_FILE), built.out);
266
+ saveRun(root, { ...run, band: ROLE_BAND[role], role });
267
+ return built.out.trim();
268
+ }
269
+
270
+ export function recordHandback(run, role, gate) {
271
+ const entry = { role, gate, at: new Date().toISOString(), ...(role === 'code' ? { task: run.tasks.ids[run.tasks.done] } : {}) };
272
+ const tasks = role === 'code' ? { ...run.tasks, done: run.tasks.done + 1 } : run.tasks;
273
+ return { ...run, role: null, gate: forwardGate(run, role, gate), tasks, handbacks: [...run.handbacks, entry] };
274
+ }
275
+
276
+ function parseHandback(text) {
277
+ const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.startsWith('SNAP_HANDBACK '));
278
+ if (lines.length !== 1) throw new Halt('ORCH_HANDBACK_MISSING', `expected exactly one SNAP_HANDBACK line, found ${lines.length}`);
279
+ const json = lines[0].slice('SNAP_HANDBACK '.length).trim();
280
+ const error = validate(json + '\n');
281
+ if (error) throw new Halt('ORCH_HANDBACK_INVALID', error);
282
+ const env = JSON.parse(json);
283
+ if (env.v !== 3) throw new Halt('ORCH_HANDBACK_INVALID', `a hand-back must be a v3 envelope, got v${env.v}`);
284
+ return env;
285
+ }
286
+
287
+ function handback(root, sessionId, role, text) {
288
+ const run = liveRun(root, sessionId);
289
+ // The binary refuses a second SubagentHandback, yet an agent can still report again (V1, F4).
290
+ if (!run.role && run.handbacks.at(-1)?.role === role) {
291
+ throw new Halt('ORCH_HANDBACK_CONFLICT', `${role} already handed back for this position; a second report is not routed`);
292
+ }
293
+ if (!run.role || run.role !== role) throw new Refusal(`handback ${role}: the dispatched role is ${run.role ?? 'none'}`);
294
+ const env = parseHandback(text);
295
+ if (env.sys.role !== role) throw new Halt('ORCH_HANDBACK_ROLE_MISMATCH', `dispatched ${role}, the hand-back names ${env.sys.role}`);
296
+ if (!MAY_HAND_BACK[role].includes(env.ops.gate)) {
297
+ throw new Halt('ORCH_GATE_UNEARNED', `${role} may hand back ${MAY_HAND_BACK[role].join('|')}, not ${env.ops.gate}`);
298
+ }
299
+ saveRun(root, recordHandback(run, role, env.ops.gate));
300
+ return `${role} handed back ${env.ops.gate}`;
301
+ }
302
+
303
+ // Two human approvals, one gate write (A4): only an approved plan writes define_approved.
304
+ function approve(root, sessionId, what, planRel) {
305
+ const run = liveRun(root, sessionId);
306
+ const step = nextStep(run);
307
+ if (step.await !== what) throw new Refusal(`approve ${what}: the next step is ${describeStep(step)}`);
308
+ const approval = { at: new Date().toISOString(), by: gitValue(root, ['config', 'user.name'], 'unknown') };
309
+ if (what === 'spec') {
310
+ saveRun(root, { ...run, approvals: { ...run.approvals, spec: approval } });
311
+ return 'spec approved';
312
+ }
313
+ const tasks = extractTasks(readPlan(root, planRel));
314
+ if (tasks.length === 0) throw new Halt('ORCH_EMPTY_SCOPE', `${planRel} holds no "### Task N" section`);
315
+ for (const t of tasks) taskScope(t, planRel);
316
+ saveRun(root, {
317
+ ...run, gate: 'define_approved', plan: planRel, tasks: { ids: tasks.map((t) => t.id), done: 0 },
318
+ approvals: { ...run.approvals, plan: approval },
319
+ });
320
+ return `plan approved: define_approved, ${tasks.length} task(s)`;
321
+ }
322
+
323
+ function start(root, sessionId, item, flag) {
324
+ if (!/^[A-Z]+-\d{3,}$/.test(item ?? '') || (flag !== undefined && flag !== '--auto')) {
325
+ throw new Refusal('usage: orchestrate.mjs start <ITEM> [--auto]');
326
+ }
327
+ if (!sessionId) throw new Halt('ORCH_NO_SESSION_ID', 'CLAUDE_CODE_SESSION_ID is absent or empty, so Guard 6 could never bind this run');
328
+ const old = readRun(root);
329
+ if (old && old.session_id === sessionId) throw new Halt('ORCH_RUN_ACTIVE', `run ${old.item} is live in this session; end it first`);
330
+ // Resolved before a stale run is cleared, so a halt here leaves everything as it was.
331
+ const testCommand = checkTestCommand(resolveTestCommand(root));
332
+ if (old) clearRunFiles(root);
333
+ saveRun(root, {
334
+ v: 1, session_id: sessionId, item, mode: flag ? 'auto' : 'step', started: new Date().toISOString(),
335
+ band: 'boundary', role: null, gate: 'boundary_routed', approvals: { spec: null, plan: null },
336
+ plan: null, tasks: { ids: [], done: 0 }, handbacks: [], halt: null, test_command: testCommand,
337
+ });
338
+ const begun = old ? `replaced the stale run ${old.item} started ${old.started}` : `run ${item} started`;
339
+ return `${begun}; test command: ${testCommand}`;
340
+ }
341
+
342
+ function clearRunFiles(root) {
343
+ rmSync(join(root, ENVELOPE_FILE), { force: true });
344
+ rmSync(join(root, HANDBACK_DIR), { recursive: true, force: true });
345
+ }
346
+
347
+ // Prints the run it removes, so the closing report reads the record rather than memory.
348
+ function end(root) {
349
+ const path = join(root, RUN_FILE);
350
+ const text = existsSync(path) ? readFileSync(path, 'utf8').trim() : 'no run file';
351
+ rmSync(path, { force: true });
352
+ clearRunFiles(root);
353
+ return text;
354
+ }
355
+
356
+ function recordHalt(root, halt) {
357
+ try {
358
+ const run = readRun(root);
359
+ if (run && !run.halt) saveRun(root, { ...run, halt: { code: halt.code, reason: halt.reason, at: new Date().toISOString() } });
360
+ } catch { /* an unreadable run file cannot carry its own halt */ }
361
+ }
362
+
363
+ export function cli(argv, env, cwd = process.cwd()) {
364
+ const [verb, a, b] = argv;
365
+ const root = findRunRoot(cwd);
366
+ const sid = env.CLAUDE_CODE_SESSION_ID;
367
+ const verbs = {
368
+ start: () => start(root, sid, a, b),
369
+ install: () => install(root, sid, a, b === '--check'),
370
+ handback: () => handback(root, sid, a, readFileSync(0, 'utf8')),
371
+ approve: () => approve(root, sid, a, b),
372
+ end: () => end(root),
373
+ };
374
+ try {
375
+ if (!verbs[verb]) throw new Refusal('usage: orchestrate.mjs start|install|handback|approve|end');
376
+ process.stdout.write(verbs[verb]() + '\n');
377
+ return 0;
378
+ } catch (e) {
379
+ if (e instanceof Refusal) { process.stderr.write(`orchestrate: ${e.message}\n`); return 2; }
380
+ if (!(e instanceof Halt)) throw e;
381
+ if (verb !== 'start') recordHalt(root, e);
382
+ process.stderr.write(`${e.code}: ${e.reason}\n`);
383
+ return 1;
384
+ }
385
+ }
386
+
387
+ const invoked = process.argv[1] && pathToFileURL(realpathSync(process.argv[1])).href === import.meta.url;
388
+ if (invoked) process.exitCode = cli(process.argv.slice(2), process.env);