@futurelastic/colab-handbook 1.13.0-rc.58 → 1.13.0-rc.59

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/audit/audit.mjs CHANGED
@@ -39,6 +39,8 @@
39
39
  // # private identity vocabulary — see "Identity" below
40
40
  // node audit.mjs --batch-history # also read each local repo's batch landing history
41
41
  // # (colab batch-stats --json) — see "Batch history" below
42
+ // node audit.mjs --base <rev> # the instruction-file ratchet's base for LOCAL repos
43
+ // # (default origin/<trunk>) — see checkInstructionFileShape
42
44
  //
43
45
  // Identity (--identity): metadata never passes through git, so the pre-commit identity scan
44
46
  // (templates/pre-commit-identity) structurally cannot see it, and it is the first thing a
@@ -132,6 +134,7 @@ const gateLib = require("../tools/lib/gate.js");
132
134
  // #417: CLAUDE.md as a thin shell over AGENTS.md — the @-import resolver and the tool-block table,
133
135
  // shared with `colab adopt` so the shell it writes and the shape the audit checks are one shape.
134
136
  const instructionFile = require("../tools/lib/instruction-file.js");
137
+ const instructionGate = require("../tools/lib/instruction-gate.js"); // #588
135
138
  // #228's identity vocabulary — resolution, parsing, matching and REDACTION. Shared with the
136
139
  // conformance test that holds it and the shell hook (templates/pre-commit-identity) to the
137
140
  // same semantics; the shell scanner cannot require it (a template lands in repos with no
@@ -159,6 +162,11 @@ function parseArgs(argv) {
159
162
  else if (a === "--quiet" || a === "-q") opts.quiet = true;
160
163
  else if (a === "--identity") opts.identity = true;
161
164
  else if (a === "--batch-history") opts.batchHistory = true;
165
+ else if (a === "--base") {
166
+ const p = argv[++i];
167
+ if (!p) die("--base needs a rev");
168
+ opts.base = p;
169
+ }
162
170
  else if (a === "--local") {
163
171
  const p = argv[++i];
164
172
  if (!p) die("--local needs a path");
@@ -653,6 +661,7 @@ function makeSource(target) {
653
661
  return {
654
662
  label: target.label,
655
663
  kind: "local",
664
+ root,
656
665
  exists: existsSync(root),
657
666
  readFile: (p) => {
658
667
  const f = join(root, p);
@@ -1775,7 +1784,8 @@ function auditRepo(target, ctx) {
1775
1784
  // block to place, and its AGENTS.md says it "follows the colab-handbook" (#587).
1776
1785
  checkInstructionFileBlocks(src, warn, { self: isSelf });
1777
1786
  // #419: and prose left in CLAUDE.md / no AGENTS.md at all — same posture, same reason.
1778
- checkInstructionFileShape(src, warn);
1787
+ // #588: and the same finding FAILS where the instruction-file ratchet trips (local repos only).
1788
+ checkInstructionFileShape(src, warn, fail, { base: ctx.base, trunk: cfg?.trunk ?? null });
1779
1789
 
1780
1790
  // ---- markdown anchor links resolve (#158) --------------------------------
1781
1791
  // Unconditional, same posture as checkClaudeMdSize above: general markdown hygiene,
@@ -2674,10 +2684,33 @@ function checkInstructionFileBlocks(src, warn, { self = false } = {}) {
2674
2684
  // A repo with neither file is not this check's business (no instruction
2675
2685
  // file at all is an adoption gap, reported elsewhere).
2676
2686
  //
2677
- // WARN, never FAIL: existing repos migrate over time (handbook-sync's graft step moves the prose).
2678
- // Byte-identical CLAUDE.md and AGENTS.md (a symlinked or copied pair) are one file here, as in
2679
- // checkInstructionFileBlocks: there is nothing to move, and the prose is loaded once.
2680
- function checkInstructionFileShape(src, warn) {
2687
+ // WARN, and FAIL only under the ratchet (#588): existing repos migrate over time (handbook-sync's
2688
+ // graft step moves the prose), so the finding fails only where `colab instruction-files` would —
2689
+ // a LOCAL repo inside git, judged against merge-base(<base>, HEAD) with <base> = `--base`, else
2690
+ // origin/<trunk>: some CLAUDE.md non-conforming in the working tree AND either a CLAUDE.md/AGENTS.md
2691
+ // changed since the merge base, or every CLAUDE.md conformed there. Same code as the hook and the
2692
+ // reusable workflow (tools/lib/instruction-gate.js), so the three cannot disagree. A remote source,
2693
+ // or a local one with no base to compare against, keeps the warning: no ratchet, no failure.
2694
+ function instructionRatchet(src, opts) {
2695
+ if (src.kind !== "local" || !src.root) return null;
2696
+ const base = opts.base || (opts.trunk ? `origin/${opts.trunk}` : null);
2697
+ if (!base) return null;
2698
+ const r = instructionGate.gate({ cwd: src.root, base, head: "worktree" });
2699
+ if (!r.ok) return opts.base ? { ok: false, error: r.error } : null; // an explicit base that cannot be read is said aloud
2700
+ return r;
2701
+ }
2702
+
2703
+ function checkInstructionFileShape(src, warn, fail = warn, opts = {}) {
2704
+ const ratchet = instructionRatchet(src, opts);
2705
+ if (ratchet && !ratchet.ok) warn(`instruction-file ratchet not evaluated: ${ratchet.error} (#588)`);
2706
+ if (ratchet && ratchet.ok && ratchet.fail) {
2707
+ const why = ratchet.reason === "touched"
2708
+ ? "this change touches CLAUDE.md/AGENTS.md"
2709
+ : "every CLAUDE.md conformed at the merge base, so this regresses the repo";
2710
+ for (const f of ratchet.bad) {
2711
+ fail(`prose-in-claude-md: ${f.message} (CONVENTIONS.md §9 step 5; ratchet: ${why}; \`colab instruction-files --base <rev>\` reproduces it) (#588)`);
2712
+ }
2713
+ }
2681
2714
  const claude = src.readFile("CLAUDE.md");
2682
2715
  if (claude === null || claude === undefined) return;
2683
2716
  const agents = src.readFile("AGENTS.md");
@@ -2689,6 +2722,7 @@ function checkInstructionFileShape(src, warn) {
2689
2722
  } else if (agents === claude) {
2690
2723
  return;
2691
2724
  }
2725
+ if (ratchet && ratchet.ok && ratchet.fail) return; // already reported above, as a failure
2692
2726
  const residue = instructionFile.shellResidue(claude);
2693
2727
  if (!residue.length) return;
2694
2728
  const shape = instructionFile.isThinShell(claude)
@@ -3306,6 +3340,7 @@ function runAudit(opts) {
3306
3340
  const ctx = { handbook: handbookInfo(HANDBOOK_ROOT), templateNames: templateNames(HANDBOOK_ROOT) };
3307
3341
  ctx.identity = opts.identity ? loadIdentityVocabulary() : null;
3308
3342
  ctx.batchHistory = !!opts.batchHistory;
3343
+ ctx.base = opts.base || null;
3309
3344
 
3310
3345
  const results = [];
3311
3346
  for (const t of targets) {
package/package.json CHANGED
@@ -33,5 +33,5 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "version": "1.13.0-rc.58"
36
+ "version": "1.13.0-rc.59"
37
37
  }
@@ -33,6 +33,7 @@ Starting points you **copy into your own repo**. That is the entire model.
33
33
  | `adr-README.md` | `docs/adr/README.md` | Any repo starting a `docs/adr/` directory ([`code-wrap`](../skills/code-wrap/SKILL.md)'s A2 step) | Same issue-keyed naming rule as `gotchas-d-README.md`, applied to architecture decision records instead of gotchas — an existing sequentially-numbered `docs/adr/` is left as-is; only new decisions use `<issue>-<slug>.md`. Optional, same as above. |
34
34
  | `docs-lint.mjs` | anywhere in-repo (e.g. `tools/docs-lint.mjs`) | Every repo — checks the STRUCTURE of the doc graph (router integrity, orphans, drafts-in-`docs/`, router size budget, dated files, §-citation resolution, `gotchas.d/` registry discipline, two-surface linkage) | Zero-dependency, plain Node — but it does **shell out to `git check-ignore`** once per enumeration, so that a git-ignored scratch file (your `.plans/` plan file, say) can never fail a structural check on your repo (#310). No git, or no repo, and it filters nothing and lints exactly as before. **Enumerated by `colab template` and DOES take an automatic version stamp** (colab-handbook #252): `colab template docs-lint.mjs --dest tools/docs-lint.mjs` copies it stamped on its **second** line (`// colab-handbook: docs-lint @ <version>`, after the `#!/usr/bin/env node` shebang — a bare `#` on any other line is a JS syntax error, unlike the YAML templates above) — `--dest` is required, since this file has no formulaic destination the way a workflow does. Pairs with `docs-lint.yml`. Also runs from `code-wrap`'s docs step and a weekly fleet sweep (colab-handbook #249) — this row is the third of its three seats. |
35
35
  | `docs-lint.yml` | `.github/workflows/docs-lint.yml` | Every repo that copied `docs-lint.mjs` | Advisory job — `continue-on-error: true` on the lint step, so a finding never blocks a merge until a repo deliberately removes that line. Requires `docs-lint.mjs` to already be in the repo; does not vendor it. |
36
+ | `instruction-files.yml` | `.github/workflows/instruction-files.yml` | Every repo with a `CLAUDE.md` (#588) | **A caller, not a copy:** its one job `uses:` the handbook's reusable `.github/workflows/instruction-files.yml`, so the judgement is maintained once and works from any org. Fails when a `CLAUDE.md` carries repo prose instead of `@AGENTS.md` + tool blocks — **ratcheted**: only when the change touches `CLAUDE.md`/`AGENTS.md`, or the repo had already migrated. An unmigrated repo stays green until it edits those files. Pin `@<tag>` plus `with: handbook-ref: <tag>` to freeze the checker. |
36
37
  | `branch-name.yml` | `.github/workflows/branch-name.yml` | Opt-in — any repo that wants §4's branch shape checked on every PR | One step, no dependencies: the PR's head branch against CONVENTIONS.md §4's regex, both shapes (`<type>/<slug>-<N>` and the `<login>/<machine>/` prefixed one) passing as shipped. Once the repo declares `branchPrefix: machine`, delete the `?` after the regex's first group to require the prefix. The head ref reaches the script through `env:`, never interpolated — on a public repo it is attacker-chosen. |
37
38
 
38
39
  ### The `dedupe` job — why a claimed branch's first run skips the suite (#418)
@@ -110,7 +111,7 @@ match their source stem (`pre-push-guard` → `<hooks>/pre-push`) — so `colab
110
111
  does not carry them, and they take **no version stamp**. The original reason a stamp
111
112
  was impossible here — prepending a comment line above a `#!` shebang breaks it — is
112
113
  fixed for `docs-lint.mjs` above (a second-line stamp, colab-handbook #252), but that fix
113
- still needs a destination formula before it can apply to these too, and these three
114
+ still needs a destination formula before it can apply to these too, and these
114
115
  files don't have one. Copy them with `cp`, `chmod +x`, and own them exactly as you own
115
116
  a workflow.
116
117
 
@@ -119,6 +120,7 @@ a workflow.
119
120
  | `pre-push-guard` | `<hooks>/pre-push` | Every repo with a protected trunk | Refuses a raw push to trunk, a declared integration line, or `main` on a repo that promotes, and the release channels `next` / `stable`, which only `colab release cut` / `finalize` move (#445). Reads `project.yml`; missing descriptor → allows, with a warning. |
120
121
  | `pre-commit-dispatch` | `<hooks>/pre-commit` | Any repo that needs **more than one** pre-commit check | Runs every hooklet in `pre-commit.d/`, fails if any failed, and **refuses when there is nothing to run**. Read its header before installing — it replaces a hook you already have, and step 2 of its instructions is where your existing check survives. |
121
122
  | `pre-commit-identity` | `<hooks>/pre-commit.d/20-identity` | Any repo that could publish an identity — every public one, and any private one that may ever be opened | Scans staged content against a vocabulary the operator supplies **by path**. Also installs as `commit-msg`. |
123
+ | `pre-commit-instruction-files` | `<hooks>/pre-commit.d/30-instruction-files` | Every repo with a `CLAUDE.md` (#588) | Runs `colab instruction-files --staged` only when a `CLAUDE.md`/`AGENTS.md` is staged — otherwise one `git diff --cached` and out. Same judgement and ratchet as the CI caller above. No `colab` on the machine → warns and passes; CI still judges the push. |
122
124
  | `identity-vocabulary.example` | *outside every repo* — e.g. `~/.colab/identity-vocabulary` | The above | Invented entries. **A real one is never committed anywhere**, which is the whole reason the scanner takes a path instead of shipping a list. |
123
125
 
124
126
  `<hooks>` is `git config core.hooksPath` if you set one, else `.git/hooks`. The
@@ -195,6 +197,7 @@ mkdir -p <hooks>/pre-commit.d
195
197
  git mv <hooks>/pre-commit <hooks>/pre-commit.d/10-secrets # your existing check, unchanged
196
198
  cp templates/pre-commit-dispatch <hooks>/pre-commit
197
199
  cp templates/pre-commit-identity <hooks>/pre-commit.d/20-identity
200
+ cp templates/pre-commit-instruction-files <hooks>/pre-commit.d/30-instruction-files
198
201
  chmod +x <hooks>/pre-commit <hooks>/pre-commit.d/*
199
202
  cp templates/identity-vocabulary.example ~/.colab/identity-vocabulary # then EDIT it, outside any repo
200
203
  ```
@@ -0,0 +1,8 @@
1
+ # Copy to .github/workflows/instruction-files.yml — CLAUDE.md must be @AGENTS.md + tool blocks (#588).
2
+ name: instruction-files
3
+ on:
4
+ push:
5
+ pull_request:
6
+ jobs:
7
+ instruction-files:
8
+ uses: futurelastic/colab-handbook/.github/workflows/instruction-files.yml@main
@@ -0,0 +1,55 @@
1
+ #!/bin/sh
2
+ # pre-commit-instruction-files — refuse a commit that leaves repo prose in a CLAUDE.md (#588).
3
+ #
4
+ # THE RULE (CONVENTIONS.md §9 step 5). Repo prose lives in AGENTS.md; CLAUDE.md is only the
5
+ # `@AGENTS.md` import plus the blocks tools look up in CLAUDE.md by name (the Conventions block
6
+ # with its stamp, any paired tool-managed block). An editor-side hook only sees edits made through
7
+ # one agent's file tools — a shell write, another agent, a person or a generator that rewrites
8
+ # CLAUDE.md all pass it. This runs on every commit, whoever made it.
9
+ #
10
+ # THE JUDGEMENT IS NOT HERE. It is `colab instruction-files --staged` — the same code the audit
11
+ # and the reusable CI workflow (.github/workflows/instruction-files.yml in the handbook) run, so
12
+ # the three cannot disagree. Same ratchet too: staging a CLAUDE.md or AGENTS.md is touching the
13
+ # rule's files, so every CLAUDE.md must then conform; a commit that leaves both alone is never
14
+ # judged, so an unmigrated repo is not blocked by adding this hook.
15
+ #
16
+ # COST. With no CLAUDE.md/AGENTS.md staged this is one `git diff --cached --name-only` and exits —
17
+ # a few milliseconds. Only a commit that stages one of them starts node.
18
+ #
19
+ # WHERE `colab` COMES FROM: $COLAB_BIN if set (the handbook's own hooklet points it at its
20
+ # checkout), else `colab` on PATH. Neither present → warn and pass: an unconfigured machine is a
21
+ # different statement from a failed check, and CI still runs the same judgement on the push.
22
+ #
23
+ # INSTALL — beside the dispatcher (templates/pre-commit-dispatch, see its header):
24
+ # cp templates/pre-commit-instruction-files <hooks>/pre-commit.d/30-instruction-files
25
+ # chmod +x <hooks>/pre-commit.d/30-instruction-files
26
+ #
27
+ # EXIT: 0 pass (or nothing to judge, or no colab), 1 refused — the message names the fix.
28
+
29
+ set -u
30
+
31
+ staged=$(git diff --cached --name-only --diff-filter=ACMRT 2>/dev/null | grep -E '(^|/)(CLAUDE|AGENTS)\.md$' || true)
32
+ [ -n "$staged" ] || exit 0
33
+
34
+ bin="${COLAB_BIN:-colab}"
35
+ if [ -n "${COLAB_BIN:-}" ]; then
36
+ [ -f "$bin" ] || { printf '%s\n' "⚠ pre-commit-instruction-files: COLAB_BIN=$bin does not exist — not judged; CI will judge on push." >&2; exit 0; }
37
+ set -- node "$bin"
38
+ elif command -v colab >/dev/null 2>&1; then
39
+ set -- colab
40
+ else
41
+ printf '%s\n' "⚠ pre-commit-instruction-files: \`colab\` is not installed — CLAUDE.md not judged here; CI will judge it on push (npm i -g @futurelastic/colab-handbook)." >&2
42
+ exit 0
43
+ fi
44
+
45
+ "$@" instruction-files --staged
46
+ status=$?
47
+ if [ "$status" -eq 1 ]; then
48
+ printf '%s\n' "❌ commit BLOCKED: move the prose above into AGENTS.md and keep CLAUDE.md to \`@AGENTS.md\` + tool blocks." >&2
49
+ exit 1
50
+ fi
51
+ if [ "$status" -ne 0 ]; then
52
+ printf '%s\n' "❌ commit BLOCKED: the instruction-file check could not run (exit $status) — see above." >&2
53
+ exit 1
54
+ fi
55
+ exit 0
package/tools/colab CHANGED
@@ -84,6 +84,7 @@ const refsBrake = require('./lib/refs-brake'); // #385
84
84
  const localAdopt = require('./lib/local-adopt'); // #393
85
85
  const ownerBranch = require('./lib/owner-branch'); // #394
86
86
  const humanDoor = require('./lib/ship-human-door'); // #525
87
+ const instructionGate = require('./lib/instruction-gate'); // #588
87
88
  const {
88
89
  HOST, UserError, normIssueNum, issueTag, claimKey, today, nowISO, hoursSince, humanAge,
89
90
  parseArgs, table, shortRepo,
@@ -15795,6 +15796,59 @@ Empty output is clean ground ONLY when the fetch succeeded. Exit: 0 answered, 2
15795
15796
  staleness (fetch skipped or failed, and the result would have been "clean").
15796
15797
  `;
15797
15798
 
15799
+ const HELP_INSTRUCTION_FILES = `colab instruction-files [--base <rev> | --staged] [--repo <path>] [--json]
15800
+
15801
+ Is every tracked CLAUDE.md the thin-shell shape — the \`@AGENTS.md\` import plus tool-managed blocks,
15802
+ with the repo's prose in AGENTS.md (CONVENTIONS.md §9 step 5, #588)? One judgement
15803
+ (tools/lib/instruction-file.js), shared with the audit, the pre-commit hook and the reusable CI
15804
+ workflow \`.github/workflows/instruction-files.yml\`.
15805
+
15806
+ --base <rev> RATCHET against merge-base(<rev>, HEAD). Fails only when a CLAUDE.md does not
15807
+ conform at HEAD AND either a CLAUDE.md/AGENTS.md changed since the merge base, or
15808
+ every CLAUDE.md conformed there. An unmigrated repo whose change leaves both files
15809
+ alone passes. This is what CI runs.
15810
+ --staged judge the INDEX against HEAD, same ratchet (staging a CLAUDE.md/AGENTS.md is
15811
+ touching it). This is what the pre-commit hook runs.
15812
+ (neither) judge every CLAUDE.md at HEAD, no ratchet: any non-conforming file fails.
15813
+ --repo <path> repo to run in (default: cwd)
15814
+ --json { ok, error?, mode, base, fail, reason, files: [{ path, conforming, message }], changed }
15815
+
15816
+ Exit: 0 pass · 1 fail · 2 cannot judge (not a repo, base not fetched — never read as a pass).
15817
+ The fix for a failure is always the same: move the prose to AGENTS.md (handbook-sync's graft step
15818
+ does the move), keeping CLAUDE.md to \`@AGENTS.md\`, blank lines and tool blocks.
15819
+ `;
15820
+
15821
+ function cmdInstructionFiles(argv) {
15822
+ const opts = parseArgs(argv, {
15823
+ values: { '--repo': 'repo', '--base': 'base' },
15824
+ flags: { '--json': 'json', '--staged': 'staged', '-h': 'help', '--help': 'help' },
15825
+ });
15826
+ if (opts.help) return print(HELP_INSTRUCTION_FILES);
15827
+ if (opts.staged && opts.base) throw new UserError('--staged and --base are two different questions — pass one: `colab instruction-files --staged` (a commit) or `colab instruction-files --base <rev>` (a branch)');
15828
+ // The tree you stand in, NOT resolveRepo's main checkout: from inside a linked worktree the hook
15829
+ // and CI must judge that worktree's index and HEAD, never trunk's.
15830
+ const at = opts.repo ? path.resolve(String(opts.repo)) : process.cwd();
15831
+ const cwd = git.repoRoot(at);
15832
+ if (!cwd) throw new UserError(`${at} is not inside a git repo — pass --repo <path>`);
15833
+ const r = instructionGate.gate({ cwd, staged: !!opts.staged, base: opts.base ? String(opts.base) : null });
15834
+ if (opts.json) {
15835
+ print(JSON.stringify(r, null, 2));
15836
+ return !r.ok ? 2 : r.fail ? 1 : 0;
15837
+ }
15838
+ const lines = instructionGate.describe(r);
15839
+ if (!r.ok) {
15840
+ process.stderr.write(`✗ instruction-files: ${lines[0]} — re-run once the base is fetched (\`git fetch origin\`), or run \`colab instruction-files\` with no --base to judge without the ratchet\n`);
15841
+ return 2;
15842
+ }
15843
+ if (r.fail) {
15844
+ process.stderr.write(`✗ instruction-files: CLAUDE.md carries repo prose — move it to AGENTS.md (\`colab instruction-files --help\`)\n`);
15845
+ for (const l of lines) process.stderr.write(` ${l}\n`);
15846
+ return 1;
15847
+ }
15848
+ for (const l of lines) print(r.bad.length ? `! ${l}` : `✓ ${l}`);
15849
+ return 0;
15850
+ }
15851
+
15798
15852
  function cmdHolders(argv) {
15799
15853
  const opts = parseArgs(argv, {
15800
15854
  values: { '--repo': 'repo', '--base': 'base' },
@@ -16461,6 +16515,10 @@ Commands:
16461
16515
  holders <path> [--base B] [--json] who else is holding <path> — refs that touched it and
16462
16516
  have not landed on the base (filters the raw git-log
16463
16517
  one-liner through \`landed\`'s content classification)
16518
+ instruction-files [--base B | --staged] [--json]
16519
+ CLAUDE.md is only @AGENTS.md + tool blocks? ratcheted:
16520
+ fails only where the change touches it or would regress
16521
+ a migrated repo (#588) — the hook and CI run this
16464
16522
  promote [--repo P] [--message M] [--dry] trunk → main (--no-ff); gated by deploy + promotion; never tags
16465
16523
  deliver [--repo P] [--dry] [--json] [--reopen] project.yml owner: only — open/refresh ONE PR
16466
16524
  trunk → the owner's branch; never merges it (#394)
@@ -16548,6 +16606,7 @@ function main(argv) {
16548
16606
  case 'trunk-ci': return cmdTrunkCi(rest);
16549
16607
  case 'ci-wait': return cmdCiWait(rest);
16550
16608
  case 'holders': return cmdHolders(rest);
16609
+ case 'instruction-files': return cmdInstructionFiles(rest);
16551
16610
  case 'promote': return cmdPromote(rest);
16552
16611
  case 'deliver': return cmdDeliver(rest);
16553
16612
  case 'doctor': return cmdDoctor(rest);
@@ -282,6 +282,52 @@ function lineRanges(nums, text = null) {
282
282
  return parts.join(', ');
283
283
  }
284
284
 
285
+ /**
286
+ * Is one CLAUDE.md the thin-shell shape (#588)? The single judgement every enforcement point uses —
287
+ * the audit, the pre-commit hook and the reusable CI workflow all reach it through
288
+ * `instruction-gate.js`, never a second copy.
289
+ *
290
+ * `{ conforming, residue, legacy, message }`. `agents` is the sibling AGENTS.md text, or null.
291
+ * Conforming: no residue (`shellResidue`), or CLAUDE.md byte-identical to its AGENTS.md (a
292
+ * symlinked or copied pair is one file — nothing to move). A missing AGENTS.md on its own is not a
293
+ * failure: a CLAUDE.md that is only tool blocks breaks no rule; the audit still advises on it.
294
+ * `message` (null when conforming) names the fix, because a refusal that does not is a dead end.
295
+ */
296
+ function judgeClaudeMd(claude, agents = null, rel = ENTRY) {
297
+ if (claude === null || claude === undefined) return { conforming: true, residue: [], legacy: false, message: null };
298
+ if (agents !== null && agents !== undefined && agents === claude) return { conforming: true, residue: [], legacy: false, message: null };
299
+ const residue = shellResidue(claude);
300
+ if (!residue.length) return { conforming: true, residue, legacy: false, message: null };
301
+ const legacy = !isThinShell(claude);
302
+ const shape = legacy ? 'and it has no @AGENTS.md import (a legacy prose-only file)' : 'next to its @AGENTS.md import';
303
+ const sibling = path.posix.join(path.posix.dirname(rel), AUTHORED).replace(/^\.\//, '');
304
+ return {
305
+ conforming: false,
306
+ residue,
307
+ legacy,
308
+ message: `${rel} line${residue.length === 1 ? '' : 's'} ${lineRanges(residue, claude)} carry repo prose ${shape} — move them to ${sibling} ` +
309
+ `and keep ${rel} to the \`@AGENTS.md\` import, blank lines and tool blocks such as the Conventions block`,
310
+ };
311
+ }
312
+
313
+ /**
314
+ * The ratchet (#588), pure. `changed` = repo-relative paths that differ between the base and the
315
+ * head; `head` / `base` = `[{ path, conforming }]` for every CLAUDE.md at each side (`base` null
316
+ * when there is no base to compare against). Fails iff some head CLAUDE.md does not conform AND
317
+ * (a) a CLAUDE.md or AGENTS.md changed — the branch touched the rule's files, so it owns them; or
318
+ * (b) every CLAUDE.md conformed at the base — the repo had migrated, and this would regress it.
319
+ * An unmigrated repo whose branch leaves both files alone stays green, so adding the check never
320
+ * turns a trunk red on its own. `{ fail, reason, bad }`; `reason` is 'touched' | 'regressed' | null.
321
+ */
322
+ const RULE_FILE_RE = /(^|\/)(CLAUDE|AGENTS)\.md$/;
323
+ function ratchetVerdict({ changed = [], head = [], base = null }) {
324
+ const bad = head.filter((f) => !f.conforming);
325
+ if (!bad.length) return { fail: false, reason: null, bad };
326
+ if (changed.some((p) => RULE_FILE_RE.test(p))) return { fail: true, reason: 'touched', bad };
327
+ if (base && base.every((f) => f.conforming)) return { fail: true, reason: 'regressed', bad };
328
+ return { fail: false, reason: null, bad };
329
+ }
330
+
285
331
  module.exports = {
286
332
  stripCode,
287
333
  IMPORT_MAX_DEPTH,
@@ -300,4 +346,7 @@ module.exports = {
300
346
  conventionsBlock,
301
347
  shellResidue,
302
348
  lineRanges,
349
+ judgeClaudeMd,
350
+ RULE_FILE_RE,
351
+ ratchetVerdict,
303
352
  };
@@ -0,0 +1,150 @@
1
+ 'use strict';
2
+ /**
3
+ * The instruction-file gate (#588) — the ONE git-aware entry point the three enforcement points
4
+ * share: the audit (`checkInstructionFileShape`, warn → fail), the pre-commit hook
5
+ * (`colab instruction-files --staged`) and the reusable CI workflow
6
+ * (`colab instruction-files --base <ref>`). The shape judgement itself is
7
+ * `instruction-file.js` `judgeClaudeMd`, and the ratchet is its `ratchetVerdict`; this module only
8
+ * reads trees out of git and feeds them in. Nothing else re-implements either.
9
+ *
10
+ * Sides a tree can be read from:
11
+ * { ref: '<rev>' } a commit (CI's head, the merge base)
12
+ * 'index' the staged content (the pre-commit hook)
13
+ * 'worktree' the files on disk, tracked paths only (the audit, which reads the working tree)
14
+ *
15
+ * "Every tracked CLAUDE.md" means every path whose basename is `CLAUDE.md`, at any depth, judged
16
+ * against the `AGENTS.md` beside it. A symlinked CLAUDE.md is read through its link target, so the
17
+ * common `CLAUDE.md -> AGENTS.md` pair reads as one file (conforming), as the audit already treats
18
+ * a byte-identical pair.
19
+ */
20
+
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const { execFileSync } = require('child_process');
24
+ const inst = require('./instruction-file.js');
25
+
26
+ const CLAUDE_RE = /(^|\/)CLAUDE\.md$/;
27
+
28
+ function git(cwd, args) {
29
+ try {
30
+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 });
31
+ } catch (_) {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ /** `[{ path, mode }]` for every CLAUDE.md on `side`; null when the side cannot be read. */
37
+ function listClaude(cwd, side) {
38
+ let out;
39
+ if (side === 'index' || side === 'worktree') out = git(cwd, ['ls-files', '-s', '-z']);
40
+ else out = git(cwd, ['ls-tree', '-r', '-z', '--full-tree', side.ref]);
41
+ if (out === null) return null;
42
+ const found = [];
43
+ for (const rec of out.split('\0')) {
44
+ if (!rec) continue;
45
+ const tab = rec.indexOf('\t');
46
+ const p = rec.slice(tab + 1);
47
+ if (!CLAUDE_RE.test(p)) continue;
48
+ found.push({ path: p, mode: rec.split(' ')[0] });
49
+ }
50
+ return found;
51
+ }
52
+
53
+ /** `readFile(rel) -> string|null` on `side`. */
54
+ function reader(cwd, side) {
55
+ if (side === 'worktree') {
56
+ return (rel) => {
57
+ try { return fs.readFileSync(path.join(cwd, rel), 'utf8'); } catch (_) { return null; }
58
+ };
59
+ }
60
+ const prefix = side === 'index' ? ':' : `${side.ref}:`;
61
+ return (rel) => git(cwd, ['show', `${prefix}${rel}`]);
62
+ }
63
+
64
+ /**
65
+ * `[{ path, conforming, message }]` — every CLAUDE.md on `side`, judged. null when the side
66
+ * cannot be read (an unknown ref). Symlinks (mode 120000) are followed one hop, in-repo only.
67
+ */
68
+ function judgeSide(cwd, side) {
69
+ const list = listClaude(cwd, side);
70
+ if (list === null) return null;
71
+ const read = reader(cwd, side);
72
+ return list.map(({ path: rel, mode }) => {
73
+ let text;
74
+ if (mode === '120000' && side !== 'worktree') {
75
+ const target = (read(rel) || '').trim();
76
+ const r = inst.resolveImport(rel, target);
77
+ text = r.path ? read(r.path) : null;
78
+ } else {
79
+ text = read(rel);
80
+ }
81
+ const agentsRel = path.posix.join(path.posix.dirname(rel), inst.AUTHORED).replace(/^\.\//, '');
82
+ const j = inst.judgeClaudeMd(text, read(agentsRel), rel);
83
+ return { path: rel, conforming: j.conforming, message: j.message };
84
+ });
85
+ }
86
+
87
+ /**
88
+ * Run the gate. Options:
89
+ * cwd repo (default process.cwd())
90
+ * staged true → judge the index against HEAD (the pre-commit hook)
91
+ * base a rev → judge `head` against merge-base(base, HEAD) (CI, the audit)
92
+ * head 'worktree' to judge the working tree instead of HEAD (the audit); default HEAD
93
+ * With neither `staged` nor `base`, every CLAUDE.md at the head is judged with no ratchet:
94
+ * any non-conforming file fails (`reason: 'strict'`).
95
+ *
96
+ * Returns `{ ok, error?, fail, reason, mode, base, files, bad, changed }`. `ok: false` means the
97
+ * gate could not answer (not a repo, base unknown, merge base not reachable in a shallow clone)
98
+ * — callers must refuse rather than read that as a pass.
99
+ */
100
+ function gate({ cwd = process.cwd(), staged = false, base = null, head = null } = {}) {
101
+ if (git(cwd, ['rev-parse', '--git-dir']) === null) return { ok: false, error: `${cwd} is not a git repo` };
102
+ const hasHead = git(cwd, ['rev-parse', '--verify', '-q', 'HEAD^{commit}']) !== null;
103
+
104
+ if (staged) {
105
+ const files = judgeSide(cwd, 'index');
106
+ const changed = (git(cwd, ['diff', '--cached', '--name-only', '-z']) || '').split('\0').filter(Boolean);
107
+ const baseFiles = hasHead ? judgeSide(cwd, { ref: 'HEAD' }) : [];
108
+ const v = inst.ratchetVerdict({ changed, head: files, base: baseFiles });
109
+ return { ok: true, mode: 'staged', base: hasHead ? 'HEAD' : null, files, changed, ...v };
110
+ }
111
+
112
+ const headSide = head === 'worktree' ? 'worktree' : { ref: head || 'HEAD' };
113
+ if (headSide !== 'worktree' && !hasHead && !head) return { ok: false, error: 'HEAD has no commit yet' };
114
+ const files = judgeSide(cwd, headSide);
115
+ if (files === null) return { ok: false, error: `cannot read ${head || 'HEAD'}` };
116
+
117
+ if (!base) {
118
+ const bad = files.filter((f) => !f.conforming);
119
+ return { ok: true, mode: 'strict', base: null, files, changed: [], fail: bad.length > 0, reason: bad.length ? 'strict' : null, bad };
120
+ }
121
+
122
+ if (git(cwd, ['rev-parse', '--verify', '-q', `${base}^{commit}`]) === null) {
123
+ return { ok: false, error: `base ${base} is not a commit here — fetch it (a CI checkout needs fetch-depth: 0)` };
124
+ }
125
+ const headRev = headSide === 'worktree' ? 'HEAD' : headSide.ref;
126
+ const mb = (git(cwd, ['merge-base', base, headRev]) || '').trim();
127
+ if (!mb) return { ok: false, error: `no merge base between ${base} and ${headRev} — a shallow clone? (fetch-depth: 0)` };
128
+ const diffArgs = headSide === 'worktree' ? ['diff', '--name-only', '-z', mb] : ['diff', '--name-only', '-z', mb, headRev];
129
+ const changed = (git(cwd, diffArgs) || '').split('\0').filter(Boolean);
130
+ const baseFiles = judgeSide(cwd, { ref: mb });
131
+ const v = inst.ratchetVerdict({ changed, head: files, base: baseFiles });
132
+ return { ok: true, mode: 'ratchet', base: mb, files, changed, ...v };
133
+ }
134
+
135
+ /** One human line per verdict, naming the fix. */
136
+ function describe(r) {
137
+ if (!r.ok) return [`cannot judge: ${r.error}`];
138
+ if (!r.bad.length) return [`instruction files conform (${r.files.length} CLAUDE.md judged)`];
139
+ const why = {
140
+ touched: 'this change touches CLAUDE.md/AGENTS.md, so every CLAUDE.md must conform',
141
+ regressed: 'every CLAUDE.md conformed at the merge base, so this would regress the repo',
142
+ strict: 'judged with no base (no ratchet)',
143
+ }[r.reason];
144
+ const lines = r.bad.map((f) => f.message);
145
+ if (r.fail) lines.push(`(${why} — CONVENTIONS.md §9 step 5, #588)`);
146
+ else lines.push('(not failing: unmigrated repo and this change leaves CLAUDE.md/AGENTS.md alone — the ratchet, #588)');
147
+ return lines;
148
+ }
149
+
150
+ module.exports = { CLAUDE_RE, listClaude, reader, judgeSide, gate, describe };