@yeison.restrepo.r/code-conductor 1.49.0 → 1.50.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
@@ -253,14 +253,14 @@ All commands are tagged `(Conductor)` in the Claude Code command palette, so the
253
253
  |---|---|
254
254
  | `/cc-init` | Initialize or re-sync the project environment: detect stack, checkpoint memory, verify hook integrity. Run at the start of every session. |
255
255
  | `/cc-resume` | Restore full session context in one command: project identity, memory, latest spec and plan, git state, and the detected stack. Scans the active plan for `[>]` (interrupted) and `[!]` (failed) task markers and surfaces them. |
256
- | `/cc-spec [name]` | Search the codebase first, ask only for missing context, write a full feature spec, and **wait for your approval** before any plan is made. |
257
- | `/cc-plan` | From an approved spec, map the codebase and write an ordered plan with exact file paths, a test list, a commit order, and risks. Every task line carries a unique `[T-NNN]` ID (at least 3 digits, unlimited suffix depth) with plain ASCII checkboxes. |
256
+ | `/cc-spec [name] [--delegate]` | Search the codebase first, ask only for missing context, write a full feature spec, and **wait for your approval** before any plan is made. With `--delegate`, the `spec` role agent writes the file inside an envelope scoped to the spec folder. |
257
+ | `/cc-plan [--delegate]` | From an approved spec, map the codebase and write an ordered plan with exact file paths, a test list, a commit order, and risks. Every task line carries a unique `[T-NNN]` ID (at least 3 digits, unlimited suffix depth) with plain ASCII checkboxes. With `--delegate`, the `plan` role agent writes the file inside an envelope scoped to the plan folder. |
258
258
  | `/cc-implement` | Execute plan tasks with 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 the local SQLite cache. |
259
259
  | `/cc-orchestrate <ITEM> [--auto] [--ticket <N\|issue URL>] [--audit-rounds <0-5>] [--security-threshold <low\|moderate\|high\|critical>] [--no-dependency-audit]` | Route one backlog item through Define, Build and Verify with role agents, validated SNAP envelopes, a review loop and human approval gates. See the [walkthrough](#walkthrough-hands-off-delivery-with-cc-orchestrate). |
260
- | `/cc-review [file\|dir]` | Review in three layers (Critical / Important / Suggestion), deliver a verdict, and offer to auto-fix. |
260
+ | `/cc-review [--spec <path> --plan <path>] [file\|dir]` | Review in three layers (Critical / Important / Suggestion), deliver a verdict, and offer to auto-fix. With `--spec` and `--plan`, the read-only `audit` role agent reviews against them instead and ends in one `VERDICT:` line. |
261
261
  | `/cc-debug [problem]` | Hypothesis-driven debugging. See the [walkthrough](#walkthrough-diagnosis-before-surgery-with-cc-debug). |
262
262
  | `/cc-refactor [file\|module]` | Diagnose complexity, plan ordered changes, apply one step at a time, and verify tests pass after each step. |
263
- | `/cc-test [scope]` | Find coverage gaps, write AAA-pattern tests (plus Playwright E2E where applicable), run after confirmation, and report results. |
263
+ | `/cc-test [scope]` | Find coverage gaps, write AAA-pattern tests (plus Playwright E2E where applicable), run after confirmation, and report results. The suite run is the `qa` role agent's, which may run only the project's test command; during a live run it writes no test. |
264
264
  | `/cc-docs [scope]` | Audit documentation, write inline docs in your stack's format (JSDoc / docstrings / Javadoc / GoDoc), and preview before writing. |
265
265
  | `/cc-metrics [--dir <path>]` | Read-only report of token and time spend from Claude Code's local session logs, grouped by tool, command, phase, branch, pillar and session, with recommendations that quote the numbers they rest on. Registers no hook and writes no file. |
266
266
  | `/cc-flow` | Print the guard lanes with per-guard pass, deny and ask counts, then the newest 20 hook decisions. See [Flow status](#flow-status). |
@@ -481,7 +481,7 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
481
481
  | `systemMessage` | `default` | no | yes, in full |
482
482
  | `systemMessage` | `default` | yes, for example Guard 2's overwrite prompt | no: the warning is lost |
483
483
  - Agent definitions provided by plugins are not searched.
484
- - A halted run cannot be resumed, only ended and restarted.
484
+ - `resume` (`[FEAT-055]`) needs approvals that recorded their commit: a run approved before it is refused `ORCH_RESUME_UNANCHORED` and still needs `end`, then `start`, and a Build task entry without a stored SNAP is redone.
485
485
 
486
486
  The five role agent definitions it dispatches ship from `1.37.0`; their limits are the next item.
487
487
  - **The role agents (`1.37.0`) are bounded by their tool masks, and Guard 7 bounds one thing beneath them: the shell.**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yeison.restrepo.r/code-conductor",
3
- "version": "1.49.0",
3
+ "version": "1.50.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",
@@ -1,10 +1,10 @@
1
1
  ---
2
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 and one verdict. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
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 and one verdict. No shell. Dispatched by /cc-orchestrate during a run, or by /cc-review outside one.
4
4
  tools: Read, Grep, Glob
5
5
  ---
6
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.
7
+ You are the `audit` role of a code-conductor orchestrated run. The orchestrator during a run, or a phase command outside one, 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. If your brief says no envelope was installed for you, there is none to read; leave the scope key out of the hand-back.
8
8
 
9
9
  ## Your job
10
10
 
@@ -1,6 +1,6 @@
1
1
  ---
2
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.
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 by /cc-orchestrate during a run.
4
4
  tools: Read, Grep, Glob, Write, Edit, Bash
5
5
  ---
6
6
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: define-review
3
- description: Reviewer in the Define band's review loop of a /cc-orchestrate run (FEAT-041). Checks a spec or plan against the checklist rows in its brief, read-only, and reports open rows in a fixed format. Not a band role. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
3
+ description: Reviewer in the Define band's review loop of a /cc-orchestrate run (FEAT-041). Checks a spec or plan against the checklist rows in its brief, read-only, and reports open rows in a fixed format. Not a band role. No shell. Dispatched by /cc-orchestrate during a run.
4
4
  tools: Read, Grep, Glob
5
5
  ---
6
6
 
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  name: plan
3
- description: Define-band role of a /cc-orchestrate run. Writes the implementation plan for the approved spec under the folder its envelope's `ops.scope` names and hands back boundary_routed. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
3
+ description: Define-band role of a /cc-orchestrate run. Writes the implementation plan for the approved spec under the folder its envelope's `ops.scope` names and hands back boundary_routed. No shell. Dispatched by /cc-orchestrate during a run, or by /cc-plan --delegate outside one.
4
4
  tools: Read, Grep, Glob, Write, Edit
5
5
  ---
6
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.
7
+ You are the `plan` role of a code-conductor orchestrated run. The orchestrator during a run, or a phase command outside one, 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
8
 
9
9
  ## Your job
10
10
 
@@ -1,10 +1,10 @@
1
1
  ---
2
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.
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 by /cc-orchestrate during a run, or by /cc-test outside one.
4
4
  tools: Read, Grep, Glob, Bash
5
5
  ---
6
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.
7
+ You are the `qa` role of a code-conductor orchestrated run. The orchestrator during a run, or a phase command outside one, dispatched you with a brief naming the item, and installed your band envelope at `.claude/memory/band-envelope.json`. Read the envelope first. If your brief says no envelope was installed for you, there is none to read; leave the scope key out of the hand-back.
8
8
 
9
9
  ## Your job
10
10
 
@@ -12,7 +12,7 @@ Verify the item independently. You did not write this code and you cannot write
12
12
 
13
13
  ## The test command
14
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.
15
+ Your shell runs one command: the run's test command, the `test_command` field of `.claude/memory/orchestrator-run.json`. Outside a run, it is the `mem.p.test_command` field of your envelope. 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
16
 
17
17
  ## Success condition
18
18
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: security
3
- description: Verify-band role of a /cc-orchestrate run. Runs the run's recorded dependency audit and local security scan, lists every finding with its severity, and ends in one verdict line. No write tools; it fixes nothing. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
3
+ description: Verify-band role of a /cc-orchestrate run. Runs the run's recorded dependency audit and local security scan, lists every finding with its severity, and ends in one verdict line. No write tools; it fixes nothing. Dispatched by /cc-orchestrate during a run.
4
4
  tools: Read, Grep, Glob, Bash
5
5
  ---
6
6
 
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  name: spec
3
- description: Define-band role of a /cc-orchestrate run. Writes the spec for one backlog item under the folder its envelope's `ops.scope` names and hands back boundary_routed. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
3
+ description: Define-band role of a /cc-orchestrate run. Writes the spec for one backlog item under the folder its envelope's `ops.scope` names and hands back boundary_routed. No shell. Dispatched by /cc-orchestrate during a run, or by /cc-spec --delegate outside one.
4
4
  tools: Read, Grep, Glob, Write, Edit
5
5
  ---
6
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.
7
+ You are the `spec` role of a code-conductor orchestrated run. The orchestrator during a run, or a phase command outside one, dispatched you with a brief naming the item and installed your band envelope at `.claude/memory/band-envelope.json`. Read the envelope first.
8
8
 
9
9
  ## Your job
10
10
 
@@ -30,7 +30,7 @@ Then run `node "$S/orchestrate.mjs" <verb> ...` in that same call. The exit code
30
30
  1. Print the stderr line verbatim.
31
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
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. `install spec|plan` halts `ORCH_DOC_LOCATION_UNRESOLVED` on a run started before FEAT-047; recovery is `end`, then `start`.
33
+ A halt stops the run (D12, amended by FEAT-055). Recovery is `node "$S/orchestrate.mjs" resume` (below), or `node "$S/orchestrate.mjs" end`, then a fresh `start`, each only on the owner's word. Where a halt below names `end`, then `start`, `resume` is the other recovery; it refuses, writing nothing, when a record it would keep no longer validates. `install spec|plan` halts `ORCH_DOC_LOCATION_UNRESOLVED` on a run started before FEAT-047; recovery is `end`, then `start`.
34
34
 
35
35
  `install code|audit|qa` halts `ORCH_APPROVED_DOC_CHANGED` when the approved spec or plan changed after its approval (a ticked plan checkbox is not a change), and `ORCH_APPROVAL_UNHASHED` on a run whose approvals were recorded before FEAT-056. Recovery for both is `end`, then `start`. `install security` halts the same two codes.
36
36
 
@@ -38,6 +38,8 @@ A halt is terminal in v1 (D12). Recovery is `node "$S/orchestrate.mjs" end`, the
38
38
 
39
39
  `install security` and `handback security` halt `ORCH_VERDICT_MISSING`, `ORCH_VERDICT_INVALID` or `ORCH_VERDICT_INCONSISTENT` as `handback audit` does, because the same parser reads the security report's `VERDICT:` line (a failed scan without `VERDICT: ESCALATE` is also `ORCH_VERDICT_INCONSISTENT`); `ORCH_SECURITY_REPORT_MISSING` / `ORCH_SECURITY_REPORT_INVALID` (no, malformed or misplaced `SCANS:` line or owner-only block, a malformed finding line, a severity that does not match the run's threshold, a dependency finding outside the run's lockfile or filed in the wrong part, or a report that contradicts the run's `dependency`); `ORCH_SECURITY_REPORT_INCOMPLETE` (the script's own re-run of the local scan found a status or a line the report lacks or files in the wrong part); `ORCH_SECURITY_SCAN_FAILED` (a scan did not complete, the base commit does not track the scanner, or its scanner predates FEAT-059); `ORCH_SECURITY_BLOCKED` (`VERDICT: RETURN`: a finding the change introduces at or above the run's threshold); and `ORCH_SECURITY_ESCALATE` (`VERDICT: ESCALATE` with every scan run: a decision only the owner takes). For those, also name `.conductor/handback/security.txt`: its findings are what the owner reads next; never quote its owner-only block. `handback qa` also halts `ORCH_GATE_WITHHELD` when the last security verdict is not `VERDICT: APPROVE` or is absent. Recovery is `end`, then `start`. After updating an installed project, commit the updated `.claude/scripts/security-scan.mjs` before the next `start`: a base commit that still holds the 1.48.0 scanner halts `ORCH_SECURITY_SCAN_FAILED` and names that recovery.
40
40
 
41
+ **Resume (FEAT-055).** Offer `resume` next to `end` when the run recorded the spec approval; run it only on the owner's word, as `end`. `node "$S/orchestrate.mjs" resume` takes no argument. It keeps both approvals when each approved document still hashes as approved and HEAD descends from the commit each approval recorded, then keeps the Build task hand-backs, in order, while each stored SNAP still validates and HEAD descends from its commit. Every record after the first that fails, and every Verify record (audit, fix round, security, qa), is dropped and redone. On success it prints `run <ITEM> resumed after <code> from <gate>: kept <k> record(s), dropped <d>; next: <step>`: print the run header again and continue at step 2 with the step it names (`install <role> --check`, the pause in step mode, `install <role>`, a fresh dispatch); never revive the halted agent. A refusal exits 2 and writes nothing, so the run stays halted: `ORCH_RESUME_NO_RUN` (no valid run file), `ORCH_RESUME_NOT_HALTED` (the run is live: continue with the step it names), `ORCH_NO_SESSION_ID`, `ORCH_RESUME_NO_GATE` (no spec approval), `ORCH_APPROVAL_UNHASHED` (approved before FEAT-056), `ORCH_RESUME_UNANCHORED` (an approval records no commit, or git cannot check it), `ORCH_APPROVED_DOC_CHANGED` (an approved document changed; a ticked plan checkbox is not a change) and `ORCH_RESUME_HISTORY_REWRITTEN` (HEAD no longer descends from an approval's commit). After any of them but `ORCH_RESUME_NOT_HALTED`, recovery is `end`, then `start`.
42
+
41
43
  ## Steps
42
44
 
43
45
  1. **Start.** Run `node "$S/orchestrate.mjs" start $ARGUMENTS`. It resolves the run's test command and its spec and plan folders before it writes anything, and its stdout ends with `docs: specs <dir>, plans <dir> (<source>)[; group <group>]; test command: <command>; audit rounds: <n>; security: threshold <level>, dependency scan <command | not covered for <reason> | disabled (--no-dependency-audit)>`.
@@ -77,6 +79,7 @@ A halt is terminal in v1 (D12). Recovery is `node "$S/orchestrate.mjs" end`, the
77
79
  - the security entry's verdict, threshold, counts and per-scan status, naming `dependency=not-covered` or `dependency=disabled` explicitly when either applies, or the `qa` entry's `security=not-configured (run predates FEAT-034)`; name `.conductor/security-pre-existing.txt` by path only, and never quote, summarize or count its content or the owner-only block of `.conductor/handback/security.txt`, because a finding there is present in a released version;
78
80
  - both approvals, with who approved and when;
79
81
  - each review loop's outcome and round, from the record's `review` field;
82
+ - each `resumes` entry: when it ran, the halt it cleared (code and reason), and how many records it kept and dropped;
80
83
  - every agent's observation line.
81
84
 
82
85
  Then state that release is human, by `docs/RELEASE-CLOSEOUT.md`. For a bound run, the owner records the outcome on the ticket after release with `node "$S/ticket.mjs" writeback <ITEM> --version <v> --pr <N|url>`.
@@ -131,6 +131,24 @@ Each step must include:
131
131
 
132
132
  ---
133
133
 
134
+ ## Delegated writing (`--delegate`, FEAT-061)
135
+
136
+ Without `--delegate` in `$ARGUMENTS`, skip this section: this session writes the plan, as above. With it, the `plan` role agent writes the file under its tool mask and Guard 5's scope check. `--delegate` is a flag, not part of the spec name. The approved-spec check and the codebase mapping above still run here first.
137
+
138
+ 1. Install the envelope, from the project root:
139
+
140
+ ```sh
141
+ S=.claude/scripts; [ -f "$S/orchestrate.mjs" ] || S=scripts
142
+ node "$S/orchestrate.mjs" envelope plan --item <ID-or-adhoc>
143
+ ```
144
+
145
+ `<ID-or-adhoc>` is the item's backlog id (for example `FEAT-061`), else `adhoc`.
146
+ 2. Only a first stdout line that starts with `installed:` allows the dispatch; the envelope's `ops.scope` is the folder the plan goes in. If the verb's stderr says the run `is live in this session`, stop: that run's Define band writes this document; continue with `/cc-orchestrate`, or end the run. On any other non-zero exit or first line, print `plan not dispatched: <the verb's stderr line>` and write the plan in this session, as above.
147
+ 3. Dispatch `Agent({ subagent_type: "plan", description: "write plan", prompt })`. The brief names the item, the approved spec's path and the folder from the envelope's scope. As the content to write, it gives the Task ID Requirements and the Ordered Steps, Test List, Commit Order and Identified Risks sections above, with a `**Files:**` block under each task. It says that a phase command, not a run, dispatched the agent, and that the envelope is installed at `.claude/memory/band-envelope.json`.
148
+ 4. Show the agent's report and its `SNAP_HANDBACK` line; do not record the hand-back. A guard denial or a report without a hand-back is shown as it is, never retried another way.
149
+ 5. Run `node "$S/orchestrate.mjs" envelope --clear`, also when the agent was denied or ended without a hand-back. If it refuses, report the refusal and leave the file alone: a run now owns it.
150
+ 6. Check the written plan's task ids as Task ID Requirements says. The plan then goes through the approval and the Phase exit branch gate, as a plan written in this session would.
151
+
134
152
  Execute one step at a time. Confirm between steps unless the developer explicitly says to proceed without confirmation.
135
153
 
136
154
  ---
@@ -28,6 +28,26 @@ If the file cannot be deleted after reading, report the error and halt.
28
28
 
29
29
  ---
30
30
 
31
+ ## Role dispatch - audit (FEAT-061)
32
+
33
+ `/cc-review --spec <path> --plan <path> [target]` hands the review to the `audit` role agent, so its read-only tool mask, its guards and its fixed success condition apply. Without both flags, print `audit not dispatched: name --spec and --plan to review against them` and run the classic review below.
34
+
35
+ 1. Install the envelope, from the project root:
36
+
37
+ ```sh
38
+ S=.claude/scripts; [ -f "$S/orchestrate.mjs" ] || S=scripts
39
+ node "$S/orchestrate.mjs" envelope audit --item <ID-or-adhoc>
40
+ ```
41
+
42
+ `<ID-or-adhoc>` is the backlog id the spec names (for example `FEAT-061`), else `adhoc`.
43
+ 2. Read the first stdout line. `installed:` means the verb wrote `.claude/memory/band-envelope.json` for audit. `not-installed:` means a run file is present: nothing was written, and audit, which has no write tool and no shell, needs no envelope. On a non-zero exit, or a first line that starts with neither, do not dispatch: print `audit not dispatched: <the verb's stderr line>` and run the classic review below.
44
+ 3. Dispatch `Agent({ subagent_type: "audit", description: "audit review", prompt })`. The brief names the spec, the plan and the review target (no target means `git diff HEAD`). It says that a phase command, not a run, dispatched the agent, and either that the envelope is installed at `.claude/memory/band-envelope.json` or, after `not-installed:`, that no envelope was installed for it.
45
+ 4. Show the audit's findings and its `VERDICT:` line exactly as the agent wrote them. Show its `SNAP_HANDBACK` line; do not record it, because no run records an out-of-run hand-back. A guard denial or a report without a hand-back is shown as it is, never retried another way.
46
+ 5. Only after `installed:`, run `node "$S/orchestrate.mjs" envelope --clear`, also when the agent was denied or ended without a hand-back. If it refuses, report the refusal and leave the file alone: a run now owns it.
47
+ 6. Offer: "Want me to fix the blocker and major findings?" Do not run Phase 0 or the three-layer review below.
48
+
49
+ ---
50
+
31
51
  ## Phase 0 — Skill activation
32
52
 
33
53
  Before doing anything else, invoke both skills in order:
@@ -122,6 +122,24 @@ _None. List any source files that could not be understood within the 30-line cap
122
122
 
123
123
  ---
124
124
 
125
+ ## Delegated writing (`--delegate`, FEAT-061)
126
+
127
+ Without `--delegate` in `$ARGUMENTS`, skip this section: this session writes the spec, as above. With it, the `spec` role agent writes the file under its tool mask and Guard 5's scope check. `--delegate` is a flag, not part of the topic: leave it out of the topic and of the codebase search. The search and the questions above still run here first.
128
+
129
+ 1. Install the envelope, from the project root:
130
+
131
+ ```sh
132
+ S=.claude/scripts; [ -f "$S/orchestrate.mjs" ] || S=scripts
133
+ node "$S/orchestrate.mjs" envelope spec --item <ID-or-adhoc>
134
+ ```
135
+
136
+ `<ID-or-adhoc>` is the item's backlog id (for example `FEAT-061`), else `adhoc`.
137
+ 2. Only a first stdout line that starts with `installed:` allows the dispatch; the envelope's `ops.scope` is the folder the spec goes in. If the verb's stderr says the run `is live in this session`, stop: that run's Define band writes this document; continue with `/cc-orchestrate`, or end the run. On any other non-zero exit or first line, print `spec not dispatched: <the verb's stderr line>` and write the spec in this session, as above.
138
+ 3. Dispatch `Agent({ subagent_type: "spec", description: "write spec", prompt })`. The brief names the item, the folder from the envelope's scope, the answers gathered above, and the section list above as the content to write. It says that a phase command, not a run, dispatched the agent, and that the envelope is installed at `.claude/memory/band-envelope.json`.
139
+ 4. Show the agent's report and its `SNAP_HANDBACK` line; do not record the hand-back. A guard denial or a report without a hand-back is shown as it is, never retried another way.
140
+ 5. Run `node "$S/orchestrate.mjs" envelope --clear`, also when the agent was denied or ended without a hand-back. If it refuses, report the refusal and leave the file alone: a run now owns it.
141
+ 6. The written spec then goes through the approval wait below, as a spec written in this session would.
142
+
125
143
  Wait for explicit approval before proceeding to `/cc-plan`.
126
144
 
127
145
  Once approved, append a summary to `.claude/memory/project.md` under:
@@ -2,6 +2,27 @@
2
2
  description: "(Conductor) Analyze coverage gaps and write missing tests"
3
3
  ---
4
4
 
5
+ ## Role dispatch - qa (FEAT-061)
6
+
7
+ The final suite run belongs to the `qa` role agent, which may run only the project's test command (Guard 7). Before Phase 0, from the project root:
8
+
9
+ ```sh
10
+ S=.claude/scripts; [ -f "$S/orchestrate.mjs" ] || S=scripts
11
+ node "$S/orchestrate.mjs" envelope qa
12
+ ```
13
+
14
+ Branch on the first stdout line:
15
+
16
+ - **`not-installed:`** — a run of this session is live, and the line names the command qa runs. Write no test file: Guard 6 denies the write, and the run's code tasks own the writes. Skip Phase 0 and everything below it: dispatch qa now, as **Dispatch** says, and report.
17
+ - **`installed:`** — no run exists, and the verb wrote `.claude/memory/band-envelope.json` for qa with the test command in it. Continue with Phase 0 and the test writing below; at "Run tests after writing them", dispatch qa instead of running the suite here.
18
+ - **A non-zero exit, or any other first line** — print `qa not dispatched: <the verb's stderr line>` and continue with the flow below, running the suite in this session.
19
+
20
+ **Dispatch:** `Agent({ subagent_type: "qa", description: "run the suite", prompt })`. The brief names the scope (`$ARGUMENTS`). It says that a phase command, not a run, dispatched the agent, and either that the envelope is installed at `.claude/memory/band-envelope.json` or, after `not-installed:`, that no envelope was installed for it. Report qa's exact exit status and summary line as the result. A red suite, a guard denial or a report without a `SNAP_HANDBACK` line is reported as it is: never rerun the suite in this session to replace qa's answer.
21
+
22
+ **Clear:** after `installed:`, run `node "$S/orchestrate.mjs" envelope --clear` before this command ends, on whatever path it ends, also when the developer declines the run. If it refuses, report the refusal and leave the file alone: a run now owns it.
23
+
24
+ ---
25
+
5
26
  ## Phase 0 — Skill activation
6
27
 
7
28
  Before doing anything else, invoke the `subagent-driven-development` Superpowers skill:
@@ -47,7 +68,7 @@ Identify what is untested. Prioritize:
47
68
  4. Capture a screenshot
48
69
  5. Generate the Playwright test
49
70
 
50
- **Run tests after writing them.** Confirm before running.
71
+ **Run tests after writing them.** Confirm before running. After `installed:` in the role dispatch above, the run is qa's: dispatch it as **Dispatch** says, instead of running the suite here.
51
72
 
52
73
  **Report:**
53
74
  - Passed: N
@@ -307,6 +307,17 @@ function allowedCommands(role, run) {
307
307
  return [run.security.audit_command, run.security.scan_command].filter(nonEmptyString);
308
308
  }
309
309
 
310
+ // FEAT-061 D1: outside every run, qa's one command is the one a phase command put in its envelope.
311
+ // Any run file, even a foreign or unreadable one, withholds it, so a broken run's leftover envelope grants nothing.
312
+ function envelopeCommand(role, payload) {
313
+ const cwd = payloadCwd(payload);
314
+ if (role !== 'qa' || findRootHolding(cwd, ORCH_RUN_REL)) return null;
315
+ const root = findRootHolding(cwd, BAND_ENVELOPE_REL);
316
+ const env = root ? readEnvelope(join(root, ...BAND_ENVELOPE_REL)) : null;
317
+ const command = env?.sys.role === 'qa' && isPlainObject(env.mem) ? env.mem.p?.test_command : undefined;
318
+ return nonEmptyString(command) ? [command] : null;
319
+ }
320
+
310
321
  const unresolvedReason = (role) => (role === 'security'
311
322
  ? 'no live run in this session records the security commands, so security has no shell.'
312
323
  : `no live run in this session records a test command, so ${role} has no shell.`);
@@ -319,7 +330,7 @@ function roleShellDecision(role, input, payload) {
319
330
  const found = ROLE_SHELL_METACHARACTERS.find((m) => command.includes(m));
320
331
  if (found !== undefined) return deny(`Guard 7: ROLE_SHELL_CHAINING: the command contains ${JSON.stringify(found)}; a role runs one command, never a chain.`, 'ROLE_SHELL_CHAINING');
321
332
  const run = liveRunOf(payload);
322
- const allowed = run && allowedCommands(role, run);
333
+ const allowed = run ? allowedCommands(role, run) : envelopeCommand(role, payload);
323
334
  if (!allowed) return deny(`Guard 7: ROLE_SHELL_UNRESOLVED: ${unresolvedReason(role)}`, 'ROLE_SHELL_UNRESOLVED');
324
335
  if (allowed.includes(command)) return null;
325
336
  const which = role === 'security' ? `allowed commands are ${allowed.join(', ')}` : `allowed command is ${allowed[0]}`;
@@ -32,6 +32,7 @@ export const REVIEW_CAP = 3;
32
32
  // FEAT-057: fix rounds per run, fixed at start so the orchestrator's prompt cannot change the cap.
33
33
  export const AUDIT_ROUNDS_DEFAULT = 2;
34
34
  const AUDIT_ROUNDS_MAX = 5;
35
+ const SNAP_STORE_MAX_BYTES = 64 * 1024;
35
36
  const isAuditRounds = (n) => Number.isInteger(n) && n >= 0 && n <= AUDIT_ROUNDS_MAX;
36
37
  // Every outcome a closed loop can carry; only the skip is the orchestrator's to record (FEAT-058).
37
38
  const REVIEW_OUTCOME = /^(clean|cap|unchanged|skipped:[a-z][a-z0-9-]{0,39})$/;
@@ -68,7 +69,7 @@ const DEPENDENCY_STATES = ['audit', 'not-covered', 'disabled'];
68
69
  const OBJECT_NAME = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
69
70
  export const SECURITY_NOT_CONFIGURED = 'not-configured (run predates FEAT-034)';
70
71
 
71
- // A halt stops the run and is recorded in it (D12). A refusal is a misuse of the CLI:
72
+ // A halt stops the run and is recorded in it (D12); resume clears it from the last gate whose record still validates (FEAT-055). A refusal is a misuse of the CLI:
72
73
  // nothing is written and nothing is recorded.
73
74
  export class Halt extends Error {
74
75
  constructor(code, reason) { super(`${code}: ${reason}`); this.code = code; this.reason = reason; }
@@ -131,14 +132,14 @@ function readRun(root) {
131
132
 
132
133
  const saveRun = (root, run) => writeAtomic(join(root, RUN_FILE), JSON.stringify(run, null, 2) + '\n');
133
134
 
134
- // Every verb but start and end drives a run that must exist, be this session's, and not be halted.
135
+ // Every verb but start, resume and end drives a run that must exist, be this session's, and not be halted.
135
136
  function liveRun(root, sessionId) {
136
137
  const run = readRun(root);
137
138
  if (!run) throw new Refusal(`no run file at ${join(root, RUN_FILE)}; start one first`);
138
139
  if (run.session_id !== sessionId) {
139
140
  throw new Refusal(`run ${run.item} belongs to another session; end it, or start to replace it`);
140
141
  }
141
- if (run.halt) throw new Refusal(`run ${run.item} halted with ${run.halt.code}; recover with end, then start (D12)`);
142
+ if (run.halt) throw new Refusal(`run ${run.item} halted with ${run.halt.code}; recover with resume, or end then start (D12, FEAT-055)`);
142
143
  return run;
143
144
  }
144
145
 
@@ -330,8 +331,7 @@ const scanRef = (root) => relative(root, join(HERE, 'security-scan.mjs')).split(
330
331
 
331
332
  // FEAT-034: what the security seat will run, fixed at start so Guard 7 and the router read one record.
332
333
  function resolveSecurity(root, stack, { threshold, dependencyAudit }) {
333
- const head = gitValue(root, ['rev-parse', 'HEAD'], '');
334
- const base = OBJECT_NAME.test(head) ? head : null;
334
+ const base = headObject(root);
335
335
  const auditCommand = dependencyAudit ? PM_AUDIT_COMMAND[stack.packageManager] ?? null : null;
336
336
  const dependency = !dependencyAudit ? 'disabled' : auditCommand ? 'audit' : 'not-covered';
337
337
  // C14: the scanner writes complete lines, severity included; 'none' keeps a fixed arity outside git (plan decisions).
@@ -364,6 +364,14 @@ function gitValue(root, args, fallback) {
364
364
  return (r.status === 0 && r.stdout.trim()) || fallback;
365
365
  }
366
366
 
367
+ const headCommit = (root) => {
368
+ const head = gitValue(root, ['rev-parse', 'HEAD'], '0000000').toLowerCase();
369
+ return /^[0-9a-f]{7,40}$/.test(head) ? head : '0000000';
370
+ };
371
+
372
+ // A full object name or null: what an approval and the security seat anchor to (FEAT-055, FEAT-034).
373
+ const headObject = (root) => { const head = gitValue(root, ['rev-parse', 'HEAD'], ''); return OBJECT_NAME.test(head) ? head : null; };
374
+
367
375
  // A fix step's files come from the record, re-checked against the plan because the run file is writable.
368
376
  function codeScope(root, run, step) {
369
377
  if (step.fix !== undefined) { const { files } = fixDue(run); return fixScope(root, run, Array.isArray(files) ? files : [], step.fix); }
@@ -372,10 +380,9 @@ function codeScope(root, run, step) {
372
380
  }
373
381
 
374
382
  function envelopeFields(run, root, step) {
375
- const head = gitValue(root, ['rev-parse', 'HEAD'], '0000000').toLowerCase();
376
383
  const { tk, scope } = ROLE_ARTIFACTS[step.role];
377
384
  const fields = {
378
- ph: PHASE[step.role], c: /^[0-9a-f]{7,40}$/.test(head) ? head : '0000000', s: run.item,
385
+ ph: PHASE[step.role], c: headCommit(root), s: run.item,
379
386
  // A fix re-enters Build, so it carries Build's entry gate, the one --to code checks (D6).
380
387
  n: [], f: [], d: [], x: [], role: step.role, tk, gate: step.fix === undefined ? run.gate : expectedGate('code'),
381
388
  };
@@ -398,15 +405,21 @@ function envelopeFields(run, root, step) {
398
405
  const currentHash = (root, kind, rel) => { try { return documentHash(kind, readFileSync(join(root, rel))); } catch { return null; } };
399
406
 
400
407
  // FEAT-056: after define_approved, a changed spec or plan means the run would execute text nobody approved.
408
+ // FEAT-055: returned, not thrown, so resume refuses with the same text where install halts.
409
+ function approvedDocHalt(root, run, kind) {
410
+ const { path, sha256 } = run.approvals[kind] ?? {};
411
+ if (typeof path !== 'string' || typeof sha256 !== 'string') {
412
+ return new Halt('ORCH_APPROVAL_UNHASHED', `run ${run.item} records an approval without a document hash (started before FEAT-056); run end, then start`);
413
+ }
414
+ const now = currentHash(root, kind, path);
415
+ if (now === sha256) return null;
416
+ return new Halt('ORCH_APPROVED_DOC_CHANGED', `${kind} ${path} was approved at sha256 ${sha256} and ${now ? `now hashes ${now}` : 'can no longer be read'}`);
417
+ }
418
+
401
419
  function checkApprovedDocs(root, run) {
402
420
  for (const kind of ['spec', 'plan']) {
403
- const { path, sha256 } = run.approvals[kind] ?? {};
404
- if (typeof path !== 'string' || typeof sha256 !== 'string') {
405
- throw new Halt('ORCH_APPROVAL_UNHASHED', `run ${run.item} records an approval without a document hash (started before FEAT-056); run end, then start`);
406
- }
407
- const now = currentHash(root, kind, path);
408
- if (now === sha256) continue;
409
- throw new Halt('ORCH_APPROVED_DOC_CHANGED', `${kind} ${path} was approved at sha256 ${sha256} and ${now ? `now hashes ${now}` : 'can no longer be read'}`);
421
+ const failure = approvedDocHalt(root, run, kind);
422
+ if (failure) throw failure;
410
423
  }
411
424
  }
412
425
 
@@ -461,15 +474,20 @@ export function recordHandback(run, role, gate, verdict, extra = {}) {
461
474
  return { ...run, role: null, gate: forwardGate(run, role, gate), tasks, handbacks: [...run.handbacks, entry] };
462
475
  }
463
476
 
477
+ // FEAT-055: the validated text is returned too, so resume can validate the same bytes again.
464
478
  function parseHandback(text) {
465
479
  const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.startsWith('SNAP_HANDBACK '));
466
480
  if (lines.length !== 1) throw new Halt('ORCH_HANDBACK_MISSING', `expected exactly one SNAP_HANDBACK line, found ${lines.length}`);
467
481
  const json = lines[0].slice('SNAP_HANDBACK '.length).trim();
482
+ // The SNAP is stored in the run file, which the hooks stop reading past their envelope cap (Guard 6 would go from deny to warn).
483
+ if (Buffer.byteLength(json) > SNAP_STORE_MAX_BYTES) {
484
+ throw new Halt('ORCH_HANDBACK_INVALID', `the hand-back SNAP is larger than ${SNAP_STORE_MAX_BYTES} bytes`);
485
+ }
468
486
  const error = validate(json + '\n');
469
487
  if (error) throw new Halt('ORCH_HANDBACK_INVALID', error);
470
488
  const env = JSON.parse(json);
471
489
  if (env.v !== 3 && env.v !== 4) throw new Halt('ORCH_HANDBACK_INVALID', `a hand-back must be a v3 or v4 envelope, got v${env.v}`);
472
- return env;
490
+ return { env, snap: json };
473
491
  }
474
492
 
475
493
  function auditStop({ verdict, blockers }, round, cap) {
@@ -739,14 +757,14 @@ async function handback(root, sessionId, role, bytes) {
739
757
  throw new Halt('ORCH_HANDBACK_CONFLICT', `${role} already handed back for this position; a second report is not routed`);
740
758
  }
741
759
  if (!run.role || run.role !== role) throw new Refusal(`handback ${role}: the dispatched role is ${run.role ?? 'none'}`);
742
- const env = parseHandback(text);
760
+ const { env, snap } = parseHandback(text);
743
761
  if (env.sys.role !== role) throw new Halt('ORCH_HANDBACK_ROLE_MISMATCH', `dispatched ${role}, the hand-back names ${env.sys.role}`);
744
762
  if (!MAY_HAND_BACK[role].includes(env.ops.gate)) {
745
763
  throw new Halt('ORCH_GATE_UNEARNED', `${role} may hand back ${MAY_HAND_BACK[role].join('|')}, not ${env.ops.gate}`);
746
764
  }
747
765
  if (role === 'security') return securityHandback(root, run, env.ops.gate, text);
748
766
  const verdict = role === 'audit' ? parseVerdict(text) : null;
749
- const recorded = recordHandback(run, role, env.ops.gate, verdict?.verdict);
767
+ const recorded = recordHandback(run, role, env.ops.gate, verdict?.verdict, { snap });
750
768
  saveRun(root, recorded);
751
769
  // Saved first, so the halt cli records lands on top of the audit entry (FEAT-060, FEAT-057).
752
770
  if (verdict && verdict.verdict !== 'APPROVE') return auditFix(root, recorded, verdict, bytes);
@@ -755,6 +773,7 @@ async function handback(root, sessionId, role, bytes) {
755
773
  }
756
774
 
757
775
  // Two human approvals, one gate write (A4): only an approved plan writes define_approved.
776
+ // FEAT-055: and HEAD at that moment, so resume can tell whether history still holds it.
758
777
  // FEAT-056: each approval binds the bytes the owner was shown; a stale hash writes nothing.
759
778
  function approve(root, sessionId, what, rel, shown) {
760
779
  const run = liveRun(root, sessionId);
@@ -767,7 +786,7 @@ function approve(root, sessionId, what, rel, shown) {
767
786
  if (sha256 !== shown.toLowerCase()) {
768
787
  throw new Refusal(`ORCH_DOC_HASH_STALE: ${what} ${rel} hashes ${sha256}, not the ${shown} that was shown; show the document again`);
769
788
  }
770
- const approval = { at: new Date().toISOString(), by: gitValue(root, ['config', 'user.name'], 'unknown'), path: rel, sha256 };
789
+ const approval = { at: new Date().toISOString(), by: gitValue(root, ['config', 'user.name'], 'unknown'), path: rel, sha256, commit: headObject(root) };
771
790
  if (what === 'plan') return approvePlan(root, run, content.toString('utf8'), approval);
772
791
  saveRun(root, { ...run, approvals: { ...run.approvals, spec: approval } });
773
792
  return `spec approved: sha256 ${sha256}`;
@@ -792,6 +811,105 @@ function checkLoopClosed(run, what) {
792
811
  throw new Refusal(`ORCH_REVIEW_OPEN: review ${what} is ${state}; close it before the approval`);
793
812
  }
794
813
 
814
+ const RESUME_USAGE = 'usage: orchestrate.mjs resume';
815
+ const RESTART = 'recover with end, then start';
816
+ const RECORD_KINDS = ['spec', 'plan'];
817
+
818
+ // FEAT-055: every failure is a refusal, so a failed resume leaves the halt it was asked to clear as it was.
819
+ function haltedRun(root, sessionId, args) {
820
+ if (args.length > 0) throw new Refusal(RESUME_USAGE);
821
+ let run = null;
822
+ try { run = readRun(root); } catch { /* an invalid run file is judged below */ }
823
+ if (!run) throw new Refusal(`ORCH_RESUME_NO_RUN: no valid run file at ${join(root, RUN_FILE)}`);
824
+ if (!run.halt) throw new Refusal(`ORCH_RESUME_NOT_HALTED: run ${run.item} is not halted; continue with ${describeStep(nextStep(run))}`);
825
+ if (!sessionId) throw new Refusal('ORCH_NO_SESSION_ID: CLAUDE_CODE_SESSION_ID is absent or empty, so Guard 6 could never bind this run');
826
+ if (!run.approvals.spec) throw new Refusal(`ORCH_RESUME_NO_GATE: run ${run.item} records no spec approval, so no gate is left to resume from; ${RESTART}`);
827
+ return run;
828
+ }
829
+
830
+ // 0: HEAD descends from commit; 1: it does not; anything else: git cannot answer. A non-hex name never reaches git as an option.
831
+ function ancestry(root, commit) {
832
+ if (typeof commit !== 'string' || !/^[0-9a-f]{7,64}$/.test(commit)) return null;
833
+ return spawnSync('git', ['merge-base', '--is-ancestor', commit, 'HEAD'], { cwd: root, encoding: 'utf8' }).status;
834
+ }
835
+
836
+ const unanchored = (kind, reason) => new Refusal(`ORCH_RESUME_UNANCHORED: the ${kind} approval ${reason}; ${RESTART}`);
837
+
838
+ // An approval is the owner's act, which the run cannot redo, so a failing one refuses the whole resume.
839
+ function checkApproval(root, run, kind) {
840
+ const failure = approvedDocHalt(root, run, kind);
841
+ if (failure?.code === 'ORCH_APPROVAL_UNHASHED') throw new Refusal(failure.message);
842
+ const { commit } = run.approvals[kind];
843
+ if (commit === undefined) throw unanchored(kind, 'records no commit (approved before FEAT-055)');
844
+ if (commit === null) throw unanchored(kind, 'records a null commit (approved outside a git repository or before its first commit)');
845
+ if (failure) throw new Refusal(`${failure.message}; ${RESTART}`);
846
+ const answer = ancestry(root, commit);
847
+ if (answer === 1) {
848
+ throw new Refusal(`ORCH_RESUME_HISTORY_REWRITTEN: HEAD ${gitValue(root, ['rev-parse', 'HEAD'], 'unknown')} does not descend from the ${kind} approval's commit ${commit}; ${RESTART}`);
849
+ }
850
+ if (answer !== 0) throw unanchored(kind, `commit ${String(commit)} cannot be checked against HEAD`);
851
+ }
852
+
853
+ // The conflict's last entry is ambiguous, except a spec or plan entry whose approval already stands.
854
+ function candidateEntries(run) {
855
+ const last = run.handbacks.at(-1);
856
+ if (run.halt.code !== 'ORCH_HANDBACK_CONFLICT' || !last) return run.handbacks;
857
+ return RECORD_KINDS.includes(last.role) && run.approvals[last.role] ? run.handbacks : run.handbacks.slice(0, -1);
858
+ }
859
+
860
+ // A task entry still describes the repository: its position, its SNAP and its commit all hold.
861
+ function taskEntryHolds(root, entry, taskId) {
862
+ if (entry.task !== taskId || typeof entry.snap !== 'string' || validate(`${entry.snap}\n`) !== '') return false;
863
+ let env = null;
864
+ try { env = JSON.parse(entry.snap); } catch { return false; }
865
+ return env?.sys?.role === 'code' && ancestry(root, env.sys.c) === 0;
866
+ }
867
+
868
+ // Each approved document's entry, then Build's task entries up to the first that fails; Verify is always redone.
869
+ function keptEntries(root, run) {
870
+ const entries = candidateEntries(run);
871
+ const approved = RECORD_KINDS.filter((k) => run.approvals[k]).map((k) => entries.find((h) => h.role === k)).filter(Boolean);
872
+ if (!run.approvals.plan) return { kept: approved, tasks: 0 };
873
+ const tasks = entries.filter((h) => h.role === 'code' && !('fix' in h));
874
+ let n = 0;
875
+ while (n < tasks.length && n < run.tasks.ids.length && taskEntryHolds(root, tasks[n], run.tasks.ids[n])) n += 1;
876
+ return { kept: [...approved, ...tasks.slice(0, n)], tasks: n };
877
+ }
878
+
879
+ // Only approvePlan writes define_approved, and only the last task's hand-back forwards build_executed.
880
+ const resumedGate = (run, tasks) => (!run.approvals.plan ? 'boundary_routed' : tasks < run.tasks.ids.length ? 'define_approved' : 'build_executed');
881
+
882
+ // A dropped document's loop is cleared with it, so the redone document gets a fresh review loop.
883
+ const resumedReview = (run, kept) => (isPlainObject(run.review)
884
+ ? Object.fromEntries(Object.entries(run.review).filter(([k]) => kept.some((h) => h.role === k))) : run.review);
885
+
886
+ function nextLine(run) {
887
+ const step = nextStep(run);
888
+ return step.task ? `${describeStep(step)} (task ${run.tasks.done + 1} of ${run.tasks.ids.length})` : describeStep(step);
889
+ }
890
+
891
+ // FEAT-055: back to the last gate whose record still validates; every record after it is dropped and redone.
892
+ function resume(root, sessionId, args) {
893
+ const run = haltedRun(root, sessionId, args);
894
+ const approvals = RECORD_KINDS.filter((k) => run.approvals[k]);
895
+ for (const kind of approvals) checkApproval(root, run, kind);
896
+ const { kept, tasks } = keptEntries(root, run);
897
+ const records = kept.length + approvals.length;
898
+ const dropped = run.handbacks.length - kept.length;
899
+ const { code, reason, at } = run.halt;
900
+ const resumes = [...(Array.isArray(run.resumes) ? run.resumes : []), { at: new Date().toISOString(), halt: { code, reason, at }, kept: records, dropped }];
901
+ const next = {
902
+ ...run, session_id: sessionId, role: null, halt: null, gate: resumedGate(run, tasks),
903
+ handbacks: kept, tasks: { ...run.tasks, done: tasks }, review: resumedReview(run, kept), resumes,
904
+ };
905
+ // Computed before the write: resume records no halt, so a throw after saveRun would leave a changed run behind a failed exit.
906
+ const line = `run ${run.item} resumed after ${code} from ${next.gate}: kept ${records} record(s), dropped ${dropped}; next: ${nextLine(next)}`;
907
+ saveRun(root, next);
908
+ // The halted agent's envelope; the hand-back and review files stay for the owner and are overwritten on re-dispatch.
909
+ rmSync(join(root, ENVELOPE_FILE), { force: true });
910
+ return line;
911
+ }
912
+
795
913
  const reviewWellFormed = (flag, arg, extra) => extra === undefined
796
914
  && (flag === '--round' ? arg !== undefined : flag === '--record' ? arg === undefined : flag === '--close' && SKIP_OUTCOME.test(arg ?? ''));
797
915
 
@@ -942,6 +1060,89 @@ function recordHalt(root, halt) {
942
1060
  } catch { /* an unreadable run file cannot carry its own halt */ }
943
1061
  }
944
1062
 
1063
+ // FEAT-061: a phase command dispatches its role outside a run. With a run file present, even a foreign or broken one, the verb writes nothing: the envelope path is the run's.
1064
+ const ENVELOPE_ROLES = ['spec', 'plan', 'audit', 'qa'];
1065
+ const ENVELOPE_USAGE = 'usage: orchestrate.mjs envelope <spec|plan|audit|qa> [--item <label>] | --clear';
1066
+ const LABEL = /^[a-zA-Z0-9._-]+$/; // The sys.s pattern snap-validate enforces.
1067
+
1068
+ function parseEnvelopeArgs(args) {
1069
+ if (args.length === 1 && args[0] === '--clear') return { clear: true };
1070
+ const [role, flag, label] = args;
1071
+ if (!ENVELOPE_ROLES.includes(role)) throw new Refusal(ENVELOPE_USAGE);
1072
+ if (args.length === 1) return { role, label: 'adhoc' };
1073
+ if (args.length === 3 && flag === '--item' && LABEL.test(label)) return { role, label };
1074
+ throw new Refusal(ENVELOPE_USAGE);
1075
+ }
1076
+
1077
+ // Read without throwing: an unreadable run file is another owner's to clear, never this verb's halt.
1078
+ function runState(root, sessionId) {
1079
+ const path = join(root, RUN_FILE);
1080
+ if (!existsSync(path)) return { state: 'N' };
1081
+ let run = null;
1082
+ try { run = JSON.parse(readFileSync(path, 'utf8')); } catch { /* judged below */ }
1083
+ if (isValidRun(run) && sessionId && run.session_id === sessionId) return { state: 'L', run, path };
1084
+ return { state: 'O', path };
1085
+ }
1086
+
1087
+ function withRunFile(root, role, st) {
1088
+ const live = st.state === 'L';
1089
+ if (role === 'audit') {
1090
+ const who = live ? `live run ${st.run.item}` : `a run file at ${st.path} belongs to another session or is unreadable`;
1091
+ return `not-installed: ${who}; audit has no write tool and no shell, so it needs no envelope`;
1092
+ }
1093
+ if (role === 'qa' && live) {
1094
+ const command = st.run.test_command;
1095
+ if (typeof command !== 'string' || command === '') {
1096
+ throw new Refusal(`envelope qa: run ${st.run.item} records no test command, so Guard 7 grants qa no shell; end it, then start`);
1097
+ }
1098
+ return `not-installed: live run ${st.run.item}; qa runs ${command}`;
1099
+ }
1100
+ if (live) {
1101
+ throw new Refusal(`envelope ${role}: run ${st.run.item} is live in this session and its Define band writes this document; continue with /cc-orchestrate, or end the run`);
1102
+ }
1103
+ throw new Refusal(`envelope ${role}: a run file at ${st.path} belongs to another session or is unreadable; clear it with: node ${scriptRef(root)} end`);
1104
+ }
1105
+
1106
+ function adhocFields(root, role, label) {
1107
+ const fields = {
1108
+ ph: PHASE[role], c: headCommit(root), s: label, n: [], f: [], d: [], x: [], role, tk: ROLE_ARTIFACTS[role].tk, gate: expectedGate(role),
1109
+ };
1110
+ if (role === 'spec' || role === 'plan') fields.scope = resolveDocs(root, label).scopes[role];
1111
+ if (role === 'qa') fields.p = { test_command: checkTestCommand(resolveTestCommand(root)) };
1112
+ return fields;
1113
+ }
1114
+
1115
+ function installAdhoc(root, role, label) {
1116
+ if (!findAgent(role, root)) {
1117
+ throw new Halt('ORCH_AGENT_MISSING', `no agent definition named ${role} in .claude/agents/ or ~/.claude/agents/`);
1118
+ }
1119
+ const built = runScript('snap-build.mjs', [], JSON.stringify(adhocFields(root, role, label)));
1120
+ if (built.status !== 0) throw new Halt('SNAP_ERROR', built.err);
1121
+ const error = validate(built.out, role);
1122
+ if (error) throw new Halt('SNAP_ERROR', error);
1123
+ writeAtomic(join(root, ENVELOPE_FILE), built.out);
1124
+ return `installed: ${role} envelope at ${ENVELOPE_FILE}\n${built.out.trim()}`;
1125
+ }
1126
+
1127
+ function clearAdhoc(root, st) {
1128
+ if (st.state !== 'N') throw new Refusal(`envelope --clear: a run file exists at ${st.path}; the envelope belongs to that run`);
1129
+ const path = join(root, ENVELOPE_FILE);
1130
+ if (!existsSync(path)) return 'no envelope';
1131
+ rmSync(path, { force: true });
1132
+ return 'cleared';
1133
+ }
1134
+
1135
+ function envelopeVerb(root, sessionId, args) {
1136
+ const parsed = parseEnvelopeArgs(args);
1137
+ const st = runState(root, sessionId);
1138
+ if (parsed.clear) return clearAdhoc(root, st);
1139
+ if (st.state !== 'N') return withRunFile(root, parsed.role, st);
1140
+ // Every failure is a Refusal, so no halt is ever recorded in a run this verb does not own.
1141
+ try { return installAdhoc(root, parsed.role, parsed.label); } catch (e) {
1142
+ throw e instanceof Halt ? new Refusal(e.message) : e;
1143
+ }
1144
+ }
1145
+
945
1146
  export async function cli(argv, env, cwd = process.cwd()) {
946
1147
  const [verb, a, b, c] = argv;
947
1148
  const root = findRunRoot(cwd);
@@ -953,16 +1154,19 @@ export async function cli(argv, env, cwd = process.cwd()) {
953
1154
  approve: () => approve(root, sid, a, b, c),
954
1155
  hash: () => hashDoc(root, a, b),
955
1156
  review: () => review(root, sid, argv.slice(1)),
1157
+ resume: () => resume(root, sid, argv.slice(1)),
1158
+ envelope: () => envelopeVerb(root, sid, argv.slice(1)),
956
1159
  end: () => end(root),
957
1160
  };
958
1161
  try {
959
- if (!verbs[verb]) throw new Refusal('usage: orchestrate.mjs start|install|handback|approve|hash|review|end');
1162
+ if (!verbs[verb]) throw new Refusal('usage: orchestrate.mjs start|install|handback|approve|hash|review|resume|envelope|end');
960
1163
  process.stdout.write((await verbs[verb]()) + '\n');
961
1164
  return 0;
962
1165
  } catch (e) {
963
1166
  if (e instanceof Refusal) { process.stderr.write(`orchestrate: ${e.message}\n`); return 2; }
964
1167
  if (!(e instanceof Halt)) throw e;
965
- if (verb !== 'start') recordHalt(root, e);
1168
+ // resume never records a halt: one thrown by a helper it reuses must not overwrite the halt it was resuming (FEAT-055).
1169
+ if (!['start', 'envelope', 'resume'].includes(verb)) recordHalt(root, e);
966
1170
  process.stderr.write(`${e.code}: ${e.reason}\n`);
967
1171
  return 1;
968
1172
  }