@yeison.restrepo.r/code-conductor 1.34.3 → 1.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,9 +12,11 @@
12
12
 
13
13
  Three commands, from nothing to a guarded session. The output below is **real**, captured by running exactly these commands in a scratch directory.
14
14
 
15
+ **Minimum safe version: `1.34.4`.** Older versions can strip or damage an existing `CLAUDE.md`: every release before `1.24` overwrote it with no backup, `1.24` through `1.34.3` silently removed your sections whose headings matched the managed block's, and an older pre-sentinel version left at least one field file with damaged lines. Install with `@latest`, as below.
16
+
15
17
  ```bash
16
18
  mkdir demo && cd demo && git init -q && npm init -y >/dev/null
17
- npx @yeison.restrepo.r/code-conductor --project
19
+ npx @yeison.restrepo.r/code-conductor@latest --project
18
20
  ```
19
21
 
20
22
  The installer prints **nothing** and exits 0. That silence is deliberate and is asserted by a test: the stub-detection check runs *before* the seed, so a fresh scaffold cannot warn about the file it was just given (`tests/installer/deploy.test.js`, "says nothing on a fresh scaffold, whose stub it just wrote").
@@ -98,6 +100,10 @@ Four checks live in `tools/` as tracked repository infrastructure. Three of them
98
100
 
99
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.
100
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.
101
107
  - **The `P7` false positive above**, still live.
102
108
  - **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.
103
109
  - **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.
@@ -135,8 +141,10 @@ AI coding assistants are only as good as the structure you put around them. With
135
141
 
136
142
  ## Install
137
143
 
144
+ **Minimum safe version: `1.34.4`.** Older versions can strip or damage an existing `CLAUDE.md`: every release before `1.24` overwrote it with no backup, `1.24` through `1.34.3` silently removed your sections whose headings matched the managed block's, and an older pre-sentinel version left at least one field file with damaged lines. Install with `@latest`, as below.
145
+
138
146
  ```bash
139
- npx @yeison.restrepo.r/code-conductor # one-shot global setup
147
+ npx @yeison.restrepo.r/code-conductor@latest # one-shot global setup
140
148
  # or
141
149
  npm install -g @yeison.restrepo.r/code-conductor && code-conductor
142
150
  ```
@@ -282,6 +290,8 @@ Hit a block you believe is wrong? Re-run the command with `CC_GUARD3_WARN=1` and
282
290
 
283
291
  **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.
284
292
 
293
+ **Band scope guard (Guard 5)** - a `Write`, `Edit`, `create_file` or `write_file` from a subagent whose `agent_type` names a band role (`spec`, `plan`, `code`, `audit`, `qa`) is checked against the nearest `.claude/memory/band-envelope.json` above its working directory, a SNAP v3 envelope. A malformed envelope, an agent that is not the envelope's role, a role not holding `RW`, or a path outside the envelope's `scope` globs (anchored at the band root, the directory whose `.claude/` holds the envelope) is denied with a named reason. The main session, any other agent, and any project without an envelope are untouched. It assumes cooperative agents: `agent_type` is a name taken on trust, and `Bash`, `NotebookEdit`, MCP write tools and symlinked paths are not covered.
294
+
285
295
  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.
286
296
 
287
297
  ### context-guard *(global + project)* — v1.15.0
@@ -421,15 +431,24 @@ code-conductor/
421
431
 
422
432
  ## .gitignore Note
423
433
 
424
- When installed with `--project`, the installer appends these rules to your project's
425
- `.gitignore`, and only the ones you are missing — your own entries are never touched:
434
+ When installed with `--project`, the installer keeps its rules in one labelled block in
435
+ your project's `.gitignore`:
426
436
 
427
437
  ```
438
+ # Code Conductor (added by the installer; safe to keep)
428
439
  .claude/memory/turn-count.txt
429
440
  *.installer-backup.*
430
441
  *.installer-tmp.*
431
442
  ```
432
443
 
444
+ The block ends at the first blank line. Your own lines are never edited. A line that is
445
+ exactly one of these three rules (earlier versions appended them one at a time) is moved
446
+ into the block, so each rule appears once; a line you changed, such as
447
+ `/.claude/memory/turn-count.txt`, is not an exact match and stays where it is. If your
448
+ `.gitignore` has any `!` line, nothing is moved, because moving a rule past a `!` can
449
+ change what is ignored: the block then holds only the rules you lack, and the installer
450
+ says so. A change to `.gitignore` is backed up and reported exactly as for `CLAUDE.md`.
451
+
433
452
  The last two keep the installer's own backups and crash-stranded temp files out of
434
453
  `git status`. The rules ship inside the package as `project-template/gitignore`
435
454
  (no leading dot) because npm strips any file literally named `.gitignore` from every
@@ -442,28 +461,34 @@ published tarball; the installer restores the dot when it writes to your project
442
461
  `CLAUDE.md` and `.gitignore` are **merged**, never overwritten. Everything else the
443
462
  installer ships (`settings.json`, hooks, commands, `scripts/`) is replaced on every run.
444
463
 
445
- - **Managed sections** live between `<!-- cc:managed:start -->` and `<!-- cc:managed:end -->`.
446
- Code Conductor owns that block and replaces its contents wholesale on every upgrade, so
447
- released improvements reach existing installs. Edits inside the block are lost.
448
- - **Everything outside the block is yours.** Existing sections are preserved byte-for-byte;
449
- sections the template has and your file lacks are appended once, immediately above the
450
- managed block. Sections you wrote that the template has never heard of are never touched.
464
+ - **Code Conductor owns one block and nothing else.** Its content lives between
465
+ `<!-- cc:managed:start -->` and `<!-- cc:managed:end -->`, and those two markers alone
466
+ decide ownership; a heading's name never does. Every upgrade replaces the block's
467
+ contents wholesale, so released improvements reach existing installs. Edits inside the
468
+ block are lost, and recoverable from the backup.
469
+ - **Everything outside the block is yours, byte for byte.** Nothing outside it is
470
+ removed, rewritten, reordered or added.
471
+ - **A file without the markers gets the block appended at the end**, after one blank
472
+ line and in your file's line endings, and nothing else changes. If your file already
473
+ has sections named like the block's (`## Agent Identity`, `## Hard Constraints`, …),
474
+ you will see both: yours above, Code Conductor's inside the block. That is deliberate.
475
+ The installer never decides which of your sections are really its own; reconciling
476
+ them is planned for `/cc-stack` as `[FEAT-040]`.
451
477
  - **Before any change, the installer copies your file to
452
- `CLAUDE.md.installer-backup.<UTC timestamp>`** and keeps the five most recent.
453
-
454
- > **One-time migration on your first 1.24 install.** If your `CLAUDE.md` predates the
455
- > sentinel markers and already contains sections that the managed block also defines
456
- > (`## Agent Identity`, `## Hard Constraints`, …), **those sections are removed** and
457
- > replaced by the managed block, so you do not end up with two copies of each. This is the
458
- > only path that discards content you wrote. **Your pre-migration file is preserved in the
459
- > `.installer-backup.` copy beside it** — diff it after upgrading and move anything you
460
- > want to keep into a section outside the managed block.
461
-
462
- > **A cosmetic wart of that same migration, in `~/.claude/CLAUDE.md` only.** The managed
463
- > block carries the file's intro sentence ("Applies to every project on this machine…"),
464
- > and your pre-sentinel copy keeps its own above the block, so you will see that one
465
- > sentence twice after the first upgrade. Delete the copy above the block — it is outside
466
- > the managed region, so your deletion sticks.
478
+ `CLAUDE.md.installer-backup.<UTC timestamp>`**, keeps the five most recent, and prints
479
+ where it put it:
480
+
481
+ ```
482
+ code-conductor: backed up CLAUDE.md to CLAUDE.md.installer-backup.20260930T120000Z before merging (git-ignored by design)
483
+ ```
484
+
485
+ Backups are git-ignored so nobody commits one by accident and they stay out of every
486
+ teammate's `git status`; the printed line is how you find yours. A fresh install, and a
487
+ re-run that changes nothing, print nothing.
488
+
489
+ The same rules apply to `~/.claude/CLAUDE.md`, whose backup line names the `~/.claude/`
490
+ path. If your file ends inside a code fence that is never closed, the installer leaves it
491
+ untouched with a warning, because a block appended there would be hidden inside the fence.
467
492
 
468
493
  If the markers in your file are damaged — a `start` with no `end`, two blocks, an `end`
469
494
  before its `start` — the installer prints a warning, leaves the file completely untouched,
@@ -91,7 +91,7 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log } = {})
91
91
  assertAssets(assetRoot, ['global', 'skills', 'scripts', 'project-template']); // pre-flight
92
92
  assertMergeTargets(home, cwd, opts.project); // pre-flight
93
93
  writing = true; // copy phase begins
94
- const claudeDir = deployGlobal(assetRoot, home);
94
+ const claudeDir = deployGlobal(assetRoot, home, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m) });
95
95
  chmodHooks(claudeDir);
96
96
  const v = writeVerbosity(home, assetRoot, opts.verbosity, opts.verbosityGiven);
97
97
  if (v.warn) emit('stderr', v.warn);
@@ -101,7 +101,7 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log } = {})
101
101
  if (heal.status === 'removed') emit('stdout', 'code-conductor: removed the retired graphify-ast-refresh hook from settings.json (backup written beside it)');
102
102
  for (const line of heal.lines) emit('stderr', `code-conductor: ${line}`);
103
103
  writeVersionFile(home, pkgVersion(assetRoot));
104
- if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m) });
104
+ if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m) });
105
105
  return 0;
106
106
  } catch (err) {
107
107
  // Pre-flight failures (nothing written yet) → exit 1.
@@ -1,7 +1,7 @@
1
1
  import { cpSync, mkdirSync, chmodSync, existsSync, lstatSync, readdirSync, readFileSync, statSync, rmSync, unlinkSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { join, relative, isAbsolute, sep } from 'node:path';
3
3
  import { mergeFileInto, resolveRealTarget } from './file-merge.mjs';
4
- import { mergeClaudeMdText, appendMissingLinesText } from './merge-md.mjs';
4
+ import { mergeClaudeMdText, mergeGitignoreText } from './merge-md.mjs';
5
5
  import { GLOBAL_HOST_OWNED, PROJECT_HOST_OWNED, GLOBAL_SETTINGS_FINGERPRINTS, PROJECT_SETTINGS_FINGERPRINTS, hostOwnedFilter, seedHostOwned } from './host-owned.mjs';
6
6
  import { mergeSettingsFile } from './settings-merge.mjs';
7
7
 
@@ -14,7 +14,7 @@ import { mergeSettingsFile } from './settings-merge.mjs';
14
14
  // target name instead would let cpSync drop a stray `gitignore` at the project root.
15
15
  const MERGED_ROOT_FILES = new Map([
16
16
  ['CLAUDE.md', { target: 'CLAUDE.md', merge: mergeClaudeMdText }],
17
- ['gitignore', { target: '.gitignore', merge: appendMissingLinesText }],
17
+ ['gitignore', { target: '.gitignore', merge: mergeGitignoreText }],
18
18
  ]);
19
19
 
20
20
  // Verified at plan time: `find global skills project-template -type l` returns
@@ -24,6 +24,22 @@ const MERGED_ROOT_FILES = new Map([
24
24
  // later is copied as a link (never followed into user content), not resolved.
25
25
  const CP_OPTS = { recursive: true, force: true, dereference: false };
26
26
 
27
+ // One stdout line per backup, because the backup is git-ignored by the managed
28
+ // block and would otherwise be invisible (BUG-049). A backup outside `root` (a
29
+ // symlinked target resolved into a dotfiles checkout) prints absolute, and only a
30
+ // backup inside a --project root claims the ignore rule covers it.
31
+ function backupReporter(report, { root, rootLabel, file, ignoredByDesign }) {
32
+ return (backupPath) => {
33
+ const rel = relative(root, backupPath);
34
+ const inside = rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
35
+ const shown = inside ? rootLabel + rel.split(sep).join('/') : backupPath;
36
+ const suffix = inside && ignoredByDesign ? ' (git-ignored by design)' : '';
37
+ report(`code-conductor: backed up ${rootLabel}${file} to ${shown} before merging${suffix}`);
38
+ };
39
+ }
40
+ const toStdout = (m) => process.stdout.write(`${m}\n`);
41
+ const toStderr = (m) => process.stderr.write(`${m}\n`);
42
+
27
43
  // Pure guard: throws ONLY, emits nothing. It does not write a stderr diagnostic
28
44
  // before throwing — run() surfaces the error's message exactly once
29
45
  // (`code-conductor: missing bundled asset dir: <path>`), so warning here too would
@@ -92,12 +108,15 @@ export function assertMergeTargets(home, cwd, project) {
92
108
  }
93
109
  }
94
110
 
95
- export function deployGlobal(assetRoot, home) {
111
+ export function deployGlobal(assetRoot, home, { warn = toStderr, report = toStdout } = {}) {
96
112
  const target = join(home, '.claude');
97
113
  const globalDir = join(assetRoot, 'global');
98
114
  mkdirSync(target, { recursive: true });
99
115
  cpSync(globalDir, target, { ...CP_OPTS, filter: hostOwnedFilter(globalDir, GLOBAL_HOST_OWNED) });
100
- mergeFileInto(join(globalDir, 'CLAUDE.md'), join(target, 'CLAUDE.md'), mergeClaudeMdText);
116
+ mergeFileInto(join(globalDir, 'CLAUDE.md'), join(target, 'CLAUDE.md'), mergeClaudeMdText, {
117
+ warn,
118
+ onBackup: backupReporter(report, { root: target, rootLabel: '~/.claude/', file: 'CLAUDE.md', ignoredByDesign: false }),
119
+ });
101
120
  const skillsDir = join(target, 'skills');
102
121
  unblockSkillPaths(assetRoot, skillsDir);
103
122
  cpSync(join(assetRoot, 'skills'), skillsDir, CP_OPTS);
@@ -149,8 +168,8 @@ function warnIfProjectMemoryIsStub(templateClaude, target, emit) {
149
168
  return true;
150
169
  }
151
170
 
152
- export function deployProject(assetRoot, cwd, { warn } = {}) {
153
- const emit = warn || ((m) => process.stderr.write(`${m}\n`));
171
+ export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdout } = {}) {
172
+ const emit = warn;
154
173
  const target = join(cwd, '.claude');
155
174
  const templateRoot = join(assetRoot, 'project-template');
156
175
  // If something already occupies ./.claude and it is NOT a directory, this is a
@@ -172,7 +191,10 @@ export function deployProject(assetRoot, cwd, { warn } = {}) {
172
191
  cpSync(join(templateRoot, name), join(cwd, name), CP_OPTS);
173
192
  }
174
193
  for (const [source, { target: dest, merge }] of MERGED_ROOT_FILES) {
175
- mergeFileInto(join(templateRoot, source), join(cwd, dest), merge);
194
+ mergeFileInto(join(templateRoot, source), join(cwd, dest), merge, {
195
+ warn: emit,
196
+ onBackup: backupReporter(report, { root: cwd, rootLabel: '', file: dest, ignoredByDesign: true }),
197
+ });
176
198
  }
177
199
  // BEFORE the seed on purpose: running it after would make every fresh
178
200
  // scaffold warn about the stub it was just given.
@@ -6,6 +6,10 @@ import { utcStamp, pruneBackups } from './settings.mjs';
6
6
 
7
7
  const BACKUP_SUFFIX = '.installer-backup.';
8
8
  const MAX_BACKUPS = 5;
9
+ // Advice per warning code; the default fits every sentinel-count warning.
10
+ const WARNING_ADVICE = {
11
+ CLAUDE_MD_UNCLOSED_FENCE: 'close the code fence that runs to the end of the file and re-run',
12
+ };
9
13
 
10
14
  // Symlinked CLAUDE.md into a dotfiles repo is a legitimate setup, so the writer
11
15
  // works on the RESOLVED path: renameSync over the link itself would replace it
@@ -27,7 +31,9 @@ export function backupFile(realPath, now = new Date()) {
27
31
  let dst = base;
28
32
  for (let i = 1; existsSync(dst); i++) dst = `${base}-${i}`;
29
33
  copyFileSync(realPath, dst);
30
- pruneBackups(realPath, BACKUP_SUFFIX, MAX_BACKUPS);
34
+ // Retention is best effort: once the copy exists, a failed prune must not make the
35
+ // caller report "could not back it up" for a backup that is sitting on disk.
36
+ try { pruneBackups(realPath, BACKUP_SUFFIX, MAX_BACKUPS); } catch { /* best effort */ }
31
37
  return dst;
32
38
  }
33
39
 
@@ -44,7 +50,7 @@ export function writeAtomic(realPath, text) {
44
50
  }
45
51
  }
46
52
 
47
- export function mergeFileInto(templatePath, targetPath, mergeFn, { now = new Date(), warn } = {}) {
53
+ export function mergeFileInto(templatePath, targetPath, mergeFn, { now = new Date(), warn, onBackup } = {}) {
48
54
  const emit = warn || ((m) => process.stderr.write(`${m}\n`));
49
55
  const target = resolveRealTarget(targetPath);
50
56
  if (target.isDir) {
@@ -73,15 +79,32 @@ export function mergeFileInto(templatePath, targetPath, mergeFn, { now = new Dat
73
79
  return 'created';
74
80
  }
75
81
  const hostText = readFileSync(target.realPath, 'utf8');
76
- const { text, changed, warning } = mergeFn(templateText, hostText);
82
+ const { text, changed, warning, notice } = mergeFn(templateText, hostText);
77
83
  if (warning) {
78
- emit(`code-conductor: skipping ${targetPath} — ${warning}; fix the cc:managed markers and re-run`);
84
+ emit(`code-conductor: skipping ${targetPath} — ${warning}; ${WARNING_ADVICE[warning] || 'fix the cc:managed markers and re-run'}`);
79
85
  return 'skipped-warning';
80
86
  }
81
87
  if (!changed) return 'unchanged';
82
- // Backup BEFORE the rewrite and let a backup/prune failure propagate: an
83
- // unrecoverable overwrite is worse than a failed install.
84
- if (hostText.trim() !== '') backupFile(target.realPath, now);
85
- writeAtomic(target.realPath, text);
88
+ const status = backupThenWrite(target.realPath, targetPath, text, hostText.trim() !== '', { now, emit, onBackup });
89
+ if (status === 'merged' && notice) emit(`code-conductor: ${notice}`);
90
+ return status;
91
+ }
92
+
93
+ // Backup first, and a failed backup stops the write: an unrecoverable overwrite is
94
+ // worse than a skipped file. The path is reported the moment the copy exists, so the
95
+ // person running the installer learns where it is even if the write then fails.
96
+ function backupThenWrite(realPath, targetPath, text, needsBackup, { now, emit, onBackup }) {
97
+ let backup = null;
98
+ if (needsBackup) {
99
+ try { backup = backupFile(realPath, now); } catch (err) {
100
+ emit(`code-conductor: skipping ${targetPath} — could not back it up (${err.code || err.message}); nothing was written`);
101
+ return 'skipped-backup-failed';
102
+ }
103
+ if (onBackup) onBackup(backup);
104
+ }
105
+ try { writeAtomic(realPath, text); } catch (err) {
106
+ emit(`code-conductor: could not write ${targetPath} (${err.code || err.message}); it is unchanged${backup ? `, and its backup is ${backup}` : ''}`);
107
+ return 'write-failed';
108
+ }
86
109
  return 'merged';
87
110
  }
@@ -40,6 +40,7 @@ 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'],
43
44
  ['settings.json', 'merge'],
44
45
  ['settings.local.json', 'skip'],
45
46
  ]);
@@ -5,6 +5,10 @@
5
5
 
6
6
  export const SENTINEL_START = '<!-- cc:managed:start -->';
7
7
  export const SENTINEL_END = '<!-- cc:managed:end -->';
8
+ // Opens the installer's labelled block in a host .gitignore. The shipped template
9
+ // starts with it (templates.test.js) and the merge finds the block by it.
10
+ export const GITIGNORE_HEADER = '# Code Conductor (added by the installer; safe to keep)';
11
+ const NEGATION_NOTICE = 'left the existing Code Conductor entries in .gitignore where they are, because the file has a "!" line and moving them could change what it ignores';
8
12
 
9
13
  const toLf = (t) => t.replace(/\r\n/g, '\n');
10
14
 
@@ -28,25 +32,27 @@ export function normalizeHeading(line) {
28
32
  .toLowerCase();
29
33
  }
30
34
 
31
- // One fence-aware pass over LF-normalized text. Returns line INDICES only, so
32
- // callers slice `lines` themselves and no substring arithmetic is needed.
33
- // A fence opens on ``` or ~~~ at column 0 (info string allowed) and closes on a
34
- // bare run of the SAME marker char. An unclosed fence runs to EOF, so everything
35
- // after it is body text — never a heading, never a sentinel.
36
- export function scanLines(lfText) {
37
- const lines = lfText.split('\n');
35
+ // One fence-aware pass. Takes raw text: each element of `lines` keeps its own CR,
36
+ // so a caller that splices `lines` and rejoins on '\n' reproduces every untouched
37
+ // byte. Returns line INDICES only. Fences follow CommonMark: one opens on ``` or ~~~
38
+ // indented up to three spaces (info string allowed), and closes only on a bare run of
39
+ // the SAME char at least as long as the opener, so a ```` block can quote ``` ones.
40
+ // An unclosed fence runs to EOF, so everything after it is body text — never a
41
+ // heading, never a sentinel — and `openFence` says so.
42
+ export function scanLines(text) {
43
+ const lines = text.split('\n');
38
44
  const headings = [];
39
45
  const starts = [];
40
46
  const ends = [];
41
47
  let fence = null;
42
48
  for (let i = 0; i < lines.length; i++) {
43
49
  const line = lines[i].replace(/\r$/, '');
44
- const marker = line.match(/^(`{3,}|~{3,})/);
50
+ const marker = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
45
51
  if (fence) {
46
- if (marker && marker[1][0] === fence && /^(`{3,}|~{3,})\s*$/.test(line)) fence = null;
52
+ if (closesFence(marker, fence)) fence = null;
47
53
  continue;
48
54
  }
49
- if (marker) { fence = marker[1][0]; continue; }
55
+ if (marker) { fence = marker[1]; continue; }
50
56
  const trimmed = line.trim();
51
57
  if (trimmed === SENTINEL_START) { starts.push(i); continue; }
52
58
  if (trimmed === SENTINEL_END) { ends.push(i); continue; }
@@ -56,113 +62,112 @@ export function scanLines(lfText) {
56
62
  starts.length === 0 && ends.length === 0 ? 'none'
57
63
  : starts.length === 1 && ends.length === 1 && starts[0] < ends[0] ? 'balanced'
58
64
  : 'unbalanced';
59
- return { lines, headings, start: starts[0], end: ends[0], status };
65
+ return { lines, headings, start: starts[0], end: ends[0], status, openFence: fence !== null };
60
66
  }
61
67
 
62
- // A section runs from its `## ` line to the line before the next heading, or to
63
- // `limit` (the sentinel start, or EOF) — whichever comes first.
64
- function sectionRange(scan, n, limit) {
65
- const from = scan.headings[n].index;
66
- const next = scan.headings[n + 1];
67
- return [from, Math.min(next ? next.index : limit, limit)];
68
+ const closesFence = (marker, opener) =>
69
+ marker !== null && marker[1][0] === opener[0] && marker[1].length >= opener.length && marker[2].trim() === '';
70
+
71
+ const unchanged = (hostText, warning) => ({ text: hostText, changed: false, warning });
72
+
73
+ // The host's bytes, one blank separator line, then `added` in the host's EOL. A host
74
+ // with no final newline gets one first, so its last line never fuses with ours.
75
+ function appendLines(hostText, added, eol) {
76
+ if (hostText === '') return added.join(eol) + eol;
77
+ const separator = hostText.endsWith('\n') ? eol : eol + eol;
78
+ return hostText + separator + added.join(eol) + eol;
68
79
  }
69
80
 
70
- // Append `block` at EOF with exactly one blank separator line and exactly one
71
- // trailing newline, collapsing whatever trailing blank lines the host had.
72
- function appendBlock(lines, block) {
73
- const out = lines.slice();
74
- while (out.length && out[out.length - 1].trim() === '') out.pop();
75
- if (out.length) out.push('');
76
- out.push(...block);
77
- if (out[out.length - 1] !== '') out.push('');
78
- return out;
81
+ // Only the lines strictly between the sentinels are replaced. The sentinel lines and
82
+ // every byte outside them are the host's raw lines, rejoined exactly as they were split.
83
+ function refreshInterior(host, interior, eol) {
84
+ const current = host.lines.slice(host.start + 1, host.end).map((l) => l.replace(/\r$/, ''));
85
+ if (current.join('\n') === interior.join('\n')) return host.lines.join('\n');
86
+ const cr = eol === '\r\n' ? '\r' : '';
87
+ return [
88
+ ...host.lines.slice(0, host.start + 1),
89
+ ...interior.map((l) => l + cr),
90
+ ...host.lines.slice(host.end),
91
+ ].join('\n');
79
92
  }
80
93
 
94
+ // Ownership is the sentinels' alone (BUG-049). A heading's name decides nothing: a
95
+ // sentinel-less host keeps every byte and gets the block appended, and a balanced
96
+ // host has only its block interior refreshed.
81
97
  export function mergeClaudeMdText(templateText, hostText) {
82
98
  const tpl = scanLines(toLf(templateText));
83
99
  // Never mutate host content on the authority of a broken shipped template.
84
- if (tpl.status !== 'balanced') {
85
- return { text: hostText, changed: false, warning: 'TEMPLATE_SENTINEL_UNBALANCED' };
86
- }
100
+ if (tpl.status !== 'balanced') return unchanged(hostText, 'TEMPLATE_SENTINEL_UNBALANCED');
87
101
  if (hostText.trim() === '') {
88
102
  return { text: templateText, changed: templateText !== hostText, warning: null };
89
103
  }
90
- const host0 = scanLines(toLf(hostText));
104
+ const host = scanLines(hostText);
91
105
  // Guessing the intended block risks eating host content, so every malformed
92
- // count takes the same path: touch nothing at all, not even a section append.
93
- if (host0.status === 'unbalanced') {
94
- return { text: hostText, changed: false, warning: 'CLAUDE_MD_SENTINEL_UNBALANCED' };
95
- }
96
-
106
+ // count takes the same path: touch nothing at all.
107
+ if (host.status === 'unbalanced') return unchanged(hostText, 'CLAUDE_MD_SENTINEL_UNBALANCED');
108
+ // A block appended after an unclosed fence would sit inside it, invisible to the
109
+ // next run, which would append another. Writing nothing is the only idempotent move.
110
+ if (host.status === 'none' && host.openFence) return unchanged(hostText, 'CLAUDE_MD_UNCLOSED_FENCE');
97
111
  const eol = detectEol(hostText);
98
- const block = tpl.lines.slice(tpl.start, tpl.end + 1); // sentinels included
99
- const interior = tpl.lines.slice(tpl.start + 1, tpl.end); // sentinels excluded
100
- const managedKeys = new Set(
101
- tpl.headings.filter((h) => h.index > tpl.start && h.index < tpl.end).map((h) => h.key),
102
- );
103
-
104
- let lines = host0.lines.slice();
105
- if (host0.status === 'balanced') {
106
- // Both sides are already LF here, so this comparison is EOL-normalized by
107
- // construction — without that a CRLF host would "change" on every run.
108
- const current = lines.slice(host0.start + 1, host0.end);
109
- if (current.join('\n') !== interior.join('\n')) {
110
- lines.splice(host0.start + 1, host0.end - host0.start - 1, ...interior);
111
- }
112
- } else {
113
- // Migration — the ONE path that discards host content. Host sections whose
114
- // heading matches a managed heading are dropped so the appended block does
115
- // not duplicate them. The caller's backup file is the recovery.
116
- const drop = [];
117
- for (let n = 0; n < host0.headings.length; n++) {
118
- if (managedKeys.has(host0.headings[n].key)) drop.push(sectionRange(host0, n, lines.length));
119
- }
120
- for (const [from, to] of drop.reverse()) lines.splice(from, to - from);
121
- lines = appendBlock(lines, block);
122
- }
112
+ const text = host.status === 'balanced'
113
+ ? refreshInterior(host, tpl.lines.slice(tpl.start + 1, tpl.end), eol)
114
+ : appendLines(hostText, tpl.lines.slice(tpl.start, tpl.end + 1), eol);
115
+ return { text, changed: text !== hostText, warning: null };
116
+ }
123
117
 
124
- // Host-owned template sections the host lacks, in template order, inserted
125
- // immediately before the sentinel start so the block stays last across releases.
126
- const host1 = scanLines(lines.join('\n'));
127
- const have = new Set(host1.headings.map((h) => h.key));
128
- const additions = [];
129
- for (let n = 0; n < tpl.headings.length; n++) {
130
- const h = tpl.headings[n];
131
- if (h.index > tpl.start || have.has(h.key)) continue;
132
- const [from, to] = sectionRange(tpl, n, tpl.start);
133
- additions.push(...tpl.lines.slice(from, to));
134
- }
135
- if (additions.length) {
136
- lines = host1.status === 'balanced'
137
- ? [...lines.slice(0, host1.start), ...additions, ...lines.slice(host1.start)]
138
- : appendBlock(lines, additions);
139
- }
118
+ const keyOf = (line) => line.replace(/\r$/, '').trim();
140
119
 
141
- const text = lines.join(eol);
142
- return { text, changed: text !== hostText, warning: null };
120
+ // The installer's own entries are the template's non-blank, non-comment lines.
121
+ function managedEntries(templateText) {
122
+ return toLf(templateText).split('\n').map(keyOf).filter((k) => k && !k.startsWith('#'));
143
123
  }
144
124
 
145
- // .gitignore is line-oriented, not section-oriented: compare trimmed, CR-stripped,
146
- // non-empty lines and append the template lines the host lacks. Blank and
147
- // comment-only template lines are never appended.
148
- export function appendMissingLinesText(templateText, hostText) {
149
- if (hostText.trim() === '') {
150
- return { text: templateText, changed: templateText !== hostText, warning: null };
125
+ // The block runs from the header to the first blank line or EOF; `end` is exclusive.
126
+ function findBlock(lines) {
127
+ const header = lines.findIndex((l) => keyOf(l) === GITIGNORE_HEADER);
128
+ if (header === -1) return null;
129
+ let end = header + 1;
130
+ while (end < lines.length && keyOf(lines[end]) !== '') end++;
131
+ return { header, end };
132
+ }
133
+
134
+ // Exact copies of a managed entry outside the block: the lines gathering would move.
135
+ function strayEntryIndices(lines, block, entries) {
136
+ const inBlock = (i) => block !== null && i > block.header && i < block.end;
137
+ return lines.flatMap((l, i) => (!inBlock(i) && entries.includes(keyOf(l)) ? [i] : []));
138
+ }
139
+
140
+ // Missing entries go at the end of an existing block, or into a new block appended
141
+ // after one blank line. Every other host line keeps its bytes and its place.
142
+ function insertEntries(lines, block, missing, eol) {
143
+ if (!block) return appendLines(lines.join('\n'), [GITIGNORE_HEADER, ...missing], eol);
144
+ const cr = eol === '\r\n' ? '\r' : '';
145
+ const out = lines.slice();
146
+ if (block.end === out.length) {
147
+ out[out.length - 1] = out[out.length - 1].replace(/\r$/, '') + cr;
148
+ out.push('');
151
149
  }
152
- const eol = detectEol(hostText);
153
- const lines = toLf(hostText).split('\n');
154
- const have = new Set(lines.map((l) => l.replace(/\r$/, '').trim()).filter(Boolean));
155
- const additions = [];
156
- for (const raw of toLf(templateText).split('\n')) {
157
- const t = raw.replace(/\r$/, '').trim();
158
- if (!t || t.startsWith('#') || have.has(t)) continue;
159
- have.add(t);
160
- additions.push(t);
150
+ out.splice(block.end, 0, ...missing.map((e) => e + cr));
151
+ return out.join('\n');
152
+ }
153
+
154
+ export function mergeGitignoreText(templateText, hostText) {
155
+ if (hostText.trim() === '') {
156
+ return { text: templateText, changed: templateText !== hostText, warning: null, notice: null };
161
157
  }
162
- if (!additions.length) return { text: hostText, changed: false, warning: null };
163
- const out = lines.slice();
164
- while (out.length && out[out.length - 1].trim() === '') out.pop();
165
- out.push(...additions, '');
166
- const text = out.join(eol);
167
- return { text, changed: text !== hostText, warning: null };
158
+ const entries = managedEntries(templateText);
159
+ const lines = hostText.split('\n');
160
+ const strays = strayEntryIndices(lines, findBlock(lines), entries);
161
+ // Moving an ignore line past a later `!` re-include can change what the file
162
+ // ignores, so a host with any negation keeps every line exactly where it is.
163
+ const negated = lines.some((l) => keyOf(l).startsWith('!'));
164
+ const kept = negated || !strays.length ? lines : lines.filter((_, i) => !strays.includes(i));
165
+ // A gathered line 0 must not take the file's byte-order mark with it.
166
+ if (kept !== lines && lines[0].startsWith('') && !kept[0].startsWith('')) kept[0] = `${kept[0]}`;
167
+ const present = new Set(kept.map(keyOf));
168
+ const missing = entries.filter((e) => !present.has(e));
169
+ if (kept === lines && !missing.length) return { text: hostText, changed: false, warning: null, notice: null };
170
+ const text = insertEntries(kept, findBlock(kept), missing, detectEol(hostText));
171
+ const notice = negated && strays.length ? NEGATION_NOTICE : null;
172
+ return { text, changed: text !== hostText, warning: null, notice };
168
173
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yeison.restrepo.r/code-conductor",
3
- "version": "1.34.3",
3
+ "version": "1.35.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",
@@ -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']);
@@ -108,6 +108,76 @@ function guard2DuplicateWrite(input) {
108
108
  );
109
109
  }
110
110
 
111
+ // ── Guard 5 constants ─────────────────────────────────────────────────────────
112
+ // Copies of scripts/snap-contract.mjs values (ARCH-010 D7). This file is mirrored to two
113
+ // locations and the contract sits at a different relative path from each, so no import is
114
+ // correct in both; tests/hooks/guard5.test.js pins every copy to the contract instead.
115
+ const BAND_ROLES = ['spec', 'plan', 'code', 'audit', 'qa'];
116
+ const BAND_TOOL_KINDS = ['R', 'RW', 'X'];
117
+ const BAND_WRITE_TOOLS = ['Write', 'Edit', 'create_file', 'write_file'];
118
+ const BAND_ENVELOPE_MAX_BYTES = 10485760;
119
+ const BAND_ENVELOPE_REL = ['.claude', 'memory', 'band-envelope.json'];
120
+
121
+ const isPlainObject = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
122
+
123
+ // The band root is the nearest ancestor of cwd holding the envelope; the scope globs
124
+ // anchor there too, so discovery and anchoring are one rule (owner ruling, Case F).
125
+ function findBandRoot(start) {
126
+ let dir = resolve(start);
127
+ while (!existsSync(join(dir, ...BAND_ENVELOPE_REL))) {
128
+ const parent = dirname(dir);
129
+ if (parent === dir) return null;
130
+ dir = parent;
131
+ }
132
+ return dir;
133
+ }
134
+
135
+ // Only what Guard 5 itself reads is checked. Anything less is Case C, not a guess.
136
+ function readEnvelope(path) {
137
+ let env;
138
+ try {
139
+ if (statSync(path).size > BAND_ENVELOPE_MAX_BYTES) return null;
140
+ env = JSON.parse(readFileSync(path, 'utf8'));
141
+ } catch { return null; }
142
+ if (!isPlainObject(env) || env.v !== 3 || !isPlainObject(env.sys) || !isPlainObject(env.ops)) return null;
143
+ if (!BAND_ROLES.includes(env.sys.role) || !BAND_TOOL_KINDS.includes(env.sys.tk)) return null;
144
+ const scope = env.ops.scope;
145
+ if (env.sys.tk === 'RW' && !(Array.isArray(scope) && scope.every((g) => typeof g === 'string'))) return null;
146
+ return env;
147
+ }
148
+
149
+ // `**/` spans zero or more directories, a trailing `**` any depth, `*` one segment.
150
+ function globToRegExp(glob) {
151
+ const body = glob.split(/(\*\*\/|\*\*|\*)/).map((part) => {
152
+ if (part === '**/') return '(?:.*/)?';
153
+ if (part === '**') return '.*';
154
+ if (part === '*') return '[^/]*';
155
+ return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
156
+ }).join('');
157
+ return new RegExp(`^${body}$`);
158
+ }
159
+
160
+ // Guard 5: a role agent writing outside its band envelope's declared scope (ARCH-010).
161
+ // The main session carries no agent_type and is never subject to it (Case A); with no
162
+ // envelope there is nothing to verify (Case B). Cases C-G are the spec's table.
163
+ function guard5BandScope(input, payload) {
164
+ const role = payload.agent_type;
165
+ if (!BAND_ROLES.includes(role)) return null;
166
+ const cwd = typeof payload.cwd === 'string' && payload.cwd ? payload.cwd : process.cwd();
167
+ const root = findBandRoot(cwd);
168
+ if (!root) return null;
169
+ const file = join(root, ...BAND_ENVELOPE_REL);
170
+ const env = readEnvelope(file);
171
+ if (!env) return deny(`Guard 5: BAND_ENVELOPE_INVALID: ${file} is unreadable or not a valid v3 band envelope.`);
172
+ if (env.sys.role !== role) return deny(`Guard 5: BAND_ROLE_MISMATCH: agent ${role} is not the envelope's role ${env.sys.role}.`);
173
+ if (env.sys.tk !== 'RW') return deny(`Guard 5: BAND_READ_ONLY: role ${role} holds tk ${env.sys.tk}, not RW.`);
174
+ const target = targetPath(input);
175
+ const rel = relative(root, resolve(cwd, target)).split(sep).join('/');
176
+ const inside = target !== '' && rel !== '' && rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel);
177
+ if (inside && env.ops.scope.some((g) => globToRegExp(g).test(rel))) return null;
178
+ return deny(`Guard 5: BAND_SCOPE_VIOLATION: ${target || '<no path>'} is outside the declared scope [${env.ops.scope.join(', ')}]`);
179
+ }
180
+
111
181
  // ── Guard 3 constants ─────────────────────────────────────────────────────────
112
182
  // POSIX ERE fragments from tests/fixtures/guard3-reference.sh, translated class by
113
183
  // class. [[:space:]] in the C locale is EXACTLY [ \t\n\r\f\v]; JavaScript \s also
@@ -563,6 +633,8 @@ const DISPATCH = {
563
633
  Edit: [],
564
634
  Bash: [guard3BashScan],
565
635
  };
636
+ // Guard 5 runs first on every write-family tool: a scope deny outranks Guard 2's ask.
637
+ for (const tool of BAND_WRITE_TOOLS) DISPATCH[tool].unshift(guard5BandScope);
566
638
 
567
639
  // Case B. Unparseable input is not "nothing to verify", it is "the verifier could not
568
640
  // run", which is the condition that fails closed. CC_HOOK_ALLOW bypasses THIS denial only;
@@ -600,7 +672,7 @@ function main() {
600
672
  const guards = DISPATCH[name];
601
673
  if (!guards) { debug(`no guard registered for tool_name "${name}"; allowing`); return; }
602
674
  for (const guard of guards) {
603
- const decision = guard(input);
675
+ const decision = guard(input, payload);
604
676
  if (decision) { emit(decision); return; }
605
677
  }
606
678
  }
@@ -1,3 +1,5 @@
1
+ # Code Conductor (added by the installer; safe to keep)
1
2
  .claude/memory/turn-count.txt
2
3
  *.installer-backup.*
3
4
  *.installer-tmp.*
5
+ .claude/memory/band-envelope.json
@@ -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
- if (pr === '') {
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 skeletonBytes = byteLen(JSON.stringify({ v: 2, sys, ops, mem, pr: '' }));
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: 2, sys, ops, mem, pr: pr.slice(0, keep) };
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. For v2 the
18
- // two tiers coincide; they separate the moment a v3 arrives with its own budget.
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 = 2;
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. Top-level is per version; block members are version-invariant.
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
- export const BLOCK_FIELDS = { sys: ['ph', 'c', 's'], ops: ['n', 'f'], mem: ['d', 'x'] };
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[2]; if (path === undefined) err('no path provided');
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 req = { v: snap.v, 'sys.ph': snap.sys.ph, 'sys.c': snap.sys.c, 'sys.s': snap.sys.s, 'ops.n': snap.ops.n, 'ops.f': snap.ops.f, 'mem.d': snap.mem.d, 'mem.x': snap.mem.x };
13
- const missing = Object.entries(req).filter(([, v]) => v === undefined).map(([k]) => k);
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 topAllowed = TOP_FIELDS[snap.v] || TOP_FIELDS[1];
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
- for (const [key, [cap, elemCap]] of Object.entries(CAPS)) {
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);