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