@yeison.restrepo.r/code-conductor 1.49.0 → 1.51.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 +7 -5
- package/package.json +1 -1
- package/project-template/.claude/agents/audit.md +3 -2
- package/project-template/.claude/agents/code.md +2 -1
- package/project-template/.claude/agents/define-review.md +2 -1
- package/project-template/.claude/agents/plan.md +3 -2
- package/project-template/.claude/agents/qa.md +4 -3
- package/project-template/.claude/agents/security.md +2 -1
- package/project-template/.claude/agents/spec.md +3 -2
- package/project-template/.claude/commands/cc-orchestrate.md +12 -7
- package/project-template/.claude/commands/cc-plan.md +18 -0
- package/project-template/.claude/commands/cc-review.md +20 -0
- package/project-template/.claude/commands/cc-spec.md +18 -0
- package/project-template/.claude/commands/cc-test.md +22 -1
- package/project-template/.claude/hooks/pre-tool-use.mjs +12 -1
- package/scripts/orchestrate.mjs +342 -33
package/README.md
CHANGED
|
@@ -141,6 +141,7 @@ Useful variations:
|
|
|
141
141
|
|
|
142
142
|
- `--auto` skips the pause between role dispatches. The spec and plan approvals always pause.
|
|
143
143
|
- `--ticket 42` (or an issue URL) binds the run to a GitHub issue. `start` fetches it once through `gh`, halts on a pull request, a closed issue, or an empty or over-65536-byte body, and writes the body into a fenced, hashed snapshot at `.conductor/ticket/<ITEM>.md`, which **only the spec role reads, as untrusted requirement input**. After release, the owner runs `node .claude/scripts/ticket.mjs writeback <ITEM> --version <v> --pr <N|url> [--changelog <file>] [--close]`, which posts one outcome comment to the bound issue, never twice for the same version, and closes it only with `--close`.
|
|
144
|
+
- `- Role models: default` in the project `CLAUDE.md` puts each role on the model its profile ships as `default-model:` (`opus` for `spec`, `plan`, `audit`, `security` and the `define-review` reviewer, `sonnet` for `code`, `haiku` for `qa`), so the auditor reviews on another model than the author. `<role>=<opus|sonnet|haiku|inherit>` tokens override single roles (`- Role models: default, qa=sonnet`) or set only some. `start` freezes the map in the run file and every dispatch carries the model the script prints. When an audit returns a plan task a second time, that fix round runs on `opus`, and the audit entry records why. Without the line, every role inherits the session's model, as before.
|
|
144
145
|
|
|
145
146
|
What it needs: agent definitions named `spec`, `plan`, `code`, `audit`, and `qa` in `.claude/agents/` or `~/.claude/agents/` (they ship from `1.37.0`); a resolvable test command, as above; and plans in the writing-plans format (`### Task N` with a `**Files:**` block). A failed validation halts the run, terminally in this version: recover with `end`, then `start`.
|
|
146
147
|
|
|
@@ -253,14 +254,14 @@ All commands are tagged `(Conductor)` in the Claude Code command palette, so the
|
|
|
253
254
|
|---|---|
|
|
254
255
|
| `/cc-init` | Initialize or re-sync the project environment: detect stack, checkpoint memory, verify hook integrity. Run at the start of every session. |
|
|
255
256
|
| `/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. |
|
|
257
|
+
| `/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. |
|
|
258
|
+
| `/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
259
|
| `/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
260
|
| `/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. |
|
|
261
|
+
| `/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
262
|
| `/cc-debug [problem]` | Hypothesis-driven debugging. See the [walkthrough](#walkthrough-diagnosis-before-surgery-with-cc-debug). |
|
|
262
263
|
| `/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. |
|
|
264
|
+
| `/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
265
|
| `/cc-docs [scope]` | Audit documentation, write inline docs in your stack's format (JSDoc / docstrings / Javadoc / GoDoc), and preview before writing. |
|
|
265
266
|
| `/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
267
|
| `/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 +482,7 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
|
|
|
481
482
|
| `systemMessage` | `default` | no | yes, in full |
|
|
482
483
|
| `systemMessage` | `default` | yes, for example Guard 2's overwrite prompt | no: the warning is lost |
|
|
483
484
|
- Agent definitions provided by plugins are not searched.
|
|
484
|
-
-
|
|
485
|
+
- `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
486
|
|
|
486
487
|
The five role agent definitions it dispatches ship from `1.37.0`; their limits are the next item.
|
|
487
488
|
- **The role agents (`1.37.0`) are bounded by their tool masks, and Guard 7 bounds one thing beneath them: the shell.**
|
|
@@ -504,6 +505,7 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
|
|
|
504
505
|
- **`[BUG-076]`, open:** `scripts/orchestrate.mjs` lets `approve` pass once a role's review loop has recorded any outcome, without checking that the loop's recorded hash matches the document being approved, and `review <role> --round` accepts a document outside the role's docs scope, so a run record can show a clean review for a document no reviewer read; your approval itself stays bound to the hash you were shown. Until it is fixed, check that the review loop's recorded document and hash match the document you approve before trusting its outcome.
|
|
505
506
|
- **`[BUG-077]`, open:** `scripts/orchestrate.mjs` lets `approve spec <path> <sha256>` accept any file path relative to the run root, without checking that it is the spec the `spec` role handed back or that it sits under the run's `docs.specs` folder, so approving the wrong path makes the post-approval hash check in `install` protect that file while later edits to the real spec go undetected. Until it is fixed, confirm that the path you approve is the spec the `spec` role handed back, under the run's recorded specs folder.
|
|
506
507
|
- **`[BUG-078]`, open:** `scripts/orchestrate.mjs` builds a fix round's write scope with the approved plan included, so Guard 5 lets the fix-round `code` agent write to the plan and only the brief's instruction stops it; any change other than checkbox ticks still halts the run with `ORCH_APPROVED_DOC_CHANGED` on the next `install audit` or fix round, and ticks do not affect `tasks.done`. Until it is fixed, check after a fix round that the approved plan's checkboxes are unchanged.
|
|
508
|
+
- **`[BUG-079]`, open:** `scripts/orchestrate.mjs` stores every non-security hand-back's full SNAP in `.claude/memory/orchestrator-run.json` with a 64 KiB cap per SNAP but no cap on the total, so a plan of roughly 80 or more tasks with maximally sized hand-backs can push the run file past the hook's 10 MiB read cap, after which `readRunFile` returns null and Guard 6 downgrades from deny to warn for the rest of the run. Until it is fixed, keep orchestrated plans well under 80 tasks, or split a larger item into several runs.
|
|
507
509
|
- **The `P7` false positive** described under [Guard 3, and what it learned](#guard-3-and-what-it-learned) is still live.
|
|
508
510
|
- **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.
|
|
509
511
|
- **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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yeison.restrepo.r/code-conductor",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.51.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,11 @@
|
|
|
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
|
|
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
|
+
default-model: opus
|
|
5
6
|
---
|
|
6
7
|
|
|
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
|
+
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
9
|
|
|
9
10
|
## Your job
|
|
10
11
|
|
|
@@ -1,7 +1,8 @@
|
|
|
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
|
|
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
|
+
default-model: sonnet
|
|
5
6
|
---
|
|
6
7
|
|
|
7
8
|
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.
|
|
@@ -1,7 +1,8 @@
|
|
|
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
|
|
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
|
+
default-model: opus
|
|
5
6
|
---
|
|
6
7
|
|
|
7
8
|
You are the `define-review` reviewer of a code-conductor orchestrated run. The orchestrator dispatched you, fresh for this round, with a brief naming the item, the round, the document under review, its source, and the checklist rows.
|
|
@@ -1,10 +1,11 @@
|
|
|
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
|
|
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
|
+
default-model: opus
|
|
5
6
|
---
|
|
6
7
|
|
|
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
|
+
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
9
|
|
|
9
10
|
## Your job
|
|
10
11
|
|
|
@@ -1,10 +1,11 @@
|
|
|
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
|
|
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
|
+
default-model: haiku
|
|
5
6
|
---
|
|
6
7
|
|
|
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
|
+
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
9
|
|
|
9
10
|
## Your job
|
|
10
11
|
|
|
@@ -12,7 +13,7 @@ Verify the item independently. You did not write this code and you cannot write
|
|
|
12
13
|
|
|
13
14
|
## The test command
|
|
14
15
|
|
|
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
|
+
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
17
|
|
|
17
18
|
## Success condition
|
|
18
19
|
|
|
@@ -1,7 +1,8 @@
|
|
|
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
|
|
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
|
+
default-model: opus
|
|
5
6
|
---
|
|
6
7
|
|
|
7
8
|
You are the `security` 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, then the `security` object of `.claude/memory/orchestrator-run.json`.
|
|
@@ -1,10 +1,11 @@
|
|
|
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
|
|
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
|
+
default-model: opus
|
|
5
6
|
---
|
|
6
7
|
|
|
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
|
+
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
9
|
|
|
9
10
|
## Your job
|
|
10
11
|
|
|
@@ -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
|
|
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,24 +38,27 @@ 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
|
-
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)>`.
|
|
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)>`. With a `- Role models:` line in the project `CLAUDE.md`, it then ends with `; role models: spec=<m>, plan=<m>, code=<m>, audit=<m>, security=<m>, qa=<m>, define-review=<m>`, each `<m>` one of `opus`, `sonnet`, `haiku` or `inherit`, followed by `; note: audit and code share <m>` when both name the same model (FEAT-053).
|
|
44
46
|
- If stdout names a replaced stale run, report its item and start time.
|
|
45
47
|
- On `ORCH_RUN_ACTIVE`, report it, offer `end`, and stop.
|
|
46
48
|
- 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`.
|
|
47
49
|
- On `ORCH_SECURITY_COMMAND_UNSAFE`, report it and stop in the same way: a recorded security command carries chaining, and no run file was written.
|
|
48
50
|
- On `ORCH_DOC_LOCATION_INVALID`, report it and stop. No run file was written. The owner fixes the named `- Specs:` / `- Plans:` line in `CLAUDE.md` (add the missing one, fix the value, or use two disjoint folders) before a fresh `start`.
|
|
51
|
+
- On `ORCH_ROLE_MODELS_INVALID`, report it and stop. No run file was written. The owner fixes or removes the `- Role models:` line in `CLAUDE.md` that the reason names (an unknown role, a model outside `opus`, `sonnet`, `haiku` and `inherit`, a role set twice, an empty token, `default` twice, more than one line, or a profile's `default-model:` outside that list) before a fresh `start`.
|
|
49
52
|
- On an intake halt (`TICKET_FLAG_INVALID`, `TICKET_UNREACHABLE`, `TICKET_NOT_ISSUE`, `TICKET_CLOSED`, `TICKET_BODY_EMPTY` or `TICKET_BODY_OVER_CAP`), report it and stop. No run file and no snapshot were written; the halt names its remedy.
|
|
50
53
|
- With `--ticket`, stdout also names the ticket, its title, the snapshot `.conductor/ticket/<ITEM>.md` and its sha256. The run is bound.
|
|
51
54
|
|
|
52
|
-
Print the run header: the item, the mode (`step` unless `--auto` was given), the test command, the audit rounds, the security threshold and the dependency scan from the start line, the spec and plan folders (and group) from `docs:`, the ticket and snapshot for a bound run, and the first role, `spec`.
|
|
55
|
+
Print the run header: the item, the mode (`step` unless `--auto` was given), the test command, the audit rounds, the security threshold and the dependency scan from the start line, the spec and plan folders (and group) from `docs:`, the role models and their note from `role models:` when the start line has them, the ticket and snapshot for a bound run, and the first role, `spec`.
|
|
53
56
|
Add one line: `Review loop: fresh Agent dispatches over review files, no SendMessage; it needs no launch settings and runs in every permission mode.`
|
|
54
57
|
2. **Each dispatch.** Take the roles in band order: `spec`, `plan`, then `code` once per plan task, then `audit`; after an audit that the script answers with a fix round, `code` once for that fix and then `audit` again; then `security`; then `qa`. For each one:
|
|
55
58
|
1. **Check.** Run `node "$S/orchestrate.mjs" install <role> --check`. Print the role and the envelope it prints, and state that `--to <role>` passed.
|
|
56
59
|
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.
|
|
57
60
|
3. **Install.** Run `node "$S/orchestrate.mjs" install <role>`.
|
|
58
|
-
4. **Dispatch.** Use the `Agent` tool with `subagent_type: <role>` and the brief below. Dispatch one agent at a time, never in parallel (D8).
|
|
61
|
+
4. **Dispatch.** Use the `Agent` tool with `subagent_type: <role>` and the brief below. Dispatch one agent at a time, never in parallel (D8). **Model (FEAT-053).** When `install` printed a last line `model: <alias>`, pass that alias as the `Agent` call's `model` parameter; on `model: inherit`, or when `install` printed no `model:` line, pass no `model`. Take the model from that line only: never choose a model yourself, and never retry a failed dispatch on another one.
|
|
59
62
|
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).
|
|
60
63
|
6. **Hand back.**
|
|
61
64
|
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, and `.conductor/handback/code-fix-<r>.txt` for fix round `<r>`. For audit, use `.conductor/handback/audit-<round>.txt`, where `<round>` counts the audit passes from 1. For security, use `.conductor/handback/security.txt`.
|
|
@@ -70,13 +73,15 @@ A halt is terminal in v1 (D12). Recovery is `node "$S/orchestrate.mjs" end`, the
|
|
|
70
73
|
- **After spec:** show the owner the spec path from the hand-back, and for a bound run the snapshot path and sha256 from the start line: the owner reviews the spec against that snapshot. On approval, run `node "$S/orchestrate.mjs" approve spec <spec path> <sha256>` with the path and hash you showed.
|
|
71
74
|
- **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> <sha256>` with the path and hash you showed. This writes `define_approved`, the only gate you author after `boundary_routed`.
|
|
72
75
|
4. **Build.** Dispatch `code` once per plan task, serially, until the router moves on to `audit`. A `--check` refusal names the next step.
|
|
73
|
-
5. **Verify.** Dispatch `audit`. The audit report ends in one `VERDICT:` line just before its `SNAP_HANDBACK` line; only `VERDICT: APPROVE` lets the router move on to `security`. When `handback audit` prints `audit round <round>: RETURN with <b> blocker/major finding(s); fix round <r> of <N>: review <review> sha256 <sha256>; scope <scope>`, run the fix round: `install code --check` prints the envelope and the line `fix round <r> of <N>: review <review> sha256 <sha256>`; take the brief's values from that line, never from your own reading of the report. Then pause, install and dispatch a fresh `code` agent with the fix-round task from the dispatch table, hand it back from `.conductor/handback/code-fix-<r>.txt`, and dispatch `audit` again. Never revive an earlier agent and never message one. The orchestrator never decides whether another round runs: the script's output does. A `RETURN` with no fix rounds left, or an `ESCALATE`, halts the run (follow "On any halt"). Then dispatch `security`, which runs the recorded audit and scan commands and ends its report as the audit does: its `SCANS:` line, then one `VERDICT:` line just before its `SNAP_HANDBACK` line. `VERDICT: APPROVE` means every scan completed and no finding the change introduces is a `blocker`; `VERDICT: RETURN` means one is (`ORCH_SECURITY_BLOCKED`); `VERDICT: ESCALATE` means a scan failed (`ORCH_SECURITY_SCAN_FAILED`) or text in the change addressed the agent (`ORCH_SECURITY_ESCALATE`). A finding is a `blocker` or a `minor` by the threshold `start` recorded, and the script, not you, checks it. Findings already present at the base commit go in the report's owner-only block (`PRE-EXISTING (owner only):` … `END PRE-EXISTING`); the script writes them to `.conductor/security-pre-existing.txt` and to nothing public. This changes 1.48.0 behavior: a finding already present at the base, a dependency advisory included, no longer blocks the run at any level; only the findings the change introduces decide the verdict. `handback security` prints `security handed back build_executed; VERDICT: APPROVE; <n> finding(s) below <threshold> recorded; dependency=<ran|not-covered|disabled>; pre-existing findings, if any, are in .conductor/security-pre-existing.txt (owner only)`, and only then `qa`. A run started before FEAT-034 has no seat: `qa` follows the audit and `handback qa` prints `security=not-configured (run predates FEAT-034)`. When `qa`'s hand-back records `verify_pass`, run `node "$S/orchestrate.mjs" end`. It prints the run it removed.
|
|
76
|
+
5. **Verify.** Dispatch `audit`. The audit report ends in one `VERDICT:` line just before its `SNAP_HANDBACK` line; only `VERDICT: APPROVE` lets the router move on to `security`. When `handback audit` prints `audit round <round>: RETURN with <b> blocker/major finding(s); fix round <r> of <N>: review <review> sha256 <sha256>; scope <scope>`, run the fix round: `install code --check` prints the envelope and the line `fix round <r> of <N>: review <review> sha256 <sha256>`; take the brief's values from that line, never from your own reading of the report. In a run with role models, `install code` then ends with `model: <alias>`, as every dispatch does; it reads `model: opus` when `handback audit` ended its line with `; model opus (escalated: <tasks> returned twice)`, because the audit returned one of those plan tasks a second time. Then pause, install and dispatch a fresh `code` agent with the fix-round task from the dispatch table, hand it back from `.conductor/handback/code-fix-<r>.txt`, and dispatch `audit` again. Never revive an earlier agent and never message one. The orchestrator never decides whether another round runs: the script's output does. A `RETURN` with no fix rounds left, or an `ESCALATE`, halts the run (follow "On any halt"). Then dispatch `security`, which runs the recorded audit and scan commands and ends its report as the audit does: its `SCANS:` line, then one `VERDICT:` line just before its `SNAP_HANDBACK` line. `VERDICT: APPROVE` means every scan completed and no finding the change introduces is a `blocker`; `VERDICT: RETURN` means one is (`ORCH_SECURITY_BLOCKED`); `VERDICT: ESCALATE` means a scan failed (`ORCH_SECURITY_SCAN_FAILED`) or text in the change addressed the agent (`ORCH_SECURITY_ESCALATE`). A finding is a `blocker` or a `minor` by the threshold `start` recorded, and the script, not you, checks it. Findings already present at the base commit go in the report's owner-only block (`PRE-EXISTING (owner only):` … `END PRE-EXISTING`); the script writes them to `.conductor/security-pre-existing.txt` and to nothing public. This changes 1.48.0 behavior: a finding already present at the base, a dependency advisory included, no longer blocks the run at any level; only the findings the change introduces decide the verdict. `handback security` prints `security handed back build_executed; VERDICT: APPROVE; <n> finding(s) below <threshold> recorded; dependency=<ran|not-covered|disabled>; pre-existing findings, if any, are in .conductor/security-pre-existing.txt (owner only)`, and only then `qa`. A run started before FEAT-034 has no seat: `qa` follows the audit and `handback qa` prints `security=not-configured (run predates FEAT-034)`. When `qa`'s hand-back records `verify_pass`, run `node "$S/orchestrate.mjs" end`. It prints the run it removed.
|
|
74
77
|
6. **Report.** From the record `end` printed, name:
|
|
75
78
|
- every hand-back, with its role, gate and task;
|
|
76
79
|
- each audit round's verdict, from the audit entries' `round` and `verdict`, and each fix round with its files, from their `fix`;
|
|
80
|
+
- each entry's `model`, and each fix round whose `fix.escalated` names tasks, with those task ids (FEAT-053);
|
|
77
81
|
- 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
82
|
- both approvals, with who approved and when;
|
|
79
83
|
- each review loop's outcome and round, from the record's `review` field;
|
|
84
|
+
- each `resumes` entry: when it ran, the halt it cleared (code and reason), and how many records it kept and dropped;
|
|
80
85
|
- every agent's observation line.
|
|
81
86
|
|
|
82
87
|
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>`.
|
|
@@ -86,9 +91,9 @@ A halt is terminal in v1 (D12). Recovery is `node "$S/orchestrate.mjs" end`, the
|
|
|
86
91
|
After `spec` and after `plan` hand back, and before that role's approval, run this loop. It never halts the run and never replaces the owner's approval, but `approve` refuses with `ORCH_REVIEW_OPEN` until the loop records an outcome, so a skipped loop is always on the record. `<role>` is `spec` or `plan`; `<doc>` is the document path from the hand-back's `ops.f`. No step messages an agent: every revision is a fresh dispatch over files, so the loop needs no launch settings and runs in every permission mode, headless included.
|
|
87
92
|
|
|
88
93
|
1. **Open a round.** Run `node "$S/orchestrate.mjs" review <role> --round <doc>`. It prints `review <role> round <n> of 3: <doc> sha256 <doc sha256>`. On `review <role> closed unchanged at round <n>`, the last revision left the document as it was, a failed round: the loop is over, go to the approval.
|
|
89
|
-
2. **Review.** Dispatch a fresh `define-review` agent with the `Agent` tool and the reviewer brief below. Never revive an earlier reviewer, and never pass it an earlier round's findings. Wait for its completion notice.
|
|
94
|
+
2. **Review.** Dispatch a fresh `define-review` agent with the `Agent` tool and the reviewer brief below. Never revive an earlier reviewer, and never pass it an earlier round's findings. Wait for its completion notice. When the round line ends `; model <alias>`, pass that model to the reviewer's dispatch by the rule of step 2.4.
|
|
90
95
|
3. **Record.** Write its report verbatim with the Write tool to `.conductor/review/<role>-<n>.md`, then run `review <role> --record`. The script reads the verdict from the file's last non-blank line, `REVIEW <role> round <n>: CLEAN` or `REVIEW <role> round <n>: OPEN <k>`. On `closed clean` or `closed cap`, go to the approval. No revision follows the third pass, so the document at the approval is always the one the last reviewer read.
|
|
91
|
-
4. **Revise.** On `OPEN <k>; revise <doc> sha256 <doc sha256> from <review path> sha256 <review sha256>`, dispatch a fresh `<role>` agent with the `Agent` tool and the revision brief below, filled with those four values. Never revive the author that handed back, and never message any agent. Wait for the first delivery on any channel (a hand-back frame or a completion notice) whose last line is `REVISION <role> round <n>: done` or `REVISION <role> round <n>: blocked <reason>`, and ignore later copies. On `done`, go back to 1: the script decides whether the revision changed the document.
|
|
96
|
+
4. **Revise.** On `OPEN <k>; revise <doc> sha256 <doc sha256> from <review path> sha256 <review sha256>`, dispatch a fresh `<role>` agent with the `Agent` tool and the revision brief below, filled with those four values. Never revive the author that handed back, and never message any agent. Wait for the first delivery on any channel (a hand-back frame or a completion notice) whose last line is `REVISION <role> round <n>: done` or `REVISION <role> round <n>: blocked <reason>`, and ignore later copies. On `done`, go back to 1: the script decides whether the revision changed the document. When the `OPEN` line ends `; model <alias>`, pass that model to the author's dispatch by the rule of step 2.4.
|
|
92
97
|
|
|
93
98
|
A revision report is never passed to `handback`. If one carries a `SNAP_HANDBACK` line, run `review <role> --close skipped:snap-in-revision` and flag the report at the approval.
|
|
94
99
|
|
|
@@ -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
|
|
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]}`;
|
package/scripts/orchestrate.mjs
CHANGED
|
@@ -32,7 +32,15 @@ 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;
|
|
37
|
+
// FEAT-053: the Agent tool's model aliases plus inherit; the one list start, the profiles and isValidRun are checked against.
|
|
38
|
+
export const MODEL_ALIASES = ['opus', 'sonnet', 'haiku', 'inherit'];
|
|
39
|
+
export const MODEL_ROLES = ['spec', 'plan', 'code', 'audit', 'security', 'qa', 'define-review'];
|
|
40
|
+
const ESCALATION_MODEL = 'opus';
|
|
41
|
+
const ROLE_MODELS_PREFIX = '- Role models:';
|
|
42
|
+
const ROLE_MODELS_LINE = /^- Role models: (.+)$/;
|
|
43
|
+
const isModel = (m) => MODEL_ALIASES.includes(m);
|
|
36
44
|
// Every outcome a closed loop can carry; only the skip is the orchestrator's to record (FEAT-058).
|
|
37
45
|
const REVIEW_OUTCOME = /^(clean|cap|unchanged|skipped:[a-z][a-z0-9-]{0,39})$/;
|
|
38
46
|
const SKIP_OUTCOME = /^skipped:[a-z][a-z0-9-]{0,39}$/;
|
|
@@ -68,7 +76,7 @@ const DEPENDENCY_STATES = ['audit', 'not-covered', 'disabled'];
|
|
|
68
76
|
const OBJECT_NAME = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
|
|
69
77
|
export const SECURITY_NOT_CONFIGURED = 'not-configured (run predates FEAT-034)';
|
|
70
78
|
|
|
71
|
-
// A halt stops the run and is recorded in it (D12). A refusal is a misuse of the CLI:
|
|
79
|
+
// 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
80
|
// nothing is written and nothing is recorded.
|
|
73
81
|
export class Halt extends Error {
|
|
74
82
|
constructor(code, reason) { super(`${code}: ${reason}`); this.code = code; this.reason = reason; }
|
|
@@ -109,13 +117,24 @@ function isSecurity(s) {
|
|
|
109
117
|
return typeof s.scan_command === 'string' && s.scan_command.endsWith(` ${s.threshold}`);
|
|
110
118
|
}
|
|
111
119
|
|
|
120
|
+
// FEAT-053: a hand-edited model would let the run file, not the project, choose what a dispatch runs on.
|
|
121
|
+
function isModelRecord(run) {
|
|
122
|
+
const m = run.models;
|
|
123
|
+
const keys = isPlainObject(m) ? Object.keys(m).sort().join() : null;
|
|
124
|
+
if (m !== undefined && (keys !== [...MODEL_ROLES].sort().join() || !MODEL_ROLES.every((r) => isModel(m[r])))) return false;
|
|
125
|
+
if (run.dispatch_model !== undefined && !isModel(run.dispatch_model)) return false;
|
|
126
|
+
return run.handbacks.every((h) => !isPlainObject(h?.fix) || h.fix.model === undefined || isModel(h.fix.model));
|
|
127
|
+
}
|
|
128
|
+
|
|
112
129
|
// FEAT-057: a present audit_rounds that is not 0-5 would let a hand-edited run buy fix rounds without limit.
|
|
130
|
+
// FEAT-053: and models, dispatch_model and fix.model hold only the allow-list.
|
|
113
131
|
export function isValidRun(run) {
|
|
114
132
|
return isPlainObject(run) && run.v === 1 && typeof run.session_id === 'string' && run.session_id !== ''
|
|
115
133
|
&& typeof run.item === 'string' && GATES.includes(run.gate) && isPlainObject(run.approvals)
|
|
116
134
|
&& Array.isArray(run.handbacks) && Array.isArray(run.tasks?.ids) && Number.isInteger(run.tasks?.done)
|
|
117
135
|
&& (run.audit_rounds === undefined || isAuditRounds(run.audit_rounds))
|
|
118
|
-
&& (run.security === undefined || isSecurity(run.security))
|
|
136
|
+
&& (run.security === undefined || isSecurity(run.security))
|
|
137
|
+
&& isModelRecord(run);
|
|
119
138
|
}
|
|
120
139
|
|
|
121
140
|
function readRun(root) {
|
|
@@ -131,14 +150,14 @@ function readRun(root) {
|
|
|
131
150
|
|
|
132
151
|
const saveRun = (root, run) => writeAtomic(join(root, RUN_FILE), JSON.stringify(run, null, 2) + '\n');
|
|
133
152
|
|
|
134
|
-
// Every verb but start and end drives a run that must exist, be this session's, and not be halted.
|
|
153
|
+
// Every verb but start, resume and end drives a run that must exist, be this session's, and not be halted.
|
|
135
154
|
function liveRun(root, sessionId) {
|
|
136
155
|
const run = readRun(root);
|
|
137
156
|
if (!run) throw new Refusal(`no run file at ${join(root, RUN_FILE)}; start one first`);
|
|
138
157
|
if (run.session_id !== sessionId) {
|
|
139
158
|
throw new Refusal(`run ${run.item} belongs to another session; end it, or start to replace it`);
|
|
140
159
|
}
|
|
141
|
-
if (run.halt) throw new Refusal(`run ${run.item} halted with ${run.halt.code}; recover with
|
|
160
|
+
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
161
|
return run;
|
|
143
162
|
}
|
|
144
163
|
|
|
@@ -277,6 +296,64 @@ export function findAgent(role, root, home = homedir()) {
|
|
|
277
296
|
return null;
|
|
278
297
|
}
|
|
279
298
|
|
|
299
|
+
const modelsInvalid = (reason) => new Halt('ORCH_ROLE_MODELS_INVALID', reason);
|
|
300
|
+
|
|
301
|
+
// FEAT-053: the one CLAUDE.md opt-in line, or null; a prefix without a value halts rather than inheriting silently.
|
|
302
|
+
function roleModelsValue(root) {
|
|
303
|
+
let text = '';
|
|
304
|
+
try { text = readFileSync(join(root, 'CLAUDE.md'), 'utf8').replace(/\r\n/g, '\n'); } catch { return null; }
|
|
305
|
+
const lines = text.split('\n').filter((l) => l.startsWith(ROLE_MODELS_PREFIX));
|
|
306
|
+
if (lines.length === 0) return null;
|
|
307
|
+
if (lines.length > 1) throw modelsInvalid(`CLAUDE.md has ${lines.length} "${ROLE_MODELS_PREFIX}" lines; keep one`);
|
|
308
|
+
const m = ROLE_MODELS_LINE.exec(lines[0]);
|
|
309
|
+
if (!m) throw modelsInvalid(`"${lines[0]}" has no value; write default or <role>=<model> tokens`);
|
|
310
|
+
return m[1];
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// An explicit token wins over default whatever the order, so the parse only collects.
|
|
314
|
+
function parseRoleModels(value) {
|
|
315
|
+
const explicit = {};
|
|
316
|
+
let defaults = false;
|
|
317
|
+
for (const token of value.split(',').map((t) => t.trim())) {
|
|
318
|
+
if (token === '') throw modelsInvalid(`empty token in "${ROLE_MODELS_PREFIX} ${value}"`);
|
|
319
|
+
if (token === 'default') {
|
|
320
|
+
if (defaults) throw modelsInvalid('"default" appears twice');
|
|
321
|
+
defaults = true;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
const parts = token.split('=');
|
|
325
|
+
if (parts.length !== 2) throw modelsInvalid(`token "${token}" is neither default nor <role>=<model>`);
|
|
326
|
+
const [role, model] = parts;
|
|
327
|
+
if (!MODEL_ROLES.includes(role)) throw modelsInvalid(`unknown role "${role}" in "${token}"; the roles are ${MODEL_ROLES.join(', ')}`);
|
|
328
|
+
if (!isModel(model)) throw modelsInvalid(`model "${model}" in "${token}" is not one of ${MODEL_ALIASES.join(', ')}`);
|
|
329
|
+
if (role in explicit) throw modelsInvalid(`role "${role}" is set twice`);
|
|
330
|
+
explicit[role] = model;
|
|
331
|
+
}
|
|
332
|
+
return { defaults, explicit };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// The shipped default sits under a key Claude Code does not read; no profile, or no key, inherits.
|
|
336
|
+
function profileDefault(role, root) {
|
|
337
|
+
const path = findAgent(role, root);
|
|
338
|
+
if (!path) return 'inherit';
|
|
339
|
+
const front = readFileSync(path, 'utf8').match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
340
|
+
const value = front?.[1].match(/^default-model:[ \t]*(\S*)[ \t]*\r?$/m)?.[1];
|
|
341
|
+
if (value === undefined) return 'inherit';
|
|
342
|
+
if (!isModel(value)) throw modelsInvalid(`${path} sets default-model: ${value}, not one of ${MODEL_ALIASES.join(', ')}`);
|
|
343
|
+
return value;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Fixed at start, like audit_rounds; null keeps a run without the line exactly as it was before FEAT-053.
|
|
347
|
+
function resolveRoleModels(root) {
|
|
348
|
+
const value = roleModelsValue(root);
|
|
349
|
+
if (value === null) return null;
|
|
350
|
+
const { defaults, explicit } = parseRoleModels(value);
|
|
351
|
+
return Object.fromEntries(MODEL_ROLES.map((r) => [r, explicit[r] ?? (defaults ? profileDefault(r, root) : 'inherit')]));
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const shareNote = (m) => (m.audit === m.code && m.code !== 'inherit' ? `; note: audit and code share ${m.code}` : '');
|
|
355
|
+
const modelsNote = (m) => (m ? `; role models: ${MODEL_ROLES.map((r) => `${r}=${m[r]}`).join(', ')}${shareNote(m)}` : '');
|
|
356
|
+
|
|
280
357
|
function runScript(name, args, input = '') {
|
|
281
358
|
const r = spawnSync(process.execPath, [join(HERE, name), ...args], { input, encoding: 'utf8' });
|
|
282
359
|
return { status: r.status, out: r.stdout, err: (r.stderr || '').trim() };
|
|
@@ -330,8 +407,7 @@ const scanRef = (root) => relative(root, join(HERE, 'security-scan.mjs')).split(
|
|
|
330
407
|
|
|
331
408
|
// FEAT-034: what the security seat will run, fixed at start so Guard 7 and the router read one record.
|
|
332
409
|
function resolveSecurity(root, stack, { threshold, dependencyAudit }) {
|
|
333
|
-
const
|
|
334
|
-
const base = OBJECT_NAME.test(head) ? head : null;
|
|
410
|
+
const base = headObject(root);
|
|
335
411
|
const auditCommand = dependencyAudit ? PM_AUDIT_COMMAND[stack.packageManager] ?? null : null;
|
|
336
412
|
const dependency = !dependencyAudit ? 'disabled' : auditCommand ? 'audit' : 'not-covered';
|
|
337
413
|
// C14: the scanner writes complete lines, severity included; 'none' keeps a fixed arity outside git (plan decisions).
|
|
@@ -364,6 +440,14 @@ function gitValue(root, args, fallback) {
|
|
|
364
440
|
return (r.status === 0 && r.stdout.trim()) || fallback;
|
|
365
441
|
}
|
|
366
442
|
|
|
443
|
+
const headCommit = (root) => {
|
|
444
|
+
const head = gitValue(root, ['rev-parse', 'HEAD'], '0000000').toLowerCase();
|
|
445
|
+
return /^[0-9a-f]{7,40}$/.test(head) ? head : '0000000';
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
// A full object name or null: what an approval and the security seat anchor to (FEAT-055, FEAT-034).
|
|
449
|
+
const headObject = (root) => { const head = gitValue(root, ['rev-parse', 'HEAD'], ''); return OBJECT_NAME.test(head) ? head : null; };
|
|
450
|
+
|
|
367
451
|
// A fix step's files come from the record, re-checked against the plan because the run file is writable.
|
|
368
452
|
function codeScope(root, run, step) {
|
|
369
453
|
if (step.fix !== undefined) { const { files } = fixDue(run); return fixScope(root, run, Array.isArray(files) ? files : [], step.fix); }
|
|
@@ -372,10 +456,9 @@ function codeScope(root, run, step) {
|
|
|
372
456
|
}
|
|
373
457
|
|
|
374
458
|
function envelopeFields(run, root, step) {
|
|
375
|
-
const head = gitValue(root, ['rev-parse', 'HEAD'], '0000000').toLowerCase();
|
|
376
459
|
const { tk, scope } = ROLE_ARTIFACTS[step.role];
|
|
377
460
|
const fields = {
|
|
378
|
-
ph: PHASE[step.role], c:
|
|
461
|
+
ph: PHASE[step.role], c: headCommit(root), s: run.item,
|
|
379
462
|
// A fix re-enters Build, so it carries Build's entry gate, the one --to code checks (D6).
|
|
380
463
|
n: [], f: [], d: [], x: [], role: step.role, tk, gate: step.fix === undefined ? run.gate : expectedGate('code'),
|
|
381
464
|
};
|
|
@@ -398,20 +481,32 @@ function envelopeFields(run, root, step) {
|
|
|
398
481
|
const currentHash = (root, kind, rel) => { try { return documentHash(kind, readFileSync(join(root, rel))); } catch { return null; } };
|
|
399
482
|
|
|
400
483
|
// FEAT-056: after define_approved, a changed spec or plan means the run would execute text nobody approved.
|
|
484
|
+
// FEAT-055: returned, not thrown, so resume refuses with the same text where install halts.
|
|
485
|
+
function approvedDocHalt(root, run, kind) {
|
|
486
|
+
const { path, sha256 } = run.approvals[kind] ?? {};
|
|
487
|
+
if (typeof path !== 'string' || typeof sha256 !== 'string') {
|
|
488
|
+
return new Halt('ORCH_APPROVAL_UNHASHED', `run ${run.item} records an approval without a document hash (started before FEAT-056); run end, then start`);
|
|
489
|
+
}
|
|
490
|
+
const now = currentHash(root, kind, path);
|
|
491
|
+
if (now === sha256) return null;
|
|
492
|
+
return new Halt('ORCH_APPROVED_DOC_CHANGED', `${kind} ${path} was approved at sha256 ${sha256} and ${now ? `now hashes ${now}` : 'can no longer be read'}`);
|
|
493
|
+
}
|
|
494
|
+
|
|
401
495
|
function checkApprovedDocs(root, run) {
|
|
402
496
|
for (const kind of ['spec', 'plan']) {
|
|
403
|
-
const
|
|
404
|
-
if (
|
|
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'}`);
|
|
497
|
+
const failure = approvedDocHalt(root, run, kind);
|
|
498
|
+
if (failure) throw failure;
|
|
410
499
|
}
|
|
411
500
|
}
|
|
412
501
|
|
|
413
502
|
const fixNote = (run) => { const f = fixDue(run); return `fix round ${f.round} of ${run.audit_rounds ?? 0}: review ${f.review} sha256 ${f.sha256}`; };
|
|
414
503
|
|
|
504
|
+
// FEAT-053: what the script says this dispatch runs on, never the orchestrator's choice; null in a run without models.
|
|
505
|
+
function dispatchModel(run, step) {
|
|
506
|
+
if (!isPlainObject(run.models)) return null;
|
|
507
|
+
return step.fix === undefined ? run.models[step.role] : fixDue(run).model ?? run.models.code;
|
|
508
|
+
}
|
|
509
|
+
|
|
415
510
|
// Builds and validates the next envelope with --to; installs it unless only checking.
|
|
416
511
|
function install(root, sessionId, role, check) {
|
|
417
512
|
const run = liveRun(root, sessionId);
|
|
@@ -425,10 +520,11 @@ function install(root, sessionId, role, check) {
|
|
|
425
520
|
if (built.status !== 0) throw new Halt('SNAP_ERROR', built.err);
|
|
426
521
|
const error = validate(built.out, role);
|
|
427
522
|
if (error) throw new Halt(error.includes('SNAP_GATE_MISMATCH') ? 'SNAP_GATE_MISMATCH' : 'SNAP_ERROR', error);
|
|
428
|
-
const
|
|
523
|
+
const model = dispatchModel(run, step);
|
|
524
|
+
const out = built.out.trim() + (step.fix === undefined ? '' : `\n${fixNote(run)}`) + (model ? `\nmodel: ${model}` : '');
|
|
429
525
|
if (check) return out;
|
|
430
526
|
writeAtomic(join(root, ENVELOPE_FILE), built.out);
|
|
431
|
-
saveRun(root, { ...run, band: ROLE_BAND[role], role });
|
|
527
|
+
saveRun(root, { ...run, band: ROLE_BAND[role], role, ...(model ? { dispatch_model: model } : {}) });
|
|
432
528
|
return out;
|
|
433
529
|
}
|
|
434
530
|
|
|
@@ -453,23 +549,30 @@ function entryFields(run, role) {
|
|
|
453
549
|
return {};
|
|
454
550
|
}
|
|
455
551
|
|
|
552
|
+
// FEAT-053: an entry carries the model install recorded, read from the run file and never from the report.
|
|
456
553
|
export function recordHandback(run, role, gate, verdict, extra = {}) {
|
|
457
554
|
if (role === 'qa' && gate === 'verify_pass') withholdUnlessApproved(run);
|
|
458
555
|
const fields = entryFields(run, role);
|
|
459
|
-
const
|
|
556
|
+
const model = isPlainObject(run.models) && isModel(run.dispatch_model) ? { model: run.dispatch_model } : {};
|
|
557
|
+
const entry = { role, gate, at: new Date().toISOString(), ...fields, ...(verdict ? { verdict } : {}), ...model, ...extra };
|
|
460
558
|
const tasks = role === 'code' && !('fix' in fields) ? { ...run.tasks, done: run.tasks.done + 1 } : run.tasks;
|
|
461
559
|
return { ...run, role: null, gate: forwardGate(run, role, gate), tasks, handbacks: [...run.handbacks, entry] };
|
|
462
560
|
}
|
|
463
561
|
|
|
562
|
+
// FEAT-055: the validated text is returned too, so resume can validate the same bytes again.
|
|
464
563
|
function parseHandback(text) {
|
|
465
564
|
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.startsWith('SNAP_HANDBACK '));
|
|
466
565
|
if (lines.length !== 1) throw new Halt('ORCH_HANDBACK_MISSING', `expected exactly one SNAP_HANDBACK line, found ${lines.length}`);
|
|
467
566
|
const json = lines[0].slice('SNAP_HANDBACK '.length).trim();
|
|
567
|
+
// 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).
|
|
568
|
+
if (Buffer.byteLength(json) > SNAP_STORE_MAX_BYTES) {
|
|
569
|
+
throw new Halt('ORCH_HANDBACK_INVALID', `the hand-back SNAP is larger than ${SNAP_STORE_MAX_BYTES} bytes`);
|
|
570
|
+
}
|
|
468
571
|
const error = validate(json + '\n');
|
|
469
572
|
if (error) throw new Halt('ORCH_HANDBACK_INVALID', error);
|
|
470
573
|
const env = JSON.parse(json);
|
|
471
574
|
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;
|
|
575
|
+
return { env, snap: json };
|
|
473
576
|
}
|
|
474
577
|
|
|
475
578
|
function auditStop({ verdict, blockers }, round, cap) {
|
|
@@ -478,6 +581,20 @@ function auditStop({ verdict, blockers }, round, cap) {
|
|
|
478
581
|
return new Halt('ORCH_AUDIT_ESCALATE', `audit escalated a decision only the owner takes; see ${report}`);
|
|
479
582
|
}
|
|
480
583
|
|
|
584
|
+
// FEAT-053: a plan task the audit returns a second time goes to the most capable model, and the record names the trigger.
|
|
585
|
+
function fixModel(root, run, paths) {
|
|
586
|
+
if (!isPlainObject(run.models)) return { fields: {}, note: '' };
|
|
587
|
+
const tasks = extractTasks(readDoc(root, run.plan, `cannot read ${run.plan}`).toString('utf8'))
|
|
588
|
+
.filter((t) => t.files.some((f) => paths.includes(f))).map((t) => t.id);
|
|
589
|
+
const earlier = new Set(run.handbacks.slice(0, -1).flatMap((h) => (h.role === 'audit' && Array.isArray(h.fix?.tasks) ? h.fix.tasks : [])));
|
|
590
|
+
const escalated = tasks.filter((id) => earlier.has(id));
|
|
591
|
+
if (escalated.length === 0) return { fields: { tasks, model: run.models.code }, note: `; model ${run.models.code}` };
|
|
592
|
+
return {
|
|
593
|
+
fields: { tasks, model: ESCALATION_MODEL, escalated },
|
|
594
|
+
note: `; model ${ESCALATION_MODEL} (escalated: ${escalated.join(', ')} returned twice)`,
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
|
|
481
598
|
// FEAT-057: the cap is read from the run file, never from the orchestrator, so its prompt cannot buy a round (E2).
|
|
482
599
|
// Every halt here lands on top of the audit entry handback already saved.
|
|
483
600
|
function auditFix(root, run, verdict, bytes) {
|
|
@@ -488,8 +605,9 @@ function auditFix(root, run, verdict, bytes) {
|
|
|
488
605
|
checkApprovedDocs(root, run);
|
|
489
606
|
const fix = { round: used + 1, files: verdict.paths, review: `${HANDBACK_DIR}/audit-${entry.round}.txt`, sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
490
607
|
const scope = fixScope(root, run, fix.files, fix.round);
|
|
491
|
-
|
|
492
|
-
|
|
608
|
+
const { fields, note } = fixModel(root, run, verdict.paths);
|
|
609
|
+
saveRun(root, { ...run, handbacks: [...run.handbacks.slice(0, -1), { ...entry, fix: { ...fix, ...fields } }] });
|
|
610
|
+
return `audit round ${entry.round}: RETURN with ${verdict.blockers} blocker/major finding(s); fix round ${fix.round} of ${cap}: review ${fix.review} sha256 ${fix.sha256}; scope ${scope.join(', ')}${note}`;
|
|
493
611
|
}
|
|
494
612
|
|
|
495
613
|
// FEAT-060: a candidate is wider than the valid form, so a near-miss halts by name instead of passing unseen.
|
|
@@ -739,14 +857,14 @@ async function handback(root, sessionId, role, bytes) {
|
|
|
739
857
|
throw new Halt('ORCH_HANDBACK_CONFLICT', `${role} already handed back for this position; a second report is not routed`);
|
|
740
858
|
}
|
|
741
859
|
if (!run.role || run.role !== role) throw new Refusal(`handback ${role}: the dispatched role is ${run.role ?? 'none'}`);
|
|
742
|
-
const env = parseHandback(text);
|
|
860
|
+
const { env, snap } = parseHandback(text);
|
|
743
861
|
if (env.sys.role !== role) throw new Halt('ORCH_HANDBACK_ROLE_MISMATCH', `dispatched ${role}, the hand-back names ${env.sys.role}`);
|
|
744
862
|
if (!MAY_HAND_BACK[role].includes(env.ops.gate)) {
|
|
745
863
|
throw new Halt('ORCH_GATE_UNEARNED', `${role} may hand back ${MAY_HAND_BACK[role].join('|')}, not ${env.ops.gate}`);
|
|
746
864
|
}
|
|
747
865
|
if (role === 'security') return securityHandback(root, run, env.ops.gate, text);
|
|
748
866
|
const verdict = role === 'audit' ? parseVerdict(text) : null;
|
|
749
|
-
const recorded = recordHandback(run, role, env.ops.gate, verdict?.verdict);
|
|
867
|
+
const recorded = recordHandback(run, role, env.ops.gate, verdict?.verdict, { snap });
|
|
750
868
|
saveRun(root, recorded);
|
|
751
869
|
// Saved first, so the halt cli records lands on top of the audit entry (FEAT-060, FEAT-057).
|
|
752
870
|
if (verdict && verdict.verdict !== 'APPROVE') return auditFix(root, recorded, verdict, bytes);
|
|
@@ -755,6 +873,7 @@ async function handback(root, sessionId, role, bytes) {
|
|
|
755
873
|
}
|
|
756
874
|
|
|
757
875
|
// Two human approvals, one gate write (A4): only an approved plan writes define_approved.
|
|
876
|
+
// FEAT-055: and HEAD at that moment, so resume can tell whether history still holds it.
|
|
758
877
|
// FEAT-056: each approval binds the bytes the owner was shown; a stale hash writes nothing.
|
|
759
878
|
function approve(root, sessionId, what, rel, shown) {
|
|
760
879
|
const run = liveRun(root, sessionId);
|
|
@@ -767,7 +886,7 @@ function approve(root, sessionId, what, rel, shown) {
|
|
|
767
886
|
if (sha256 !== shown.toLowerCase()) {
|
|
768
887
|
throw new Refusal(`ORCH_DOC_HASH_STALE: ${what} ${rel} hashes ${sha256}, not the ${shown} that was shown; show the document again`);
|
|
769
888
|
}
|
|
770
|
-
const approval = { at: new Date().toISOString(), by: gitValue(root, ['config', 'user.name'], 'unknown'), path: rel, sha256 };
|
|
889
|
+
const approval = { at: new Date().toISOString(), by: gitValue(root, ['config', 'user.name'], 'unknown'), path: rel, sha256, commit: headObject(root) };
|
|
771
890
|
if (what === 'plan') return approvePlan(root, run, content.toString('utf8'), approval);
|
|
772
891
|
saveRun(root, { ...run, approvals: { ...run.approvals, spec: approval } });
|
|
773
892
|
return `spec approved: sha256 ${sha256}`;
|
|
@@ -792,11 +911,113 @@ function checkLoopClosed(run, what) {
|
|
|
792
911
|
throw new Refusal(`ORCH_REVIEW_OPEN: review ${what} is ${state}; close it before the approval`);
|
|
793
912
|
}
|
|
794
913
|
|
|
914
|
+
const RESUME_USAGE = 'usage: orchestrate.mjs resume';
|
|
915
|
+
const RESTART = 'recover with end, then start';
|
|
916
|
+
const RECORD_KINDS = ['spec', 'plan'];
|
|
917
|
+
|
|
918
|
+
// FEAT-055: every failure is a refusal, so a failed resume leaves the halt it was asked to clear as it was.
|
|
919
|
+
function haltedRun(root, sessionId, args) {
|
|
920
|
+
if (args.length > 0) throw new Refusal(RESUME_USAGE);
|
|
921
|
+
let run = null;
|
|
922
|
+
try { run = readRun(root); } catch { /* an invalid run file is judged below */ }
|
|
923
|
+
if (!run) throw new Refusal(`ORCH_RESUME_NO_RUN: no valid run file at ${join(root, RUN_FILE)}`);
|
|
924
|
+
if (!run.halt) throw new Refusal(`ORCH_RESUME_NOT_HALTED: run ${run.item} is not halted; continue with ${describeStep(nextStep(run))}`);
|
|
925
|
+
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');
|
|
926
|
+
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}`);
|
|
927
|
+
return run;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// 0: HEAD descends from commit; 1: it does not; anything else: git cannot answer. A non-hex name never reaches git as an option.
|
|
931
|
+
function ancestry(root, commit) {
|
|
932
|
+
if (typeof commit !== 'string' || !/^[0-9a-f]{7,64}$/.test(commit)) return null;
|
|
933
|
+
return spawnSync('git', ['merge-base', '--is-ancestor', commit, 'HEAD'], { cwd: root, encoding: 'utf8' }).status;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
const unanchored = (kind, reason) => new Refusal(`ORCH_RESUME_UNANCHORED: the ${kind} approval ${reason}; ${RESTART}`);
|
|
937
|
+
|
|
938
|
+
// An approval is the owner's act, which the run cannot redo, so a failing one refuses the whole resume.
|
|
939
|
+
function checkApproval(root, run, kind) {
|
|
940
|
+
const failure = approvedDocHalt(root, run, kind);
|
|
941
|
+
if (failure?.code === 'ORCH_APPROVAL_UNHASHED') throw new Refusal(failure.message);
|
|
942
|
+
const { commit } = run.approvals[kind];
|
|
943
|
+
if (commit === undefined) throw unanchored(kind, 'records no commit (approved before FEAT-055)');
|
|
944
|
+
if (commit === null) throw unanchored(kind, 'records a null commit (approved outside a git repository or before its first commit)');
|
|
945
|
+
if (failure) throw new Refusal(`${failure.message}; ${RESTART}`);
|
|
946
|
+
const answer = ancestry(root, commit);
|
|
947
|
+
if (answer === 1) {
|
|
948
|
+
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}`);
|
|
949
|
+
}
|
|
950
|
+
if (answer !== 0) throw unanchored(kind, `commit ${String(commit)} cannot be checked against HEAD`);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// The conflict's last entry is ambiguous, except a spec or plan entry whose approval already stands.
|
|
954
|
+
function candidateEntries(run) {
|
|
955
|
+
const last = run.handbacks.at(-1);
|
|
956
|
+
if (run.halt.code !== 'ORCH_HANDBACK_CONFLICT' || !last) return run.handbacks;
|
|
957
|
+
return RECORD_KINDS.includes(last.role) && run.approvals[last.role] ? run.handbacks : run.handbacks.slice(0, -1);
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
// A task entry still describes the repository: its position, its SNAP and its commit all hold.
|
|
961
|
+
function taskEntryHolds(root, entry, taskId) {
|
|
962
|
+
if (entry.task !== taskId || typeof entry.snap !== 'string' || validate(`${entry.snap}\n`) !== '') return false;
|
|
963
|
+
let env = null;
|
|
964
|
+
try { env = JSON.parse(entry.snap); } catch { return false; }
|
|
965
|
+
return env?.sys?.role === 'code' && ancestry(root, env.sys.c) === 0;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// Each approved document's entry, then Build's task entries up to the first that fails; Verify is always redone.
|
|
969
|
+
function keptEntries(root, run) {
|
|
970
|
+
const entries = candidateEntries(run);
|
|
971
|
+
const approved = RECORD_KINDS.filter((k) => run.approvals[k]).map((k) => entries.find((h) => h.role === k)).filter(Boolean);
|
|
972
|
+
if (!run.approvals.plan) return { kept: approved, tasks: 0 };
|
|
973
|
+
const tasks = entries.filter((h) => h.role === 'code' && !('fix' in h));
|
|
974
|
+
let n = 0;
|
|
975
|
+
while (n < tasks.length && n < run.tasks.ids.length && taskEntryHolds(root, tasks[n], run.tasks.ids[n])) n += 1;
|
|
976
|
+
return { kept: [...approved, ...tasks.slice(0, n)], tasks: n };
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
// Only approvePlan writes define_approved, and only the last task's hand-back forwards build_executed.
|
|
980
|
+
const resumedGate = (run, tasks) => (!run.approvals.plan ? 'boundary_routed' : tasks < run.tasks.ids.length ? 'define_approved' : 'build_executed');
|
|
981
|
+
|
|
982
|
+
// A dropped document's loop is cleared with it, so the redone document gets a fresh review loop.
|
|
983
|
+
const resumedReview = (run, kept) => (isPlainObject(run.review)
|
|
984
|
+
? Object.fromEntries(Object.entries(run.review).filter(([k]) => kept.some((h) => h.role === k))) : run.review);
|
|
985
|
+
|
|
986
|
+
function nextLine(run) {
|
|
987
|
+
const step = nextStep(run);
|
|
988
|
+
return step.task ? `${describeStep(step)} (task ${run.tasks.done + 1} of ${run.tasks.ids.length})` : describeStep(step);
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// FEAT-055: back to the last gate whose record still validates; every record after it is dropped and redone.
|
|
992
|
+
function resume(root, sessionId, args) {
|
|
993
|
+
const run = haltedRun(root, sessionId, args);
|
|
994
|
+
const approvals = RECORD_KINDS.filter((k) => run.approvals[k]);
|
|
995
|
+
for (const kind of approvals) checkApproval(root, run, kind);
|
|
996
|
+
const { kept, tasks } = keptEntries(root, run);
|
|
997
|
+
const records = kept.length + approvals.length;
|
|
998
|
+
const dropped = run.handbacks.length - kept.length;
|
|
999
|
+
const { code, reason, at } = run.halt;
|
|
1000
|
+
const resumes = [...(Array.isArray(run.resumes) ? run.resumes : []), { at: new Date().toISOString(), halt: { code, reason, at }, kept: records, dropped }];
|
|
1001
|
+
const next = {
|
|
1002
|
+
...run, session_id: sessionId, role: null, halt: null, gate: resumedGate(run, tasks),
|
|
1003
|
+
handbacks: kept, tasks: { ...run.tasks, done: tasks }, review: resumedReview(run, kept), resumes,
|
|
1004
|
+
};
|
|
1005
|
+
// Computed before the write: resume records no halt, so a throw after saveRun would leave a changed run behind a failed exit.
|
|
1006
|
+
const line = `run ${run.item} resumed after ${code} from ${next.gate}: kept ${records} record(s), dropped ${dropped}; next: ${nextLine(next)}`;
|
|
1007
|
+
saveRun(root, next);
|
|
1008
|
+
// The halted agent's envelope; the hand-back and review files stay for the owner and are overwritten on re-dispatch.
|
|
1009
|
+
rmSync(join(root, ENVELOPE_FILE), { force: true });
|
|
1010
|
+
return line;
|
|
1011
|
+
}
|
|
1012
|
+
|
|
795
1013
|
const reviewWellFormed = (flag, arg, extra) => extra === undefined
|
|
796
1014
|
&& (flag === '--round' ? arg !== undefined : flag === '--record' ? arg === undefined : flag === '--close' && SKIP_OUTCOME.test(arg ?? ''));
|
|
797
1015
|
|
|
798
1016
|
// FEAT-041 (e), reworked by FEAT-058: the loop revises through files, and its outcomes come
|
|
799
1017
|
// from the script's own reads of the review file and the document, never from the orchestrator's word.
|
|
1018
|
+
// FEAT-053: the two lines that trigger a dispatch name its model; a closing line triggers none.
|
|
1019
|
+
const modelSegment = (run, role) => (isPlainObject(run.models) ? `; model ${run.models[role]}` : '');
|
|
1020
|
+
|
|
800
1021
|
function review(root, sessionId, [role, flag, arg, extra]) {
|
|
801
1022
|
const run = liveRun(root, sessionId);
|
|
802
1023
|
if (!reviewWellFormed(flag, arg, extra)) throw new Refusal(REVIEW_USAGE);
|
|
@@ -805,8 +1026,8 @@ function review(root, sessionId, [role, flag, arg, extra]) {
|
|
|
805
1026
|
const loops = isPlainObject(run.review) ? run.review : {};
|
|
806
1027
|
const loop = isPlainObject(loops[role]) && Number.isInteger(loops[role].round) ? loops[role] : { round: 0, outcome: null };
|
|
807
1028
|
if (loop.outcome) throw new Refusal(`review ${role}: the loop closed ${loop.outcome}; a closed loop does not reopen`);
|
|
808
|
-
const { next, say } = flag === '--round' ? openRound(root, role, loop, arg)
|
|
809
|
-
: flag === '--record' ? recordRound(root, role, loop)
|
|
1029
|
+
const { next, say } = flag === '--round' ? openRound(root, role, loop, arg, modelSegment(run, 'define-review'))
|
|
1030
|
+
: flag === '--record' ? recordRound(root, role, loop, modelSegment(run, role))
|
|
810
1031
|
: { next: closedLoop(loop, arg), say: `review ${role} closed ${arg} at round ${loop.round}` };
|
|
811
1032
|
saveRun(root, { ...run, review: { ...loops, [role]: next } });
|
|
812
1033
|
if (next.outcome) clearReviewDir(root);
|
|
@@ -817,7 +1038,7 @@ function review(root, sessionId, [role, flag, arg, extra]) {
|
|
|
817
1038
|
const closedLoop = (loop, outcome) => ({ round: loop.round, outcome, sha256: loop.sha256 ?? null });
|
|
818
1039
|
const clearReviewDir = (root) => rmSync(join(root, REVIEW_DIR), { recursive: true, force: true });
|
|
819
1040
|
|
|
820
|
-
function openRound(root, role, loop, rel) {
|
|
1041
|
+
function openRound(root, role, loop, rel, model) {
|
|
821
1042
|
if (loop.round > 0 && loop.await !== 'revision') throw new Refusal(`review ${role}: round ${loop.round} awaits its review record`);
|
|
822
1043
|
if (loop.round >= REVIEW_CAP) {
|
|
823
1044
|
throw new Refusal(`ORCH_REVIEW_CAP: review ${role} has run ${REVIEW_CAP} rounds; close it with --close skipped:<reason>`);
|
|
@@ -828,10 +1049,10 @@ function openRound(root, role, loop, rel) {
|
|
|
828
1049
|
if (loop.round > 0 && sha256 === loop.sha256) {
|
|
829
1050
|
return { next: closedLoop({ ...loop, round }, 'unchanged'), say: `review ${role} closed unchanged at round ${round}: ${rel} still hashes ${sha256}` };
|
|
830
1051
|
}
|
|
831
|
-
return { next: { round, outcome: null, sha256, doc: rel, await: 'review' }, say: `review ${role} round ${round} of ${REVIEW_CAP}: ${rel} sha256 ${sha256}` };
|
|
1052
|
+
return { next: { round, outcome: null, sha256, doc: rel, await: 'review' }, say: `review ${role} round ${round} of ${REVIEW_CAP}: ${rel} sha256 ${sha256}${model}` };
|
|
832
1053
|
}
|
|
833
1054
|
|
|
834
|
-
function recordRound(root, role, loop) {
|
|
1055
|
+
function recordRound(root, role, loop, model) {
|
|
835
1056
|
if (loop.await !== 'review') throw new Refusal(`review ${role} --record: no reviewer pass is open`);
|
|
836
1057
|
const path = `${REVIEW_DIR}/${role}-${loop.round}.md`;
|
|
837
1058
|
let bytes = null;
|
|
@@ -847,7 +1068,7 @@ function recordRound(root, role, loop) {
|
|
|
847
1068
|
const reviewSha = createHash('sha256').update(bytes).digest('hex');
|
|
848
1069
|
return {
|
|
849
1070
|
next: { ...loop, await: 'revision' },
|
|
850
|
-
say: `review ${role} round ${loop.round}: OPEN ${verdict.open}; revise ${loop.doc} sha256 ${loop.sha256} from ${path} sha256 ${reviewSha}`,
|
|
1071
|
+
say: `review ${role} round ${loop.round}: OPEN ${verdict.open}; revise ${loop.doc} sha256 ${loop.sha256} from ${path} sha256 ${reviewSha}${model}`,
|
|
851
1072
|
};
|
|
852
1073
|
}
|
|
853
1074
|
|
|
@@ -904,6 +1125,7 @@ function start(root, sessionId, args) {
|
|
|
904
1125
|
const stack = () => (detected ??= detectStack(root));
|
|
905
1126
|
const testCommand = checkTestCommand(resolveTestCommand(root, stack));
|
|
906
1127
|
const docs = resolveDocs(root, item);
|
|
1128
|
+
const models = resolveRoleModels(root);
|
|
907
1129
|
const security = resolveSecurity(root, stack(), { threshold, dependencyAudit });
|
|
908
1130
|
const bound = ticket === undefined ? null : ticketIntake(root, item, ticket);
|
|
909
1131
|
if (old) clearRunFiles(root);
|
|
@@ -914,10 +1136,11 @@ function start(root, sessionId, args) {
|
|
|
914
1136
|
v: 1, session_id: sessionId, item, mode: auto ? 'auto' : 'step', started: new Date().toISOString(),
|
|
915
1137
|
band: 'boundary', role: null, gate: 'boundary_routed', approvals: { spec: null, plan: null },
|
|
916
1138
|
plan: null, tasks: { ids: [], done: 0 }, handbacks: [], halt: null, test_command: testCommand, audit_rounds: auditRounds, security, docs,
|
|
1139
|
+
...(models ? { models } : {}),
|
|
917
1140
|
...(bound ? { ticket: { ...bound.binding, snapshot: bound.path } } : {}),
|
|
918
1141
|
});
|
|
919
1142
|
const begun = old ? `replaced the stale run ${old.item} started ${old.started}` : `run ${item} started`;
|
|
920
|
-
return `${begun}; ${bound ? ticketNote(bound) : ''}${docsNote(docs)}test command: ${testCommand}; audit rounds: ${auditRounds}${securityNote(security, root, stack())}`;
|
|
1143
|
+
return `${begun}; ${bound ? ticketNote(bound) : ''}${docsNote(docs)}test command: ${testCommand}; audit rounds: ${auditRounds}${securityNote(security, root, stack())}${modelsNote(models)}`;
|
|
921
1144
|
}
|
|
922
1145
|
|
|
923
1146
|
function clearRunFiles(root) {
|
|
@@ -942,6 +1165,89 @@ function recordHalt(root, halt) {
|
|
|
942
1165
|
} catch { /* an unreadable run file cannot carry its own halt */ }
|
|
943
1166
|
}
|
|
944
1167
|
|
|
1168
|
+
// 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.
|
|
1169
|
+
const ENVELOPE_ROLES = ['spec', 'plan', 'audit', 'qa'];
|
|
1170
|
+
const ENVELOPE_USAGE = 'usage: orchestrate.mjs envelope <spec|plan|audit|qa> [--item <label>] | --clear';
|
|
1171
|
+
const LABEL = /^[a-zA-Z0-9._-]+$/; // The sys.s pattern snap-validate enforces.
|
|
1172
|
+
|
|
1173
|
+
function parseEnvelopeArgs(args) {
|
|
1174
|
+
if (args.length === 1 && args[0] === '--clear') return { clear: true };
|
|
1175
|
+
const [role, flag, label] = args;
|
|
1176
|
+
if (!ENVELOPE_ROLES.includes(role)) throw new Refusal(ENVELOPE_USAGE);
|
|
1177
|
+
if (args.length === 1) return { role, label: 'adhoc' };
|
|
1178
|
+
if (args.length === 3 && flag === '--item' && LABEL.test(label)) return { role, label };
|
|
1179
|
+
throw new Refusal(ENVELOPE_USAGE);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// Read without throwing: an unreadable run file is another owner's to clear, never this verb's halt.
|
|
1183
|
+
function runState(root, sessionId) {
|
|
1184
|
+
const path = join(root, RUN_FILE);
|
|
1185
|
+
if (!existsSync(path)) return { state: 'N' };
|
|
1186
|
+
let run = null;
|
|
1187
|
+
try { run = JSON.parse(readFileSync(path, 'utf8')); } catch { /* judged below */ }
|
|
1188
|
+
if (isValidRun(run) && sessionId && run.session_id === sessionId) return { state: 'L', run, path };
|
|
1189
|
+
return { state: 'O', path };
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
function withRunFile(root, role, st) {
|
|
1193
|
+
const live = st.state === 'L';
|
|
1194
|
+
if (role === 'audit') {
|
|
1195
|
+
const who = live ? `live run ${st.run.item}` : `a run file at ${st.path} belongs to another session or is unreadable`;
|
|
1196
|
+
return `not-installed: ${who}; audit has no write tool and no shell, so it needs no envelope`;
|
|
1197
|
+
}
|
|
1198
|
+
if (role === 'qa' && live) {
|
|
1199
|
+
const command = st.run.test_command;
|
|
1200
|
+
if (typeof command !== 'string' || command === '') {
|
|
1201
|
+
throw new Refusal(`envelope qa: run ${st.run.item} records no test command, so Guard 7 grants qa no shell; end it, then start`);
|
|
1202
|
+
}
|
|
1203
|
+
return `not-installed: live run ${st.run.item}; qa runs ${command}`;
|
|
1204
|
+
}
|
|
1205
|
+
if (live) {
|
|
1206
|
+
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`);
|
|
1207
|
+
}
|
|
1208
|
+
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`);
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
function adhocFields(root, role, label) {
|
|
1212
|
+
const fields = {
|
|
1213
|
+
ph: PHASE[role], c: headCommit(root), s: label, n: [], f: [], d: [], x: [], role, tk: ROLE_ARTIFACTS[role].tk, gate: expectedGate(role),
|
|
1214
|
+
};
|
|
1215
|
+
if (role === 'spec' || role === 'plan') fields.scope = resolveDocs(root, label).scopes[role];
|
|
1216
|
+
if (role === 'qa') fields.p = { test_command: checkTestCommand(resolveTestCommand(root)) };
|
|
1217
|
+
return fields;
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
function installAdhoc(root, role, label) {
|
|
1221
|
+
if (!findAgent(role, root)) {
|
|
1222
|
+
throw new Halt('ORCH_AGENT_MISSING', `no agent definition named ${role} in .claude/agents/ or ~/.claude/agents/`);
|
|
1223
|
+
}
|
|
1224
|
+
const built = runScript('snap-build.mjs', [], JSON.stringify(adhocFields(root, role, label)));
|
|
1225
|
+
if (built.status !== 0) throw new Halt('SNAP_ERROR', built.err);
|
|
1226
|
+
const error = validate(built.out, role);
|
|
1227
|
+
if (error) throw new Halt('SNAP_ERROR', error);
|
|
1228
|
+
writeAtomic(join(root, ENVELOPE_FILE), built.out);
|
|
1229
|
+
return `installed: ${role} envelope at ${ENVELOPE_FILE}\n${built.out.trim()}`;
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
function clearAdhoc(root, st) {
|
|
1233
|
+
if (st.state !== 'N') throw new Refusal(`envelope --clear: a run file exists at ${st.path}; the envelope belongs to that run`);
|
|
1234
|
+
const path = join(root, ENVELOPE_FILE);
|
|
1235
|
+
if (!existsSync(path)) return 'no envelope';
|
|
1236
|
+
rmSync(path, { force: true });
|
|
1237
|
+
return 'cleared';
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
function envelopeVerb(root, sessionId, args) {
|
|
1241
|
+
const parsed = parseEnvelopeArgs(args);
|
|
1242
|
+
const st = runState(root, sessionId);
|
|
1243
|
+
if (parsed.clear) return clearAdhoc(root, st);
|
|
1244
|
+
if (st.state !== 'N') return withRunFile(root, parsed.role, st);
|
|
1245
|
+
// Every failure is a Refusal, so no halt is ever recorded in a run this verb does not own.
|
|
1246
|
+
try { return installAdhoc(root, parsed.role, parsed.label); } catch (e) {
|
|
1247
|
+
throw e instanceof Halt ? new Refusal(e.message) : e;
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
|
|
945
1251
|
export async function cli(argv, env, cwd = process.cwd()) {
|
|
946
1252
|
const [verb, a, b, c] = argv;
|
|
947
1253
|
const root = findRunRoot(cwd);
|
|
@@ -953,16 +1259,19 @@ export async function cli(argv, env, cwd = process.cwd()) {
|
|
|
953
1259
|
approve: () => approve(root, sid, a, b, c),
|
|
954
1260
|
hash: () => hashDoc(root, a, b),
|
|
955
1261
|
review: () => review(root, sid, argv.slice(1)),
|
|
1262
|
+
resume: () => resume(root, sid, argv.slice(1)),
|
|
1263
|
+
envelope: () => envelopeVerb(root, sid, argv.slice(1)),
|
|
956
1264
|
end: () => end(root),
|
|
957
1265
|
};
|
|
958
1266
|
try {
|
|
959
|
-
if (!verbs[verb]) throw new Refusal('usage: orchestrate.mjs start|install|handback|approve|hash|review|end');
|
|
1267
|
+
if (!verbs[verb]) throw new Refusal('usage: orchestrate.mjs start|install|handback|approve|hash|review|resume|envelope|end');
|
|
960
1268
|
process.stdout.write((await verbs[verb]()) + '\n');
|
|
961
1269
|
return 0;
|
|
962
1270
|
} catch (e) {
|
|
963
1271
|
if (e instanceof Refusal) { process.stderr.write(`orchestrate: ${e.message}\n`); return 2; }
|
|
964
1272
|
if (!(e instanceof Halt)) throw e;
|
|
965
|
-
|
|
1273
|
+
// resume never records a halt: one thrown by a helper it reuses must not overwrite the halt it was resuming (FEAT-055).
|
|
1274
|
+
if (!['start', 'envelope', 'resume'].includes(verb)) recordHalt(root, e);
|
|
966
1275
|
process.stderr.write(`${e.code}: ${e.reason}\n`);
|
|
967
1276
|
return 1;
|
|
968
1277
|
}
|