@yeison.restrepo.r/code-conductor 1.34.4 → 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 +34 -0
- package/lib/installer/host-owned.mjs +2 -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 +146 -4
- package/project-template/.claude/settings.json +1 -1
- package/project-template/gitignore +3 -0
- package/scripts/orchestrate.mjs +338 -0
- package/scripts/snap-build.mjs +21 -5
- package/scripts/snap-contract.mjs +31 -6
- package/scripts/snap-validate.mjs +16 -9
package/README.md
CHANGED
|
@@ -100,6 +100,29 @@ Four checks live in `tools/` as tracked repository infrastructure. Three of them
|
|
|
100
100
|
|
|
101
101
|
- **`[BUG-045]`, open:** the Guard 3 allowlist cannot cover a quoted path, because the boundary sets it interpolates contain no quote character, so an entry `docs/` does not cover `cat "docs/x.md" *.md`. Filed with its ritual priced, untouched pending its own change.
|
|
102
102
|
- **`[BUG-032]`, open:** global memory preferences sit outside the documented lookup chain. Nothing in the chain points at `~/.claude/memory/personal.md`, and the installer never deploys `global/memory/`, so a preference filed there is never read by the agent it was written for.
|
|
103
|
+
- **`[BUG-050]`, open:** the release instruments are silent on sub-shaped ids. `tools/record-parity.mjs` and `tools/id-ceiling.mjs` neither read nor reject an id like `[ARCH-008-S1]`, so a release claiming one would pass record parity having read nothing. No shipped release does; releases claim top-level ids until the item's spec chooses its repair.
|
|
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
|
+
- **`[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
|
+
- **`[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]`.
|
|
103
126
|
- **The `P7` false positive above**, still live.
|
|
104
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.
|
|
105
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.
|
|
@@ -205,6 +228,7 @@ All commands are tagged `(Conductor)` in the Claude Code command palette so they
|
|
|
205
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. |
|
|
206
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. |
|
|
207
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. |
|
|
208
232
|
|
|
209
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)).
|
|
210
234
|
| `/cc-review [file\|dir]` | Review code in three layers - Critical / Important / Suggestion - then deliver a verdict and offer to auto-fix. |
|
|
@@ -286,6 +310,14 @@ Hit a block you believe is wrong? Re-run the command with `CC_GUARD3_WARN=1` and
|
|
|
286
310
|
|
|
287
311
|
**node_modules guard (Guard 4)** - a `Read` whose path carries `node_modules` as an exact path component is denied, with backslashes and `..` resolved first. Use Glob for existence checks.
|
|
288
312
|
|
|
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.
|
|
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
|
+
|
|
289
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.
|
|
290
322
|
|
|
291
323
|
### context-guard *(global + project)* — v1.15.0
|
|
@@ -392,6 +424,7 @@ code-conductor/
|
|
|
392
424
|
│ │ ├── cc-spec.md /cc-spec
|
|
393
425
|
│ │ ├── cc-plan.md /cc-plan
|
|
394
426
|
│ │ ├── cc-implement.md /cc-implement
|
|
427
|
+
│ │ ├── cc-orchestrate.md /cc-orchestrate
|
|
395
428
|
│ │ ├── cc-review.md /cc-review
|
|
396
429
|
│ │ ├── cc-compact.md /cc-compact — phase boundary compaction
|
|
397
430
|
│ │ ├── cc-debug.md /cc-debug
|
|
@@ -411,6 +444,7 @@ code-conductor/
|
|
|
411
444
|
│ ├── snap-build.mjs SNAP v1/v2 handoff serializer
|
|
412
445
|
│ ├── snap-validate.mjs SNAP schema validator
|
|
413
446
|
│ ├── session-id.mjs Stable session-id resolver
|
|
447
|
+
│ ├── orchestrate.mjs Band router: run file, envelopes, hand-backs (FEAT-011)
|
|
414
448
|
│ └── detect-stack.mjs Stack auto-detection scanner
|
|
415
449
|
└── skills/
|
|
416
450
|
├── code-simplifier/SKILL.md Always active — complexity and simplicity rules
|
|
@@ -40,6 +40,8 @@ export const PROJECT_HOST_OWNED = new Map([
|
|
|
40
40
|
['memory/session-snapshot.json', 'skip'],
|
|
41
41
|
['memory/session-snapshot.md', 'skip'],
|
|
42
42
|
['memory/turn-count.txt', 'skip'],
|
|
43
|
+
['memory/band-envelope.json', 'skip'],
|
|
44
|
+
['memory/orchestrator-run.json', 'skip'],
|
|
43
45
|
['settings.json', 'merge'],
|
|
44
46
|
['settings.local.json', 'skip'],
|
|
45
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` |
|
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
// hookSpecificOutput.permissionDecision and EVERY path exits 0. Nothing here exits 2:
|
|
5
5
|
// a deliberate denial must never be indistinguishable from a crashed script.
|
|
6
6
|
// Zero dependencies by design; node: builtins only.
|
|
7
|
-
import { readFileSync, statSync } from 'node:fs';
|
|
8
|
-
import { posix, join } from 'node:path';
|
|
7
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
8
|
+
import { posix, join, resolve, dirname, relative, isAbsolute, sep } from 'node:path';
|
|
9
9
|
|
|
10
10
|
const LINE_LIMIT = 150;
|
|
11
11
|
const BLOCKED_COMPONENTS = new Set(['node_modules']);
|
|
@@ -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
|
|
|
@@ -108,6 +118,132 @@ function guard2DuplicateWrite(input) {
|
|
|
108
118
|
);
|
|
109
119
|
}
|
|
110
120
|
|
|
121
|
+
// ── Guard 5 constants ─────────────────────────────────────────────────────────
|
|
122
|
+
// Copies of scripts/snap-contract.mjs values (ARCH-010 D7). This file is mirrored to two
|
|
123
|
+
// locations and the contract sits at a different relative path from each, so no import is
|
|
124
|
+
// correct in both; tests/hooks/guard5.test.js pins every copy to the contract instead.
|
|
125
|
+
const BAND_ROLES = ['spec', 'plan', 'code', 'audit', 'qa'];
|
|
126
|
+
const BAND_TOOL_KINDS = ['R', 'RW', 'X'];
|
|
127
|
+
const BAND_WRITE_TOOLS = ['Write', 'Edit', 'create_file', 'write_file'];
|
|
128
|
+
const BAND_ENVELOPE_MAX_BYTES = 10485760;
|
|
129
|
+
const BAND_ENVELOPE_REL = ['.claude', 'memory', 'band-envelope.json'];
|
|
130
|
+
|
|
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());
|
|
133
|
+
|
|
134
|
+
// The band root is the nearest ancestor of cwd holding the envelope; the scope globs
|
|
135
|
+
// anchor there too, so discovery and anchoring are one rule (owner ruling, Case F).
|
|
136
|
+
// Guard 6 finds its run root by the same walk.
|
|
137
|
+
function findRootHolding(start, rel) {
|
|
138
|
+
let dir = resolve(start);
|
|
139
|
+
while (!existsSync(join(dir, ...rel))) {
|
|
140
|
+
const parent = dirname(dir);
|
|
141
|
+
if (parent === dir) return null;
|
|
142
|
+
dir = parent;
|
|
143
|
+
}
|
|
144
|
+
return dir;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Only what Guard 5 itself reads is checked. Anything less is Case C, not a guess.
|
|
148
|
+
function readEnvelope(path) {
|
|
149
|
+
let env;
|
|
150
|
+
try {
|
|
151
|
+
if (statSync(path).size > BAND_ENVELOPE_MAX_BYTES) return null;
|
|
152
|
+
env = JSON.parse(readFileSync(path, 'utf8'));
|
|
153
|
+
} catch { return null; }
|
|
154
|
+
if (!isPlainObject(env) || env.v !== 3 || !isPlainObject(env.sys) || !isPlainObject(env.ops)) return null;
|
|
155
|
+
if (!BAND_ROLES.includes(env.sys.role) || !BAND_TOOL_KINDS.includes(env.sys.tk)) return null;
|
|
156
|
+
const scope = env.ops.scope;
|
|
157
|
+
if (env.sys.tk === 'RW' && !(Array.isArray(scope) && scope.every((g) => typeof g === 'string'))) return null;
|
|
158
|
+
return env;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// `**/` spans zero or more directories, a trailing `**` any depth, `*` one segment.
|
|
162
|
+
function globToRegExp(glob) {
|
|
163
|
+
const body = glob.split(/(\*\*\/|\*\*|\*)/).map((part) => {
|
|
164
|
+
if (part === '**/') return '(?:.*/)?';
|
|
165
|
+
if (part === '**') return '.*';
|
|
166
|
+
if (part === '*') return '[^/]*';
|
|
167
|
+
return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
168
|
+
}).join('');
|
|
169
|
+
return new RegExp(`^${body}$`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Guard 5: a role agent writing outside its band envelope's declared scope (ARCH-010).
|
|
173
|
+
// The main session carries no agent_type and is never subject to it (Case A); with no
|
|
174
|
+
// envelope there is nothing to verify (Case B). Cases C-G are the spec's table.
|
|
175
|
+
function guard5BandScope(input, payload) {
|
|
176
|
+
const role = payload.agent_type;
|
|
177
|
+
if (!BAND_ROLES.includes(role)) return null;
|
|
178
|
+
const cwd = payloadCwd(payload);
|
|
179
|
+
const root = findRootHolding(cwd, BAND_ENVELOPE_REL);
|
|
180
|
+
if (!root) return null;
|
|
181
|
+
const file = join(root, ...BAND_ENVELOPE_REL);
|
|
182
|
+
const env = readEnvelope(file);
|
|
183
|
+
if (!env) return deny(`Guard 5: BAND_ENVELOPE_INVALID: ${file} is unreadable or not a valid v3 band envelope.`);
|
|
184
|
+
if (env.sys.role !== role) return deny(`Guard 5: BAND_ROLE_MISMATCH: agent ${role} is not the envelope's role ${env.sys.role}.`);
|
|
185
|
+
if (env.sys.tk !== 'RW') return deny(`Guard 5: BAND_READ_ONLY: role ${role} holds tk ${env.sys.tk}, not RW.`);
|
|
186
|
+
const target = targetPath(input);
|
|
187
|
+
const rel = relative(root, resolve(cwd, target)).split(sep).join('/');
|
|
188
|
+
const inside = target !== '' && rel !== '' && rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel);
|
|
189
|
+
if (inside && env.ops.scope.some((g) => globToRegExp(g).test(rel))) return null;
|
|
190
|
+
return deny(`Guard 5: BAND_SCOPE_VIOLATION: ${target || '<no path>'} is outside the declared scope [${env.ops.scope.join(', ')}]`);
|
|
191
|
+
}
|
|
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
|
+
|
|
111
247
|
// ── Guard 3 constants ─────────────────────────────────────────────────────────
|
|
112
248
|
// POSIX ERE fragments from tests/fixtures/guard3-reference.sh, translated class by
|
|
113
249
|
// class. [[:space:]] in the C locale is EXACTLY [ \t\n\r\f\v]; JavaScript \s also
|
|
@@ -563,6 +699,11 @@ const DISPATCH = {
|
|
|
563
699
|
Edit: [],
|
|
564
700
|
Bash: [guard3BashScan],
|
|
565
701
|
};
|
|
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];
|
|
566
707
|
|
|
567
708
|
// Case B. Unparseable input is not "nothing to verify", it is "the verifier could not
|
|
568
709
|
// run", which is the condition that fails closed. CC_HOOK_ALLOW bypasses THIS denial only;
|
|
@@ -600,9 +741,10 @@ function main() {
|
|
|
600
741
|
const guards = DISPATCH[name];
|
|
601
742
|
if (!guards) { debug(`no guard registered for tool_name "${name}"; allowing`); return; }
|
|
602
743
|
for (const guard of guards) {
|
|
603
|
-
const decision = guard(input);
|
|
744
|
+
const decision = guard(input, payload);
|
|
604
745
|
if (decision) { emit(decision); return; }
|
|
605
746
|
}
|
|
747
|
+
if (warning) emit(null);
|
|
606
748
|
}
|
|
607
749
|
|
|
608
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);
|
package/scripts/snap-build.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
|
-
import { CAPS, PRE_PARSE_MAX_BYTES as MAX_SNAP_BYTES, V1_MAX_CHARS } from './snap-contract.mjs';
|
|
2
|
+
import { CAPS, PRE_PARSE_MAX_BYTES as MAX_SNAP_BYTES, V1_MAX_CHARS, V3_CAPS } from './snap-contract.mjs';
|
|
3
3
|
|
|
4
4
|
const die = (msg) => { process.stderr.write(`SNAP_BUILD_ERROR: ${msg}\n`); process.exit(1); };
|
|
5
5
|
const byteLen = (s) => Buffer.byteLength(s, 'utf8');
|
|
@@ -49,7 +49,22 @@ const ops = { n: normArray(obj.n, CAPS['ops.n']), f: normArray(obj.f, CAPS['ops.
|
|
|
49
49
|
const mem = { d: normArray(obj.d, CAPS['mem.d']), x: normArray(obj.x, CAPS['mem.x']) };
|
|
50
50
|
const pr = typeof obj.pr === 'string' ? obj.pr : '';
|
|
51
51
|
|
|
52
|
-
|
|
52
|
+
// ---- v3: any band field selects the band envelope (ARCH-010); without one, v1/v2 are untouched ----
|
|
53
|
+
const band = ['role', 'tk', 'scope', 'gate', 'p'].some((k) => obj[k] !== undefined);
|
|
54
|
+
if (band) {
|
|
55
|
+
for (const k of ['role', 'tk', 'gate']) {
|
|
56
|
+
if (typeof obj[k] !== 'string' || obj[k] === '') die(`missing or empty scalar: ${k}`);
|
|
57
|
+
}
|
|
58
|
+
if (obj.scope !== undefined && !Array.isArray(obj.scope)) die('scope must be an array');
|
|
59
|
+
if (obj.p !== undefined && (typeof obj.p !== 'object' || obj.p === null || Array.isArray(obj.p))) die('p must be a plain object');
|
|
60
|
+
// Assignment order is serialization order: BLOCK_FIELDS[3] lists scope before gate.
|
|
61
|
+
Object.assign(sys, { role: obj.role, tk: obj.tk });
|
|
62
|
+
if (obj.scope !== undefined) ops.scope = normArray(obj.scope, V3_CAPS['ops.scope']);
|
|
63
|
+
ops.gate = obj.gate;
|
|
64
|
+
if (obj.p !== undefined) mem.p = obj.p;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (pr === '' && !band) {
|
|
53
68
|
// ---- v1: V1_MAX_CHARS cap, drop oldest of mem.d / ops.f ----
|
|
54
69
|
const snap = { v: 1, sys, ops, mem };
|
|
55
70
|
let line = JSON.stringify(snap);
|
|
@@ -60,8 +75,9 @@ if (pr === '') {
|
|
|
60
75
|
}
|
|
61
76
|
writeOut(line);
|
|
62
77
|
} else {
|
|
63
|
-
// ---- v2: 10 MiB cap, truncate raw pr before serialize ----
|
|
64
|
-
const
|
|
78
|
+
// ---- v2 and v3: 10 MiB cap, truncate raw pr before serialize ----
|
|
79
|
+
const v = band ? 3 : 2;
|
|
80
|
+
const skeletonBytes = byteLen(JSON.stringify({ v, sys, ops, mem, pr: '' }));
|
|
65
81
|
if (skeletonBytes > MAX_SNAP_BYTES) die('skeleton exceeds cap even without prose');
|
|
66
82
|
|
|
67
83
|
// total serialized bytes for a candidate pr value (skeleton already counts the two empty-value quotes)
|
|
@@ -82,6 +98,6 @@ if (pr === '') {
|
|
|
82
98
|
}
|
|
83
99
|
}
|
|
84
100
|
|
|
85
|
-
const snap = { v
|
|
101
|
+
const snap = { v, sys, ops, mem, pr: pr.slice(0, keep) };
|
|
86
102
|
writeOut(JSON.stringify(snap));
|
|
87
103
|
}
|
|
@@ -14,13 +14,13 @@ export const PRE_PARSE_MAX_BYTES = 10485760; // 10 MiB
|
|
|
14
14
|
// constraint, kept under its own name.
|
|
15
15
|
export const V1_MAX_CHARS = 4096;
|
|
16
16
|
|
|
17
|
-
// Post-parse, version-specific caps, applied once snap.v is known.
|
|
18
|
-
//
|
|
19
|
-
export const POST_PARSE_MAX = { 1: V1_MAX_CHARS, 2: PRE_PARSE_MAX_BYTES };
|
|
17
|
+
// Post-parse, version-specific caps, applied once snap.v is known. v2 and v3 share the
|
|
18
|
+
// pre-parse ceiling: neither is a context-budget file.
|
|
19
|
+
export const POST_PARSE_MAX = { 1: V1_MAX_CHARS, 2: PRE_PARSE_MAX_BYTES, 3: PRE_PARSE_MAX_BYTES };
|
|
20
20
|
|
|
21
21
|
// Highest v this contract understands. Raising it here moves the
|
|
22
22
|
// SNAP_UNKNOWN_VERSION boundary with no edit anywhere else.
|
|
23
|
-
export const MAX_VERSION =
|
|
23
|
+
export const MAX_VERSION = 3;
|
|
24
24
|
|
|
25
25
|
// One array-cap table in ONE key scheme: dotted path to [count cap, element cap].
|
|
26
26
|
// Two schemes for one table is how a drift hides from every diff and grep.
|
|
@@ -30,10 +30,35 @@ export const CAPS = {
|
|
|
30
30
|
'mem.d': [10, 300],
|
|
31
31
|
'mem.x': [5, 200],
|
|
32
32
|
};
|
|
33
|
+
// Same scheme, v3 only: ops.scope exists in no earlier version, so it cannot join CAPS.
|
|
34
|
+
export const V3_CAPS = { 'ops.scope': [20, 300] };
|
|
33
35
|
|
|
34
|
-
// Field sets
|
|
36
|
+
// Field sets, both per version. v1 and v2 share one block map, unchanged since v1;
|
|
37
|
+
// v3 adds the band fields reserved by FEAT-010 (ARCH-010).
|
|
35
38
|
export const TOP_FIELDS = {
|
|
36
39
|
1: ['v', 'sys', 'ops', 'mem'],
|
|
37
40
|
2: ['v', 'sys', 'ops', 'mem', 'pr'],
|
|
41
|
+
3: ['v', 'sys', 'ops', 'mem', 'pr'],
|
|
38
42
|
};
|
|
39
|
-
|
|
43
|
+
const V1_BLOCKS = { sys: ['ph', 'c', 's'], ops: ['n', 'f'], mem: ['d', 'x'] };
|
|
44
|
+
export const BLOCK_FIELDS = {
|
|
45
|
+
1: V1_BLOCKS,
|
|
46
|
+
2: V1_BLOCKS,
|
|
47
|
+
3: { sys: ['ph', 'c', 's', 'role', 'tk'], ops: ['n', 'f', 'scope', 'gate'], mem: ['d', 'x', 'p'] },
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// The band contract (ARCH-010). A role names an agent with a mask behind it, so the roster
|
|
51
|
+
// stops at FEAT-012's five and widens only at a new version. A gate names a band's whole
|
|
52
|
+
// exit condition, which the ARCH-009 band table fixes independently of any agent.
|
|
53
|
+
export const ROLES = ['spec', 'plan', 'code', 'audit', 'qa'];
|
|
54
|
+
export const TOOL_KINDS = ['R', 'RW', 'X'];
|
|
55
|
+
export const BANDS = ['boundary', 'define', 'build', 'verify', 'ship'];
|
|
56
|
+
export const GATES = ['boundary_routed', 'define_approved', 'build_executed', 'verify_pass', 'ship_released'];
|
|
57
|
+
export const ROLE_BAND = { spec: 'define', plan: 'define', code: 'build', audit: 'verify', qa: 'verify' };
|
|
58
|
+
// The tools Guard 5 gates. The hook cannot import this module from both of its install
|
|
59
|
+
// locations, so it carries a copy that tests/hooks/guard5.test.js pins to this one (D7).
|
|
60
|
+
export const WRITE_TOOLS = ['Write', 'Edit', 'create_file', 'write_file'];
|
|
61
|
+
|
|
62
|
+
// A receiving role expects the exit gate of the band before its own: GATES[i] is the
|
|
63
|
+
// exit of BANDS[i].
|
|
64
|
+
export const expectedGate = (role) => GATES[BANDS.indexOf(ROLE_BAND[role]) - 1];
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs'; import { BLOCK_FIELDS, CAPS, MAX_VERSION, POST_PARSE_MAX, PRE_PARSE_MAX_BYTES, TOP_FIELDS } from './snap-contract.mjs';
|
|
1
|
+
import { readFileSync } from 'node:fs'; import { BLOCK_FIELDS, CAPS, GATES, MAX_VERSION, POST_PARSE_MAX, PRE_PARSE_MAX_BYTES, ROLES, TOOL_KINDS, TOP_FIELDS, V3_CAPS, expectedGate } from './snap-contract.mjs';
|
|
2
2
|
const err = (m) => { process.stderr.write(`SNAP_ERROR: ${m}\n`); process.exit(1); };
|
|
3
|
-
const path = process.argv
|
|
3
|
+
const [path, flag, to] = process.argv.slice(2); if (path === undefined) err('no path provided');
|
|
4
|
+
if (flag !== undefined && (flag !== '--to' || !ROLES.includes(to))) err(`usage: snap-validate.mjs <file> [--to ${ROLES.join('|')}]`);
|
|
4
5
|
let raw; try { raw = readFileSync(path, 'utf8'); } catch (e) { err(e.code === 'ENOENT' ? 'file not found' : e.code); }
|
|
5
6
|
if (raw.includes('�')) err('encoding error');
|
|
6
7
|
const trimmed = raw.trim(); if (trimmed.includes('\n')) err('internal newline in payload');
|
|
@@ -8,18 +9,23 @@ if (trimmed === '') err('empty file');
|
|
|
8
9
|
if (raw.length > PRE_PARSE_MAX_BYTES) err(`payload too large: ${raw.length} > ${PRE_PARSE_MAX_BYTES} (pre-parse ceiling)`);
|
|
9
10
|
let snap; try { snap = JSON.parse(trimmed); } catch { err('malformed JSON'); }
|
|
10
11
|
if (typeof snap !== 'object' || snap === null || Array.isArray(snap)) err('root must be a plain object');
|
|
12
|
+
// D2: v is decided before every check whose meaning depends on it (BUG-038's check-order class, second sighting).
|
|
13
|
+
if (snap.v === undefined) err('missing: v'); if (typeof snap.v !== 'number' || !Number.isInteger(snap.v) || snap.v < 1) err('v must be a positive integer');
|
|
14
|
+
if (snap.v > MAX_VERSION) err('SNAP_UNKNOWN_VERSION');
|
|
11
15
|
for (const b of ['sys', 'ops', 'mem']) if (typeof snap[b] !== 'object' || snap[b] === null || Array.isArray(snap[b])) err(`missing block: ${b}`);
|
|
12
|
-
const
|
|
13
|
-
const missing =
|
|
16
|
+
const band = snap.v >= 3; const at = (k) => snap[k.split('.')[0]][k.split('.')[1]];
|
|
17
|
+
const missing = ['sys.ph', 'sys.c', 'sys.s', 'ops.n', 'ops.f', 'mem.d', 'mem.x', ...(band ? ['sys.role', 'sys.tk', 'ops.gate'] : [])].filter(k => at(k) === undefined);
|
|
14
18
|
if (missing.length) { for (const k of missing) process.stderr.write(`SNAP_ERROR: missing: ${k}\n`); process.exit(1); }
|
|
15
|
-
const
|
|
16
|
-
const topExtra = Object.keys(snap).find(k => !topAllowed.includes(k)); if (topExtra) err(`unexpected key: ${topExtra}`);
|
|
19
|
+
const topExtra = Object.keys(snap).find(k => !TOP_FIELDS[snap.v].includes(k)); if (topExtra) err(`unexpected key: ${topExtra}`);
|
|
17
20
|
if (snap.pr !== undefined && typeof snap.pr !== 'string') err('pr must be a string');
|
|
18
|
-
for (const b of ['sys', 'ops', 'mem']) { const extra = Object.keys(snap[b]).find(k => !BLOCK_FIELDS[b].includes(k)); if (extra) err(`unexpected key: ${b}.${extra}`); }
|
|
19
|
-
if (typeof snap.v !== 'number' || !Number.isInteger(snap.v) || snap.v < 1) err('v must be a positive integer'); if (snap.v > MAX_VERSION) err('SNAP_UNKNOWN_VERSION');
|
|
21
|
+
for (const b of ['sys', 'ops', 'mem']) { const extra = Object.keys(snap[b]).find(k => !BLOCK_FIELDS[snap.v][b].includes(k)); if (extra) err(`unexpected key: ${b}.${extra}`); }
|
|
20
22
|
if (raw.length > POST_PARSE_MAX[snap.v]) err(`payload too large: ${raw.length} > ${POST_PARSE_MAX[snap.v]} (v${snap.v} cap)`);
|
|
21
23
|
if (!['spec', 'plan', 'impl', 'rev'].includes(snap.sys.ph)) err('ph must be spec|plan|impl|rev');
|
|
22
|
-
|
|
24
|
+
if (band && !ROLES.includes(snap.sys.role)) err(`role must be ${ROLES.join('|')}`); if (band && !TOOL_KINDS.includes(snap.sys.tk)) err(`tk must be ${TOOL_KINDS.join('|')}`);
|
|
25
|
+
if (band && !GATES.includes(snap.ops.gate)) err(`gate must be ${GATES.join('|')}`); if (band && snap.sys.tk === 'RW' && snap.ops.scope === undefined) err('missing: ops.scope (required when tk is RW)');
|
|
26
|
+
const p = snap.mem.p; if (p !== undefined && (typeof p !== 'object' || p === null || Array.isArray(p))) err('p must be a plain object');
|
|
27
|
+
const arrayCaps = { ...CAPS, ...(snap.ops.scope === undefined ? {} : V3_CAPS) };
|
|
28
|
+
for (const [key, [cap, elemCap]] of Object.entries(arrayCaps)) {
|
|
23
29
|
const [blk, sub] = key.split('.'); const arr = snap[blk][sub]; if (!Array.isArray(arr)) err(`${key} must be an array`); if (arr.length > cap) err(`${key} exceeds cap`);
|
|
24
30
|
arr.forEach((el, i) => { if (typeof el !== 'string' || el.trim() === '') err(`empty element in ${key}[${i}]`); if (JSON.stringify(el).slice(1, -1).length > elemCap) err(`element too long in ${key}[${i}]`); });
|
|
25
31
|
}
|
|
@@ -29,4 +35,5 @@ snap.ops.f.forEach((el, i) => {
|
|
|
29
35
|
if (!['C', 'M', 'D'].includes(el.slice(idx + 1))) err(`invalid action code in ops.f[${i}]`);
|
|
30
36
|
});
|
|
31
37
|
if (!/^[0-9a-f]{7,64}$/.test(snap.sys.c)) err('invalid sys.c format'); if (!/^[a-zA-Z0-9._-]+$/.test(snap.sys.s)) err('invalid chars in sys.s');
|
|
38
|
+
if (to !== undefined && !band) err('--to requires a v3 envelope'); if (to !== undefined && snap.ops.gate !== expectedGate(to)) err(`SNAP_GATE_MISMATCH: ${to} expects ${expectedGate(to)}, got ${snap.ops.gate}`);
|
|
32
39
|
process.exit(0);
|