@yeison.restrepo.r/code-conductor 1.52.5 → 1.52.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -500,7 +500,6 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
500
500
  - **`[BUG-071]`, open:** the OpenCode guard plugin forwards only `command` from OpenCode's `bash` call, so if that tool runs a command in another working directory, Guard 3 evaluates it as if it ran in the project root. Until it is fixed, treat Guard 3 under OpenCode as best-effort for commands that set their own working directory.
501
501
  - **`[BUG-072]`, open:** the reserved list for recorded spec and plan folders misses root dot-directories outside `.claude` (such as `.husky`, `.vscode`, `.devcontainer`) and `bin`, `lib`, `tools`, so a `- Specs:` or `- Plans:` line in the project `CLAUDE.md` can make one of them the spec or plan agent's Guard 5 write scope. Until it is fixed, review any `- Specs:` or `- Plans:` line in the project `CLAUDE.md` and keep it pointing at a documentation folder.
502
502
  - **`[BUG-074]`, open:** the `/cc-orchestrate` role definitions disagree on when a task's tests are done: `code` may hand back `build_executed` on a red suite, `plan` requires each task to end green, and `qa` passes only on exit 0, so one suite result gates differently depending on the role. Until it is fixed, read a `build_executed` hand-back's reported suite exit code yourself and treat a non-zero one as not done.
503
- - **`[BUG-075]`, open:** `scripts/orchestrate.mjs` validates only the shape of a role hand-back, so it accepts a `build_executed` whose report says the suite failed or whose `ops.f` lists out-of-scope paths, lets `end` close a run with no `verify_pass`, and stamps an approval with the global `git config user.name`; Guards 5 and 7 still block the out-of-scope writes themselves. Until it is fixed, check that a run reached `verify_pass` before trusting its record, and do not read the approval name as proof of who approved.
504
503
  - **`[BUG-078]`, open:** `scripts/orchestrate.mjs` builds a fix round's write scope with the approved plan included, so Guard 5 lets the fix-round `code` agent write to the plan and only the brief's instruction stops it; any change other than checkbox ticks still halts the run with `ORCH_APPROVED_DOC_CHANGED` on the next `install audit` or fix round, and ticks do not affect `tasks.done`. Until it is fixed, check after a fix round that the approved plan's checkboxes are unchanged.
505
504
  - **`[BUG-079]`, open:** `scripts/orchestrate.mjs` stores every non-security hand-back's full SNAP in `.claude/memory/orchestrator-run.json` with a 64 KiB cap per SNAP but no cap on the total, so a plan of roughly 80 or more tasks with maximally sized hand-backs can push the run file past the hook's 10 MiB read cap, after which `readRunFile` returns null and Guard 6 downgrades from deny to warn for the rest of the run. Until it is fixed, keep orchestrated plans well under 80 tasks, or split a larger item into several runs.
506
505
  - **The `P7` false positive** described under [Guard 3, and what it learned](#guard-3-and-what-it-learned) is still live.
@@ -1,4 +1,4 @@
1
- import { cpSync, mkdirSync, chmodSync, existsSync, lstatSync, readdirSync, readFileSync, statSync, rmSync, unlinkSync } from 'node:fs';
1
+ import { cpSync, mkdirSync, chmodSync, existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, statSync, rmSync, unlinkSync } from 'node:fs';
2
2
  import { join, relative, isAbsolute, sep } from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { mergeFileInto, resolveRealTarget } from './file-merge.mjs';
@@ -242,10 +242,31 @@ const PLUGIN_IN_PLACE = new Set(['created', 'merged', 'unchanged']);
242
242
  // still backs up a copy the host edited before replacing it (BUG-069).
243
243
  const replaceWithTemplate = (templateText, hostText) => ({ text: templateText, changed: hostText !== templateText });
244
244
 
245
+ // The plugin is a managed asset, so a link at its path is removed, never followed:
246
+ // writing through it would overwrite whatever file the checkout points it at (BUG-087).
247
+ // Returns false when the link is still there, so nothing may be written.
248
+ function removePluginSymlink(pluginPath, warn) {
249
+ let st;
250
+ try { st = lstatSync(pluginPath); } catch { return true; }
251
+ if (!st.isSymbolicLink()) return true;
252
+ let linkText = 'an unreadable target';
253
+ try { linkText = readlinkSync(pluginPath); } catch { /* raced away; the unlink still decides */ }
254
+ try {
255
+ unlinkSync(pluginPath);
256
+ } catch (err) {
257
+ warn(`code-conductor: skipping ${OPENCODE_PLUGIN} — it is a symlink and could not be removed (${err.code}); nothing was written`);
258
+ return false;
259
+ }
260
+ warn(`code-conductor: replaced the symlink at ${OPENCODE_PLUGIN} (it pointed to ${linkText}) with the shipped plugin; the file it pointed to was not touched`);
261
+ return true;
262
+ }
263
+
245
264
  function installOpencodePlugin(templateRoot, cwd, { warn, report }) {
246
265
  const parts = OPENCODE_PLUGIN.split('/');
247
266
  mkdirSync(join(cwd, ...parts.slice(0, -1)), { recursive: true });
248
- const status = mergeFileInto(join(templateRoot, ...parts), join(cwd, ...parts), replaceWithTemplate, {
267
+ const pluginPath = join(cwd, ...parts);
268
+ if (!removePluginSymlink(pluginPath, warn)) return;
269
+ const status = mergeFileInto(join(templateRoot, ...parts), pluginPath, replaceWithTemplate, {
249
270
  warn,
250
271
  onBackup: backupReporter(report, { root: cwd, rootLabel: '', file: OPENCODE_PLUGIN, ignoredByDesign: true, action: 'replacing it' }),
251
272
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yeison.restrepo.r/code-conductor",
3
- "version": "1.52.5",
3
+ "version": "1.52.7",
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",
@@ -34,6 +34,8 @@ A halt stops the run (D12, amended by FEAT-055). Recovery is `node "$S/orchestra
34
34
 
35
35
  `install code|audit|qa` halts `ORCH_APPROVED_DOC_CHANGED` when the approved spec or plan changed after its approval (a ticked plan checkbox is not a change), and `ORCH_APPROVAL_UNHASHED` on a run whose approvals were recorded before FEAT-056. Recovery for both is `end`, then `start`. `install security` halts the same two codes.
36
36
 
37
+ `handback <role>` halts `ORCH_HANDBACK_SCOPE_MISMATCH` when the hand-back's `ops.scope` is not the scope `install` wrote for that position, entry for entry and in the same order, or when `audit`, `security` or `qa`, which are installed with no scope, hand back one; and `ORCH_HANDBACK_OUT_OF_SCOPE` when a path in `ops.f` is absolute, has an empty, `.` or `..` segment, or lies outside that scope. The script recomputes the scope from the plan and the run's pinned folders; it never reads it back from `.claude/memory/band-envelope.json`. Neither halt records the hand-back. For both, name the hand-back file you passed: it is what the owner reads next. Recovery is `resume` or `end`, then `start`.
38
+
37
39
  `handback audit` halts `ORCH_VERDICT_MISSING`, `ORCH_VERDICT_INVALID` or `ORCH_VERDICT_INCONSISTENT` when the audit report's `VERDICT:` line is absent, malformed, misplaced or contradicts its findings; `ORCH_AUDIT_RETURN` when the audit returned the change and the run has no fix rounds left; `ORCH_AUDIT_ESCALATE` when the audit escalated a decision to the owner, at any round; and `ORCH_FIX_SCOPE_UNAPPROVED` when a blocker or major finding of a returned audit names a file outside the approved plan's task files, or the approved spec or plan. For those six, also name `.conductor/handback/audit-<round>.txt`: its findings are what the owner reads next. `handback qa` halts `ORCH_GATE_WITHHELD` when the run's last audit entry carries no `VERDICT: APPROVE`. Recovery for all seven is `end`, then `start`.
38
40
 
39
41
  `install security` and `handback security` halt `ORCH_VERDICT_MISSING`, `ORCH_VERDICT_INVALID` or `ORCH_VERDICT_INCONSISTENT` as `handback audit` does, because the same parser reads the security report's `VERDICT:` line (a failed scan without `VERDICT: ESCALATE` is also `ORCH_VERDICT_INCONSISTENT`); `ORCH_SECURITY_REPORT_MISSING` / `ORCH_SECURITY_REPORT_INVALID` (no, malformed or misplaced `SCANS:` line or owner-only block, a malformed finding line, a severity that does not match the run's threshold, a dependency finding outside the run's lockfile or filed in the wrong part, or a report that contradicts the run's `dependency`); `ORCH_SECURITY_REPORT_INCOMPLETE` (the script's own re-run of the local scan found a status or a line the report lacks or files in the wrong part); `ORCH_SECURITY_SCAN_FAILED` (a scan did not complete, the base commit does not track the scanner, or its scanner predates FEAT-059); `ORCH_SECURITY_BLOCKED` (`VERDICT: RETURN`: a finding the change introduces at or above the run's threshold); and `ORCH_SECURITY_ESCALATE` (`VERDICT: ESCALATE` with every scan run: a decision only the owner takes). For those, also name `.conductor/handback/security.txt`: its findings are what the owner reads next; never quote its owner-only block. `handback qa` also halts `ORCH_GATE_WITHHELD` when the last security verdict is not `VERDICT: APPROVE` or is absent. Recovery is `end`, then `start`. After updating an installed project, commit the updated `.claude/scripts/security-scan.mjs` before the next `start`: a base commit that still holds the 1.48.0 scanner halts `ORCH_SECURITY_SCAN_FAILED` and names that recovery.
@@ -42,11 +44,13 @@ A halt stops the run (D12, amended by FEAT-055). Recovery is `node "$S/orchestra
42
44
 
43
45
  **Resume (FEAT-055).** Offer `resume` next to `end` when the run recorded the spec approval; run it only on the owner's word, as `end`. `node "$S/orchestrate.mjs" resume` takes no argument. It keeps both approvals when each approved document still hashes as approved and HEAD descends from the commit each approval recorded, then keeps the Build task hand-backs, in order, while each stored SNAP still validates and HEAD descends from its commit. Every record after the first that fails, and every Verify record (audit, fix round, security, qa), is dropped and redone. On success it prints `run <ITEM> resumed after <code> from <gate>: kept <k> record(s), dropped <d>; next: <step>`: print the run header again and continue at step 2 with the step it names (`install <role> --check`, the pause in step mode, `install <role>`, a fresh dispatch); never revive the halted agent. A refusal exits 2 and writes nothing, so the run stays halted: `ORCH_RESUME_NO_RUN` (no valid run file), `ORCH_RESUME_NOT_HALTED` (the run is live: continue with the step it names), `ORCH_NO_SESSION_ID`, `ORCH_RESUME_NO_GATE` (no spec approval), `ORCH_APPROVAL_UNHASHED` (approved before FEAT-056), `ORCH_RESUME_UNANCHORED` (an approval records no commit, or git cannot check it), `ORCH_APPROVED_DOC_CHANGED` (an approved document changed; a ticked plan checkbox is not a change) and `ORCH_RESUME_HISTORY_REWRITTEN` (HEAD no longer descends from an approval's commit). After any of them but `ORCH_RESUME_NOT_HALTED`, recovery is `end`, then `start`.
44
46
 
47
+ **Abandon (BUG-075).** `end` ends a live run only after `qa` records `verify_pass`; a halted run, an invalid run file and a missing one need no flag. On a live run with no `verify_pass`, `end` refuses with `ORCH_END_UNVERIFIED`, exit 2, and removes nothing. To drop such a run on the owner's word only (after `ORCH_RUN_ACTIVE`, after a declined pause, or to restart), run `node "$S/orchestrate.mjs" end --abandon`. Its first line reads `run <ITEM> abandoned at <gate> before verify_pass` and the record follows: report that line, and never present the run as finished. Never pass `--abandon` on your own.
48
+
45
49
  ## Steps
46
50
 
47
51
  1. **Start.** Run `node "$S/orchestrate.mjs" start $ARGUMENTS`. It resolves the run's test command and its spec and plan folders before it writes anything, and its stdout ends with `docs: specs <dir>, plans <dir> (<source>)[; group <group>]; test command: <command>; audit rounds: <n>; security: threshold <level>, dependency scan <command | not covered for <reason> | disabled (--no-dependency-audit)>`. With a `- Role models:` line in the project `CLAUDE.md`, it then ends with `; role models: spec=<m>, plan=<m>, code=<m>, audit=<m>, security=<m>, qa=<m>, define-review=<m>`, each `<m>` one of `opus`, `sonnet`, `haiku` or `inherit`, followed by `; note: audit and code share <m>` when both name the same model (FEAT-053).
48
52
  - If stdout names a replaced stale run, report its item and start time.
49
- - On `ORCH_RUN_ACTIVE`, report it, offer `end`, and stop.
53
+ - On `ORCH_RUN_ACTIVE`, report it, offer `end --abandon` (see "Abandon" under "On any halt"), and stop.
50
54
  - On `ORCH_TEST_COMMAND_UNRESOLVED` or `ORCH_TEST_COMMAND_UNSAFE`, report it and stop. No run file was written, so there is nothing to `end`. The owner adds a `test` script to `package.json`, or removes the chaining from the command it names, before a fresh `start`.
51
55
  - On `ORCH_SECURITY_COMMAND_UNSAFE`, report it and stop in the same way: a recorded security command carries chaining, and no run file was written.
52
56
  - On `ORCH_DOC_LOCATION_INVALID`, report it and stop. No run file was written. The owner fixes the named `- Specs:` / `- Plans:` line in `CLAUDE.md` (add the missing one, fix the value, or use two disjoint folders) before a fresh `start`.
@@ -79,7 +83,7 @@ A halt stops the run (D12, amended by FEAT-055). Recovery is `node "$S/orchestra
79
83
  - **After plan:** show the owner the plan path named in the hand-back's `ops.f`. On approval, run `node "$S/orchestrate.mjs" approve plan <plan path> <sha256>` with the path and hash you showed. This writes `define_approved`, the only gate you author after `boundary_routed`.
80
84
  - **Unattended (FEAT-054).** When the start line ended with the unattended segment, show the approval as above, then run `node "$S/orchestrate.mjs" delegate <spec|plan> --check`. It prints `delegate <kind>: <doc> sha256 <hash>; source <source>`, ending `; model <alias>` in a run with role models. Dispatch a fresh `define-review` agent with the define brief below, filled from that line only; pass the model by the rule of step 2.4. The brief carries no author report, no review-loop finding, no observation line and no earlier verdict. Write its report verbatim with the Write tool to `.conductor/delegate/<kind>.md`, then run `node "$S/orchestrate.mjs" delegate <kind> <doc> <hash>` with the path and hash the `--check` line printed. On `<kind> approved by delegated review: …`, the approval is recorded with `define-review` as approver: continue. On `owner approval required: …`, show the reviewer's findings and wait for an owner message, exactly as in attended mode; the owner approves with `approve`. `delegate` runs once per approval: a second attempt refuses `ORCH_DELEGATED_ONCE`. On any refusal of `delegate` (`ORCH_NOT_UNATTENDED`, `ORCH_REVIEW_OPEN`, `ORCH_REVIEW_DOC_MISMATCH`, `ORCH_DOC_HASH_STALE`, a missing report, a document the hand-back does not name), wait for the owner as well; never retry another way. An owner message during an unattended run is the owner's word, as always. Known limit: the run file is inside your write surface, so a hand edit could set `unattended` just as it could forge an approval; Guard 6 does not stop it, and nothing in this command may do it.
81
85
  4. **Build.** Dispatch `code` once per plan task, serially, until the router moves on to `audit`. A `--check` refusal names the next step.
82
- 5. **Verify.** Dispatch `audit`. The audit report ends in one `VERDICT:` line just before its `SNAP_HANDBACK` line; only `VERDICT: APPROVE` lets the router move on to `security`. When `handback audit` prints `audit round <round>: RETURN with <b> blocker/major finding(s); fix round <r> of <N>: review <review> sha256 <sha256>; scope <scope>`, run the fix round: `install code --check` prints the envelope and the line `fix round <r> of <N>: review <review> sha256 <sha256>`; take the brief's values from that line, never from your own reading of the report. In a run with role models, `install code` then ends with `model: <alias>`, as every dispatch does; it reads `model: opus` when `handback audit` ended its line with `; model opus (escalated: <tasks> returned twice)`, because the audit returned one of those plan tasks a second time. Then pause, install and dispatch a fresh `code` agent with the fix-round task from the dispatch table, hand it back from `.conductor/handback/code-fix-<r>.txt`, and dispatch `audit` again. Never revive an earlier agent and never message one. The orchestrator never decides whether another round runs: the script's output does. A `RETURN` with no fix rounds left, or an `ESCALATE`, halts the run (follow "On any halt"). Then dispatch `security`, which runs the recorded audit and scan commands and ends its report as the audit does: its `SCANS:` line, then one `VERDICT:` line just before its `SNAP_HANDBACK` line. `VERDICT: APPROVE` means every scan completed and no finding the change introduces is a `blocker`; `VERDICT: RETURN` means one is (`ORCH_SECURITY_BLOCKED`); `VERDICT: ESCALATE` means a scan failed (`ORCH_SECURITY_SCAN_FAILED`) or text in the change addressed the agent (`ORCH_SECURITY_ESCALATE`). A finding is a `blocker` or a `minor` by the threshold `start` recorded, and the script, not you, checks it. Findings already present at the base commit go in the report's owner-only block (`PRE-EXISTING (owner only):` … `END PRE-EXISTING`); the script writes them to `.conductor/security-pre-existing.txt` and to nothing public. This changes 1.48.0 behavior: a finding already present at the base, a dependency advisory included, no longer blocks the run at any level; only the findings the change introduces decide the verdict. `handback security` prints `security handed back build_executed; VERDICT: APPROVE; <n> finding(s) below <threshold> recorded; dependency=<ran|not-covered|disabled>; pre-existing findings, if any, are in .conductor/security-pre-existing.txt (owner only)`, and only then `qa`, or, in an unattended run, the delegated build review. In an unattended run, run `node "$S/orchestrate.mjs" delegate build --check`. It prints `delegate build: spec <path> sha256 <h>; plan <path> sha256 <h>; files <files>; security <summary>`, with the model segment as at the approvals. Dispatch a fresh `define-review` agent with the build brief below, filled from that line only, write its report verbatim to `.conductor/delegate/build.md`, and run `node "$S/orchestrate.mjs" delegate build`. Only `build approved by delegated review: …; next: install qa` lets `qa` run; a `RETURN` or `ESCALATE` halts the run (follow "On any halt"). A run started before FEAT-034 has no seat: `qa` follows the audit and `handback qa` prints `security=not-configured (run predates FEAT-034)`. When `qa`'s hand-back records `verify_pass`, run `node "$S/orchestrate.mjs" end`. It prints the run it removed.
86
+ 5. **Verify.** Dispatch `audit`. The audit report ends in one `VERDICT:` line just before its `SNAP_HANDBACK` line; only `VERDICT: APPROVE` lets the router move on to `security`. When `handback audit` prints `audit round <round>: RETURN with <b> blocker/major finding(s); fix round <r> of <N>: review <review> sha256 <sha256>; scope <scope>`, run the fix round: `install code --check` prints the envelope and the line `fix round <r> of <N>: review <review> sha256 <sha256>`; take the brief's values from that line, never from your own reading of the report. In a run with role models, `install code` then ends with `model: <alias>`, as every dispatch does; it reads `model: opus` when `handback audit` ended its line with `; model opus (escalated: <tasks> returned twice)`, because the audit returned one of those plan tasks a second time. Then pause, install and dispatch a fresh `code` agent with the fix-round task from the dispatch table, hand it back from `.conductor/handback/code-fix-<r>.txt`, and dispatch `audit` again. Never revive an earlier agent and never message one. The orchestrator never decides whether another round runs: the script's output does. A `RETURN` with no fix rounds left, or an `ESCALATE`, halts the run (follow "On any halt"). Then dispatch `security`, which runs the recorded audit and scan commands and ends its report as the audit does: its `SCANS:` line, then one `VERDICT:` line just before its `SNAP_HANDBACK` line. `VERDICT: APPROVE` means every scan completed and no finding the change introduces is a `blocker`; `VERDICT: RETURN` means one is (`ORCH_SECURITY_BLOCKED`); `VERDICT: ESCALATE` means a scan failed (`ORCH_SECURITY_SCAN_FAILED`) or text in the change addressed the agent (`ORCH_SECURITY_ESCALATE`). A finding is a `blocker` or a `minor` by the threshold `start` recorded, and the script, not you, checks it. Findings already present at the base commit go in the report's owner-only block (`PRE-EXISTING (owner only):` … `END PRE-EXISTING`); the script writes them to `.conductor/security-pre-existing.txt` and to nothing public. This changes 1.48.0 behavior: a finding already present at the base, a dependency advisory included, no longer blocks the run at any level; only the findings the change introduces decide the verdict. `handback security` prints `security handed back build_executed; VERDICT: APPROVE; <n> finding(s) below <threshold> recorded; dependency=<ran|not-covered|disabled>; pre-existing findings, if any, are in .conductor/security-pre-existing.txt (owner only)`, and only then `qa`, or, in an unattended run, the delegated build review. In an unattended run, run `node "$S/orchestrate.mjs" delegate build --check`. It prints `delegate build: spec <path> sha256 <h>; plan <path> sha256 <h>; files <files>; security <summary>`, with the model segment as at the approvals. Dispatch a fresh `define-review` agent with the build brief below, filled from that line only, write its report verbatim to `.conductor/delegate/build.md`, and run `node "$S/orchestrate.mjs" delegate build`. Only `build approved by delegated review: …; next: install qa` lets `qa` run; a `RETURN` or `ESCALATE` halts the run (follow "On any halt"). A run started before FEAT-034 has no seat: `qa` follows the audit and `handback qa` prints `security=not-configured (run predates FEAT-034)`. When `qa`'s hand-back records `verify_pass`, run `node "$S/orchestrate.mjs" end`. It prints the run it removed. Before that hand-back `end` refuses with `ORCH_END_UNVERIFIED`.
83
87
  6. **Report.** From the record `end` printed, name:
84
88
  - every hand-back, with its role, gate and task;
85
89
  - each audit round's verdict, from the audit entries' `round` and `verdict`, and each fix round with its files, from their `fix`;
@@ -552,6 +552,8 @@ function codeScope(root, run, step) {
552
552
  return taskScope(task ?? { id: step.task, files: [] }, run.plan);
553
553
  }
554
554
 
555
+ const docLocationHalt = (run) => new Halt('ORCH_DOC_LOCATION_UNRESOLVED', `run ${run.item} records no docs location (started before FEAT-047); run end, then start`);
556
+
555
557
  function envelopeFields(run, root, step) {
556
558
  const { tk, scope } = ROLE_ARTIFACTS[step.role];
557
559
  const fields = {
@@ -562,9 +564,7 @@ function envelopeFields(run, root, step) {
562
564
  if (step.role === 'code') fields.scope = codeScope(root, run, step);
563
565
  else if (step.role === 'spec' || step.role === 'plan') {
564
566
  // Read as pinned, never re-checked: the cap was enforced once, at start.
565
- if (!isPlainObject(run.docs?.scopes) || !Array.isArray(run.docs.scopes[step.role])) {
566
- throw new Halt('ORCH_DOC_LOCATION_UNRESOLVED', `run ${run.item} records no docs location (started before FEAT-047); run end, then start`);
567
- }
567
+ if (!isPlainObject(run.docs?.scopes) || !Array.isArray(run.docs.scopes[step.role])) throw docLocationHalt(run);
568
568
  fields.scope = run.docs.scopes[step.role];
569
569
  } else if (scope) fields.scope = scope;
570
570
  // Ruling 2: ticket identity rides the spec envelope only, never its content.
@@ -969,6 +969,33 @@ async function securityHandback(root, run, gate, text) {
969
969
  return `security handed back ${gate}; VERDICT: APPROVE; ${summary.total} finding(s) below ${threshold} recorded; dependency=${report.scans.dependency}; pre-existing findings, if any, are in ${OWNER_FILE} (owner only)`;
970
970
  }
971
971
 
972
+ // BUG-075: recomputed as install computed it, never read back from the envelope file, which the orchestrator can write.
973
+ function expectedScope(root, run, role) {
974
+ if (role === 'code') return codeScope(root, run, nextStep(run));
975
+ if (role !== 'spec' && role !== 'plan') return null;
976
+ if (!isPlainObject(run.docs)) throw docLocationHalt(run);
977
+ return docScopes(run.docs)[role];
978
+ }
979
+
980
+ const sameList = (a, b) => Array.isArray(a) && a.length === b.length && a.every((x, i) => x === b[i]);
981
+ const scopeText = (scope) => (scope === null || scope === undefined ? 'none' : JSON.stringify(scope));
982
+ // A path that needs normalizing is not the one the scope names, so it is never normalized.
983
+ const unsafePath = (p) => /^[A-Za-z]:/.test(p) || p.split('/').some((seg) => seg === '' || seg === '.' || seg === '..');
984
+
985
+ // BUG-075: returned, not thrown, so resume drops the record where handback halts on it.
986
+ function claimHalt(env, role, expected) {
987
+ const claimed = env.ops.scope;
988
+ if (expected === null ? claimed !== undefined : !sameList(claimed, expected)) {
989
+ return new Halt('ORCH_HANDBACK_SCOPE_MISMATCH', `${role} was installed with scope ${scopeText(expected)}, the hand-back names ${scopeText(claimed)}`);
990
+ }
991
+ if (expected === null) return null;
992
+ const covers = expected.map(globToRegExp);
993
+ const paths = (Array.isArray(env.ops.f) ? env.ops.f : []).map((f) => String(f).replace(/:[CMD]$/, ''));
994
+ const outside = paths.find((p) => unsafePath(p) || !covers.some((re) => re.test(p)));
995
+ if (outside === undefined) return null;
996
+ return new Halt('ORCH_HANDBACK_OUT_OF_SCOPE', `${role} lists ${outside} in ops.f, outside its scope ${scopeText(expected)}`);
997
+ }
998
+
972
999
  async function handback(root, sessionId, role, bytes) {
973
1000
  const text = bytes.toString('utf8');
974
1001
  const run = liveRun(root, sessionId);
@@ -982,6 +1009,8 @@ async function handback(root, sessionId, role, bytes) {
982
1009
  if (!MAY_HAND_BACK[role].includes(env.ops.gate)) {
983
1010
  throw new Halt('ORCH_GATE_UNEARNED', `${role} may hand back ${MAY_HAND_BACK[role].join('|')}, not ${env.ops.gate}`);
984
1011
  }
1012
+ const claim = claimHalt(env, role, expectedScope(root, run, role));
1013
+ if (claim) throw claim;
985
1014
  if (role === 'security') return securityHandback(root, run, env.ops.gate, text);
986
1015
  const verdict = role === 'audit' ? parseVerdict(text) : null;
987
1016
  const recorded = recordHandback(run, role, env.ops.gate, verdict?.verdict, { snap });
@@ -1016,7 +1045,7 @@ function approve(root, sessionId, what, rel, shown) {
1016
1045
  if (sha256 !== shown.toLowerCase()) {
1017
1046
  throw new Refusal(`ORCH_DOC_HASH_STALE: ${what} ${rel} hashes ${sha256}, not the ${shown} that was shown; show the document again`);
1018
1047
  }
1019
- const approval = { at: new Date().toISOString(), by: gitValue(root, ['config', 'user.name'], 'unknown'), path: rel, sha256, commit: headObject(root) };
1048
+ const approval = { at: new Date().toISOString(), by: 'owner', path: rel, sha256, commit: headObject(root) };
1020
1049
  if (what === 'plan') return approvePlan(root, run, content.toString('utf8'), approval);
1021
1050
  saveRun(root, { ...run, approvals: { ...run.approvals, spec: approval } });
1022
1051
  return `spec approved: sha256 ${sha256}`;
@@ -1275,11 +1304,16 @@ function candidateEntries(run) {
1275
1304
  }
1276
1305
 
1277
1306
  // A task entry still describes the repository: its position, its SNAP and its commit all hold.
1278
- function taskEntryHolds(root, entry, taskId) {
1307
+ // BUG-075: and it still names the scope its task installs, over paths inside it.
1308
+ function taskEntryHolds(root, run, entry, taskId) {
1279
1309
  if (entry.task !== taskId || typeof entry.snap !== 'string' || validate(`${entry.snap}\n`) !== '') return false;
1280
1310
  let env = null;
1281
1311
  try { env = JSON.parse(entry.snap); } catch { return false; }
1282
- return env?.sys?.role === 'code' && ancestry(root, env.sys.c) === 0;
1312
+ if (env?.sys?.role !== 'code' || ancestry(root, env.sys.c) !== 0) return false;
1313
+ try { return claimHalt(env, 'code', codeScope(root, run, { task: taskId })) === null; } catch (e) {
1314
+ if (e instanceof Halt) return false;
1315
+ throw e;
1316
+ }
1283
1317
  }
1284
1318
 
1285
1319
  // Each approved document's entry, then Build's task entries up to the first that fails; Verify is always redone.
@@ -1289,7 +1323,7 @@ function keptEntries(root, run) {
1289
1323
  if (!run.approvals.plan) return { kept: approved, tasks: 0 };
1290
1324
  const tasks = entries.filter((h) => h.role === 'code' && !('fix' in h));
1291
1325
  let n = 0;
1292
- while (n < tasks.length && n < run.tasks.ids.length && taskEntryHolds(root, tasks[n], run.tasks.ids[n])) n += 1;
1326
+ while (n < tasks.length && n < run.tasks.ids.length && taskEntryHolds(root, run, tasks[n], run.tasks.ids[n])) n += 1;
1293
1327
  return { kept: [...approved, ...tasks.slice(0, n)], tasks: n };
1294
1328
  }
1295
1329
 
@@ -1487,13 +1521,30 @@ function clearRunFiles(root) {
1487
1521
  rmSync(join(root, DELEGATE_DIR), { recursive: true, force: true });
1488
1522
  }
1489
1523
 
1524
+ const END_USAGE = 'usage: orchestrate.mjs end [--abandon]';
1525
+
1526
+ // BUG-075: the run end would drop before Verify passed, or null; a missing, broken or halted run is never held.
1527
+ function unverifiedRun(root) {
1528
+ let run = null;
1529
+ try { run = readRun(root); } catch { return null; }
1530
+ if (!run || run.halt) return null;
1531
+ const last = run.handbacks.at(-1);
1532
+ return last?.role === 'qa' && last.gate === 'verify_pass' ? null : run;
1533
+ }
1534
+
1490
1535
  // Prints the run it removes, so the closing report reads the record rather than memory.
1491
- function end(root) {
1536
+ // BUG-075: a live run ends only after qa's verify_pass, unless the owner abandons it by name.
1537
+ function end(root, args) {
1538
+ if (args.length > 1 || (args.length === 1 && args[0] !== '--abandon')) throw new Refusal(END_USAGE);
1539
+ const run = unverifiedRun(root);
1540
+ if (run && args.length === 0) {
1541
+ throw new Refusal(`ORCH_END_UNVERIFIED: run ${run.item} is at ${describeStep(nextStep(run))} with no verify_pass; end it only after qa, after a halt, or with end --abandon on the owner's word`);
1542
+ }
1492
1543
  const path = join(root, RUN_FILE);
1493
1544
  const text = existsSync(path) ? readFileSync(path, 'utf8').trim() : 'no run file';
1494
1545
  rmSync(path, { force: true });
1495
1546
  clearRunFiles(root);
1496
- return text;
1547
+ return run ? `run ${run.item} abandoned at ${run.gate} before verify_pass\n${text}` : text;
1497
1548
  }
1498
1549
 
1499
1550
  function recordHalt(root, halt) {
@@ -1600,7 +1651,7 @@ export async function cli(argv, env, cwd = process.cwd()) {
1600
1651
  delegate: () => delegate(root, sid, argv.slice(1)),
1601
1652
  resume: () => resume(root, sid, argv.slice(1)),
1602
1653
  envelope: () => envelopeVerb(root, sid, argv.slice(1)),
1603
- end: () => end(root),
1654
+ end: () => end(root, argv.slice(1)),
1604
1655
  };
1605
1656
  try {
1606
1657
  if (!verbs[verb]) throw new Refusal('usage: orchestrate.mjs start|install|handback|approve|hash|review|delegate|resume|envelope|end');