@sabaiway/agent-workflow-kit 23.11.0 → 23.12.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/CHANGELOG.md CHANGED
@@ -4,6 +4,35 @@ Semantically versioned ([semver](https://semver.org)), newest first. The `versio
4
4
  is the current release. `upgrade` mode reads a project's `docs/ai/.workflow-version` and applies
5
5
  every `migrations/<version>-<slug>.md` newer than it, in semver order.
6
6
 
7
+ ## 23.12.0 — a skipped check keeps its whole reason in the upgrade report; three checkers open red output with the failure (AD-240)
8
+
9
+ **After `npx @sabaiway/agent-workflow-kit@latest init` and then `/agent-workflow-kit upgrade` in a new session, a
10
+ skipped check in the Recommendations report keeps its whole reason.** Before,
11
+ the advisor folded every skip reason into one line and cut it at 200 characters, in the text report and in `--json`,
12
+ so a remedy past the cut never reached you: the masks check's refusal of empty read-only files a sandbox left kept
13
+ only the first remedy of the first path.
14
+
15
+ - **The skip line stays one line.** When it loses anything, several lines folded into one or a cut, it ends with
16
+ `(the whole reason follows)` or `… (+N more chars; the whole reason follows)`, and the whole reason follows under
17
+ it, one ` | <line>` per line; `--json` carries the same lines as `whole`, an array of strings, beside `reason`.
18
+ A reason of one line that fits within the cap after escaping carries no `whole`, and one that holds no control
19
+ character, line or paragraph separator, or lone surrogate prints exactly as before. Every such character kept shows
20
+ as its JSON escape, so no line of a reason can pass for a line of the report.
21
+ - **The masks check states each remedy once.** Its refusal of fenced entries that are empty read-only files, and its
22
+ warning about fenced entries that became real paths, print one sentence per group with each path under it as a
23
+ quoted JSON string, so the remedy for litter a sandbox left (remove the file outside the sandbox and keep its line)
24
+ always reaches the report, with the exact path.
25
+ - The upgrade's Recommendations step tells the agent to relay every `|` line.
26
+ - **The release scan now fails, with exit 1 and its error block on standard output, on a target it cannot read (a
27
+ status that fails with anything but ENOENT), where it used to report that target as missing or skip it as an
28
+ unmatched glob.**
29
+ - **The control-byte gate, the release scan and the doc-parity lint open every red run of their text output with one
30
+ block on standard output**: the verdict line naming each class, each finding at its place, then its remedy lines
31
+ (one per class; the lint's one remedy line covers both its classes); nothing goes to standard error, and a usage mistake exits 2 with the usage. A green run prints what it printed before, and
32
+ `doc-parity --json` prints its one JSON document unchanged.
33
+ - Nothing to apply by hand: what changes is what the reports say. `init` still shows no skipped check; verdicts and
34
+ exit codes are unchanged but for the release scan's unreadable target.
35
+
7
36
  ## 23.11.0 — codex runs the newest model, gpt-6.2-sol, by default (AD-239)
8
37
 
9
38
  **After `/agent-workflow-kit upgrade` (or `init`), a host that sets neither a codex model nor an effort runs
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: agent-workflow-kit
3
3
  description: Deploy or upgrade a portable AI-agent memory-and-workflow system in any project. Use when the user wants to bootstrap `docs/ai/` + an entry-point `AGENTS.md` (+ `CLAUDE.md` alias) + cap/archive/index enforcement in a new or existing repo, set up the Memory Map and session protocols, install the docs-rotation pre-commit hook, or run `/agent-workflow-kit` / `/agent-workflow-kit upgrade`. Triggers on phrases like "set up the memory system", "deploy the AI workflow here", "bootstrap docs/ai", "upgrade the workflow". New to the epic, story and task tier? Run `/agent-workflow-kit tier`. A typed decision with a confidence from Jev? Run `/agent-workflow-kit jev`.
4
4
  disable-model-invocation: true
5
5
  metadata:
6
- version: '23.11.0'
6
+ version: '23.12.0'
7
7
  ---
8
8
 
9
9
  # agent-workflow-kit
package/capability.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schema": 1,
4
4
  "name": "agent-workflow-kit",
5
5
  "kind": "composition-root",
6
- "version": "23.11.0",
6
+ "version": "23.12.0",
7
7
  "provides": [],
8
8
  "roles": {},
9
9
  "detect": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sabaiway/agent-workflow-kit",
3
- "version": "23.11.0",
3
+ "version": "23.12.0",
4
4
  "description": "Portable, cross-agent memory & workflow for AI coding agents — Claude Code, Codex, Cursor, Devin Desktop. One command deploys an AGENTS.md entry point + docs/ai context with cap/archive/index enforcement into any repo.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -19,8 +19,9 @@ any byte in 0x00–0x08, 0x0B, 0x0C, 0x0E–0x1F or 0x7F refuses; TAB, LF and CR
19
19
  bytes; bytes at or above 0x80 are not judged (UTF-8 validity and C1 controls are not this tool's
20
20
  business). A finding names the path, the surface, the byte offset and the byte in hex; the render is
21
21
  injective — bytes decode as UTF-8 where valid, a control or line-separator code point (and a valid
22
- U+FFFD) renders as `\u{XXXX}`, an invalid byte as `\xNN`, a backslash as `\\` — so no output line carries a raw control
23
- byte or U+FFFD and two names differing only in an unrenderable byte render differently.
22
+ U+FFFD) renders as `\u{XXXX}`, an invalid byte as `\xNN`, a backslash as `\\` — so no line `main` returns carries a
23
+ raw control byte or U+FFFD (the guard's error block keeps the error's first line and stack as they are) and two
24
+ names differing only in an unrenderable byte render differently.
24
25
 
25
26
  **Binary by KIND, never by guess.** A path whose git attribute says `binary` or `-diff` has its
26
27
  CONTENT skipped by kind and is NAMED in the summary (one `git check-attr --stdin -z binary diff`
@@ -36,35 +37,40 @@ kind and counted — name judged, no content surface. On a host that materialise
36
37
  Run `node ${CLAUDE_SKILL_DIR}/tools/control-bytes.mjs [--check] [--cwd <dir>]` (`--cwd` anchors at
37
38
  that directory's work-tree root):
38
39
 
39
- 1. Plain run → the human report: the work-tree root, the counts (paths judged · skipped by attribute,
40
- each named · skipped by kind · findings), then every finding as one line
41
- `<path> <surface> offset <n>: 0x<hex>` (`(+N more)` when that surface carries more than one) —
42
- under the SAME exit table as `--check`: the plain run is never a silent 0.
43
- 2. **`--check`** → the gate spelling: the same report (counts, the named attribute skips, the
44
- finding lines), then the gate exit code. **Exit 0** clean. **Exit 1** on a finding OR on a refusal —
45
- refusals never pass and never skip silently, each with its own message: an UNREADABLE path
46
- (EACCES, EIO, a descriptor whose kind disagrees with the named kind — distinct from an ABSENT
47
- path git named that vanished before the read; a TRACKED absent path with the skip-worktree bit is
48
- a sparse checkout, skipped by kind and counted); a git command that fails, is killed by a signal or
49
- is not on PATH; an UNMERGED index; an EMPTY domain; a file over the read cap (16 MiB — read as at
50
- most cap+1 bytes on the descriptor, never trusting the fstat size, so a file that grows after the
51
- fstat still refuses; the message names the cap and the path); a git LOCATION that is not a work
52
- tree. The location is a closed table of six states shared with the fingerprint and index
53
- consumers through the kit's git-location leaf, judged on the REALPATH identity of the git dir,
54
- the common dir and the work-tree top under the ambient env against the discovery from cwd with
55
- every variable whose upper-cased name starts with `GIT_` removed (a case-insensitive host honours
56
- `git_dir` too): `work-tree` (all three agree) proceeds; `not-a-repository` (git
57
- itself answers not-a-git-repository, exit 128); `error` (ENOENT, a synchronous throw, a signal, a
58
- realpath that cannot resolve, any other non-zero or unparsable answer); `redirected` (any of the
59
- three differs — `GIT_WORK_TREE` at a second tree with the same git dir, or `GIT_COMMON_DIR` at a
60
- second repository); `no-work-tree` (the git
61
- dir agrees but `--show-toplevel` fails: bare, or cwd inside `.git`); `env-only` (the ambient env
62
- reaches a repository the stripped discovery does not) — each refuses by its own state name. A
63
- pre-commit hook's own env (`GIT_INDEX_FILE`, `GIT_PREFIX`, `GIT_CONFIG_PARAMETERS`,
64
- `GIT_EXEC_PATH`) agrees and passes: the check is agreement, never a variable ban. **Exit 2**
65
- usage — every operand is validated at parse; an unknown argument is usage. Every content read is
66
- descriptor-bound (open, fstat, read on the descriptor), never a path read that a symlink swap
67
- could redirect.
40
+ 1. Plain run → clean: the report (the work-tree root; paths judged · skipped by attribute · skipped by
41
+ kind · findings; one `skipped by attribute: <path>` line per such path). Red: ONE block on standard
42
+ output, nothing on standard error, under the SAME exit table as `--check` (never a silent 0): the
43
+ verdict line `control-bytes: FAIL —` naming each class present, with counts for control-byte findings
44
+ and paths not judged, each finding `<path>: <surface> offset <n>: 0x<hex>` (`(+N more)` for more), each
45
+ path not judged `<path>: <why>`, one `control-bytes: REMEDY —` line per class, then the report; the work
46
+ tree not judged stands alone (step 2: no count, nothing after its remedy). A path that is no plain place
47
+ (escaped, holding a colon, opening with a space, with an empty, `.` or `..` segment, equal to `control-bytes`, or matching the text before `: ` on a report line) stands at `.`, the path leading its text.
48
+ 2. **`--check`** → the gate spelling: the same output, then the gate exit code. **Exit 0** clean.
49
+ **Exit 1** on a finding OR on a refusal — refusals never pass and never skip silently, each with its
50
+ own message; a failed git query, an unmerged index, an empty domain or a location that is no work
51
+ tree is the work tree not judged: one finding at `.` carrying the message, one remedy line, nothing
52
+ after. The refusals: an UNREADABLE path (EACCES, EIO, a descriptor whose kind disagrees with the
53
+ named kind — distinct from an ABSENT path git named that vanished before the read; a TRACKED absent
54
+ path with the skip-worktree bit is a sparse checkout, skipped by kind and counted); a git command
55
+ that fails, is killed by a signal or is not on PATH; an UNMERGED index; an EMPTY domain; a file over
56
+ the read cap (16 MiB — read as at most cap+1 bytes on the descriptor, never trusting the fstat size,
57
+ so a file that grows after the fstat still refuses; the message names the cap and the path); a git
58
+ LOCATION that is not a work tree. The location is a closed table of six states shared with the
59
+ fingerprint and index consumers through the kit's git-location leaf, judged on the REALPATH identity
60
+ of the git dir, the common dir and the work-tree top under the ambient env against the discovery
61
+ from cwd with every variable whose upper-cased name starts with `GIT_` removed (a case-insensitive
62
+ host honours `git_dir` too): `work-tree` (all three agree) proceeds; `not-a-repository` (git itself
63
+ answers not-a-git-repository, exit 128); `error` (ENOENT, a synchronous throw, a signal, a realpath
64
+ that cannot resolve, any other non-zero or unparsable answer); `redirected` (any of the three
65
+ differs — `GIT_WORK_TREE` at a second tree with the same git dir, or `GIT_COMMON_DIR` at a second
66
+ repository); `no-work-tree` (the git dir agrees but `--show-toplevel` fails: bare, or cwd inside
67
+ `.git`); `env-only` (the ambient env reaches a repository the stripped discovery does not) — each
68
+ refuses by its own state name. A pre-commit hook's own env (`GIT_INDEX_FILE`, `GIT_PREFIX`,
69
+ `GIT_CONFIG_PARAMETERS`, `GIT_EXEC_PATH`) agrees and passes: the check is agreement, never a variable
70
+ ban. **Exit 2** usage — every operand is validated at parse; an unknown argument is usage: the verdict
71
+ line names what was wrong, then the usage text. An error the tool does not answer for prints the
72
+ guard's block (the verdict line naming the error, the remedy line, the stack), exit 1. Every content
73
+ read is descriptor-bound (open, fstat, read on the descriptor), never a path a symlink swap redirects.
68
74
  3. **Declare it as a gate — never without consent (AD-021/D9).** `node
69
75
  ${CLAUDE_SKILL_DIR}/tools/checker-gates.mjs --cwd <project> --only control-bytes --apply` writes
70
76
  this one entry while the kit offers it; without `--only control-bytes --apply` the same command
@@ -79,7 +85,7 @@ that directory's work-tree root):
79
85
  **Honest bounds (stated, accepted):** the work tree is judged at the moment of the read — a byte
80
86
  written after the run is caught on the next run, which is why the gate belongs in the pre-commit
81
87
  matrix; the attribute is the only "binary" signal, so a binary file with no attribute refuses until
82
- the project declares it; the tool reports and never edits — the remedy is the escape in source; a
88
+ the project declares it; the tool reports and never edits; a
83
89
  checkout PATH that is itself not valid UTF-8 is unreachable by any Node consumer (cwd is a string
84
90
  before git ever answers) and a non-UTF-8 LINKED git dir or common dir path refuses as `error` — a
85
91
  stated bound, not a case this tool judges; `O_NOFOLLOW` guards the
@@ -16,7 +16,7 @@ host/session facts* in `${CLAUDE_SKILL_DIR}/references/shared/report-footer.md`.
16
16
  Run `node ${CLAUDE_SKILL_DIR}/tools/recommendations.mjs --cwd <project-root> [--json]`:
17
17
 
18
18
  1. **`--cwd` is REQUIRED** — the target project is explicit, never inferred from the shell's current directory (a subdirectory invocation still advises on the named root).
19
- 2. **Verdict first (present-even-when-empty, opening at the `## Recommendations (agent-workflow)` header).** With everything optimal the body is exactly `no recommendations — flow optimal.` — the empty-state line ALONE is the verdict, zero added lines. Every other state opens the body with ONE verdict line composed from the frozen templates: `{K} item(s) need attention` leads when any item's severity is `attention` (a CONFIGURED declaration that is broken, drifted, degrading or invalid — the deployment needs review); `{N} optional recommendation(s), apply any you want` covers the `optional` class (offers to enable an unconfigured capability), led by `nothing is broken` ONLY when no item needs attention AND no probe check was skipped (a skipped probe could hide an attention-class problem — the claim never overreaches); `optimality NOT attested — {M} probe check(s) skipped` is appended last whenever probe checks were skipped. A kit item counts in neither class (applied with no pick): with only kit items and no skip the verdict is `nothing is broken` alone. (The `(s)` invariant form IS the pinned pluralization — no singular/plural branching.) Items render attention-first, each tagged `needs attention:` / `optional:`. A failed probe renders as a stated `⚠ skipped item …` line — never a crash, never a fabricated item.
19
+ 2. **Verdict first (present-even-when-empty, opening at the `## Recommendations (agent-workflow)` header).** With everything optimal the body is exactly `no recommendations — flow optimal.` — the empty-state line ALONE is the verdict, zero added lines. Every other state opens the body with ONE verdict line composed from the frozen templates: `{K} item(s) need attention` leads when any item's severity is `attention` (a CONFIGURED declaration that is broken, drifted, degrading or invalid — the deployment needs review); `{N} optional recommendation(s), apply any you want` covers the `optional` class (offers to enable an unconfigured capability), led by `nothing is broken` ONLY when no item needs attention AND no probe check was skipped (a skipped probe could hide an attention-class problem — the claim never overreaches); `optimality NOT attested — {M} probe check(s) skipped` is appended last whenever probe checks were skipped. A kit item counts in neither class (applied with no pick): with only kit items and no skip the verdict is `nothing is broken` alone. (The `(s)` invariant form IS the pinned pluralization — no singular/plural branching.) Items render attention-first, each tagged `needs attention:` / `optional:`. A failed probe renders as a stated `⚠ skipped item …` line, never a crash or a fabricated item; if the line lost anything, its whole reason follows on `|` lines: relay all.
20
20
  3. **The apply-through-agent lane — an explicit informed-consent checkpoint:** the agent applies chat and harness items on the chat yes, harness items by the consent route below, and kit items with no question by the kit route below. A chat item is never retried outside the sandbox and every failure of a chat step is a STOP. A user item is the user's own step, handed over as worded with its posture note (e.g. `source-size.id-squatter`). After presenting, OFFER to apply; the user selects items in plain language; for each selected item you **surface its posture note inline** where one exists (the per-item notes below cover exactly the risk-marked keys). For a chat item: the user **explicitly confirms**, and **only then** — **no command runs before confirmation** — do you run the rendered command. Do NOT infer safety from the presence or absence of an `--apply` flag: most chat items' rendered command IS the mutation and completes on that one run, **including a no-`--apply` mutation** such as `spec-adoption`'s `ensure-configs --reconcile --only specs` (it writes an edited spec-layer file with the bundled body with no question, its line naming where an edit meant to last goes). Some items instead render a **dry-run preview** that changes nothing and prints an explicit follow-up `--apply`/mutating command to run NEXT (e.g. the `gates-declaration` seeder): after the SAME confirmation you run that printed follow-up command — no second ask, no improvisation (each writer keeps its own consent semantics: previews, `--apply` flags, refusals) — except profile-gap, whose apply line runs with --apply appended only on a second yes over the relayed preview. For `worktrees-dir` you apply the grant on the chat yes after its check, like every harness item, with no hand step to wait for; its `recipe:` line's `ack-write` preview is the ack fallback, run only on the user's word that the host ignores the settings key, instead of the grant, and against a trusted host NO no ack renders.
21
21
  4. Registry strings (benefits + item texts) are frozen tool data, fact-true, ONE line under the pinned shape cap — posture/risk detail lives in the notes below at the consent moment, never inline in the overview. The dual velocity+security wording (`safer — blast radius bounded by the OS sandbox, not human attention`) rides ONLY the items with a real security delta (the autonomy render, the sandbox provisioning); the bridge-wrappers item claims **velocity only**.
22
22
 
@@ -32,7 +32,8 @@ export const ADVISOR_MATRIX_DOC = 'references/modes/dispatch.md';
32
32
  export const ADVISOR_MATRIX_BEGIN = '<!-- advisor-matrix:begin -->';
33
33
  export const ADVISOR_MATRIX_END = '<!-- advisor-matrix:end -->';
34
34
 
35
- export const readKitDoc = (rel) => readFileSync(resolve(KIT_ROOT, rel), 'utf8');
35
+ export const resolveKitDoc = (rel) => resolve(KIT_ROOT, rel);
36
+ export const readKitDoc = (rel) => readFileSync(resolveKitDoc(rel), 'utf8');
36
37
 
37
38
  // Both line endings are ordinary here. Splitting on '\n' alone leaves a trailing '\r' on every line
38
39
  // of a CRLF-authored doc, and the marker match survives it (it trims) while the exact header match
@@ -0,0 +1,73 @@
1
+ // Contract: docs/ai/specs/kit/advisor-skip.md
2
+ import { isLineUnsafe, jsonForLine } from '../source-size-refusal.mjs';
3
+
4
+ export const SKIP_REASON_CAP = 200;
5
+
6
+ const EMPTY = '';
7
+ const SPACE = ' ';
8
+ const LINE_BREAK = /\r\n|\r|\n/u;
9
+ const UNPRINTABLE_REASON = 'unprintable error value';
10
+ const WHOLE_REASON_FOLLOWS = 'the whole reason follows';
11
+ const FOLD_NOTE = ` (${WHOLE_REASON_FOLLOWS})`;
12
+ const CUT_NOTE_START = '\u2026 (+';
13
+ const CUT_NOTE_END = ` more chars; ${WHOLE_REASON_FOLLOWS})`;
14
+ const SKIP_LEAD = ' \u26a0 skipped item ';
15
+ const PROBE_FAILED = ' \u2014 probe failed: ';
16
+ const CONTINUATION_LEAD = ' |';
17
+ const START_INDEX = 0;
18
+ const NEXT_INDEX_OFFSET = 1;
19
+ const LAST_INDEX = -1;
20
+ const NOT_FOUND = -1;
21
+
22
+ const readErrorText = (error) => {
23
+ try {
24
+ return String(error?.message ?? error);
25
+ } catch {
26
+ return UNPRINTABLE_REASON;
27
+ }
28
+ };
29
+
30
+ const escapeCodePoint = (codePoint) => isLineUnsafe(codePoint)
31
+ ? jsonForLine(codePoint).slice(NEXT_INDEX_OFFSET, LAST_INDEX)
32
+ : codePoint;
33
+
34
+ const escapeLine = (line) => Array.from(line, escapeCodePoint).join(EMPTY);
35
+ const hasText = (line) => line.trim() !== EMPTY;
36
+ const formatCutNote = (droppedLength) => `${CUT_NOTE_START}${droppedLength}${CUT_NOTE_END}`;
37
+
38
+ const cutSummary = (summary, pieces) => {
39
+ const prefixLengths = [START_INDEX];
40
+ for (const piece of pieces.slice(START_INDEX, SKIP_REASON_CAP)) {
41
+ prefixLengths.push(prefixLengths.at(LAST_INDEX) + piece.length);
42
+ }
43
+ const prefixLength = prefixLengths.findLast((length) =>
44
+ length + formatCutNote(summary.length - length).length <= SKIP_REASON_CAP
45
+ ) ?? START_INDEX;
46
+ return summary.slice(START_INDEX, prefixLength) + formatCutNote(summary.length - prefixLength);
47
+ };
48
+
49
+ export const composeSkip = (key, error) => {
50
+ const lines = readErrorText(error).split(LINE_BREAK);
51
+ const firstLineIndex = lines.findIndex(hasText);
52
+ if (firstLineIndex === NOT_FOUND) return { key, reason: EMPTY };
53
+
54
+ const lastLineIndex = lines.findLastIndex(hasText);
55
+ const countingLines = lines.slice(firstLineIndex, lastLineIndex + NEXT_INDEX_OFFSET);
56
+ const trimmedLines = countingLines.map((line) => line.trim()).filter(Boolean);
57
+ const [, secondLine] = trimmedLines;
58
+ const isFolded = secondLine !== undefined;
59
+ const pieces = Array.from(trimmedLines.join(SPACE), escapeCodePoint);
60
+ const summary = pieces.join(EMPTY);
61
+ if (!isFolded && summary.length <= SKIP_REASON_CAP) return { key, reason: summary };
62
+
63
+ const reason = isFolded && summary.length + FOLD_NOTE.length <= SKIP_REASON_CAP
64
+ ? summary + FOLD_NOTE
65
+ : cutSummary(summary, pieces);
66
+ const whole = countingLines.map((line) => hasText(line) ? escapeLine(line) : EMPTY);
67
+ return { key, reason, whole };
68
+ };
69
+
70
+ export const renderSkip = ({ key, reason, whole }) => [
71
+ `${SKIP_LEAD}${escapeLine(key)}${PROBE_FAILED}${reason}`,
72
+ ...(whole?.map((entry) => entry === EMPTY ? CONTINUATION_LEAD : `${CONTINUATION_LEAD}${SPACE}${entry}`) ?? []),
73
+ ];
@@ -12,6 +12,8 @@
12
12
 
13
13
  import { closeSync, constants as fsConstants, fstatSync, lstatSync, openSync, readSync, readlinkSync, realpathSync, statSync } from 'node:fs';
14
14
  import { spawnSync } from 'node:child_process';
15
+ import { composeUsageRefusal } from '../references/scripts/shared/index.mjs';
16
+ import { composeCheckerBlock, runCheckerTail } from './checker-block/index.mjs';
15
17
  import { isDirectRun } from './direct-run.mjs';
16
18
  import { probeRegularFileNoFollow, readFileBytesNoFollowCapped } from './fs-read-nofollow.mjs';
17
19
  import { GIT_MAX_BUFFER, parseIndexEntries, resolveGitLocation, withGitPath } from './git-env.mjs';
@@ -36,15 +38,25 @@ const USAGE = `usage: node control-bytes.mjs [--check] [--cwd <dir>]
36
38
  --check the gate spelling; the plain run prints the same report and shares the exit table
37
39
  exit 0 clean · 1 a finding or a refusal · 2 usage`;
38
40
 
41
+ const CHECKER_NAME = 'control-bytes';
42
+ const WORK_TREE_REMEDY = 'clear the cause the finding above names, then re-run';
43
+ const CONTROL_BYTE_REMEDY = 'rename each path whose name contains a refused byte, retarget each symlink whose target contains a refused byte, replace every refused byte in text content with an escape in source, and mark any affected binary file binary in .gitattributes, then re-run';
44
+ const PATH_REMEDY = 'settle each path above as its finding says, then re-run';
45
+ const UNEXPECTED_REMEDY = 'fix the cause the stack below names, then re-run';
46
+
39
47
  const NUL = Buffer.from([0]);
40
48
  const render = renderPathForDisplay;
41
49
  // Every DYNAMIC diagnostic (a location cause, git stderr, an fs error code, a user argument) rides
42
50
  // the same renderer as paths before it reaches a line — SAFE (never a raw byte or U+FFFD), while
43
51
  // injectivity is promised for NAMES only: a string-originated diagnostic folds invalid bytes first.
44
52
  const safe = (text) => render(Buffer.isBuffer(text) ? text : Buffer.from(String(text), 'utf8'));
45
- const refusalLine = (message) => `control-bytes: REFUSED — ${message}`;
46
- const absent = (path, tracked) => `${render(path)}: absent (${tracked ? 'tracked but missing from the work tree — stage the deletion with git rm or git add -A, or it' : 'git named it, it'} vanished before the read)`;
47
- const unreadable = (path, why) => `${render(path)}: unreadable (${safe(why)})`;
53
+ const refuseWorkTree = (root, text) => ({ code: 1, lines: composeCheckerBlock({
54
+ name: CHECKER_NAME, root, failed: 'the work tree could not be judged',
55
+ findings: [{ path: '.', text }], remedies: [WORK_TREE_REMEDY],
56
+ }) });
57
+ const pathFinding = (path, text) => ({ path: render(path), text });
58
+ const absent = (path, tracked) => pathFinding(path, `absent (${tracked ? 'tracked but missing from the work tree — stage the deletion with git rm or git add -A, or it' : 'git named it, it'} vanished before the read)`);
59
+ const unreadable = (path, why) => pathFinding(path, `unreadable (${safe(why)})`);
48
60
  const hexByte = (byte) => `0x${byte.toString(16).padStart(2, '0')}`;
49
61
  const errorCode = (err) => err?.code ?? err?.message ?? String(err);
50
62
 
@@ -123,34 +135,34 @@ export const main = (argv, deps = {}) => {
123
135
  const run = deps.spawn ?? spawnSync;
124
136
  const env = deps.env ?? process.env;
125
137
  const opts = parseArgs(argv, io);
126
- if (opts.error) return { code: 2, lines: [`control-bytes: usage — ${opts.error}`, USAGE] };
138
+ if (opts.error) return { code: 2, lines: composeUsageRefusal({ name: CHECKER_NAME, failed: opts.error, usage: USAGE }) };
127
139
  const cwd = opts.cwd ?? deps.cwd ?? process.cwd();
128
140
  const location = resolveGitLocation(cwd, { spawn: run, env, realpath: io.realpath });
129
- if (location.state !== 'work-tree') return { code: 1, lines: [refusalLine(`the git location is ${location.state} — ${safe(location.cause)}`)] };
141
+ if (location.state !== 'work-tree') return refuseWorkTree(cwd, `the git location is ${location.state} — ${safe(location.cause)}`);
130
142
  const top = location.top;
131
143
  const git = (args, input, ok) => gitQuery(run, args, { cwd: top, env, input }, ok);
132
144
  const tracked = git(TRACKED_ARGV);
133
- if (tracked.failure) return { code: 1, lines: [refusalLine(tracked.failure)] };
145
+ if (tracked.failure) return refuseWorkTree(top, tracked.failure);
134
146
  const entries = parseIndexEntries(tracked.stdout);
135
147
  const unmerged = entries.filter((e) => e.stage !== 0).length;
136
- if (unmerged > 0) return { code: 1, lines: [refusalLine(`the git index is UNMERGED (${unmerged} conflict-stage entr(ies)) — resolve the conflict, then re-run`)] };
148
+ if (unmerged > 0) return refuseWorkTree(top, `the git index is UNMERGED (${unmerged} conflict-stage entr(ies)) — resolve the conflict, then re-run`);
137
149
  const others = git(UNTRACKED_ARGV);
138
- if (others.failure) return { code: 1, lines: [refusalLine(others.failure)] };
150
+ if (others.failure) return refuseWorkTree(top, others.failure);
139
151
  const domain = [...entries.map((e) => ({ path: e.path, mode: e.mode })), ...splitZ(others.stdout).map((path) => ({ path, mode: null }))]
140
152
  .sort((a, b) => Buffer.compare(a.path, b.path));
141
- if (domain.length === 0) return { code: 1, lines: [refusalLine(`the domain is EMPTY — no tracked and no untracked-not-ignored path under ${render(Buffer.from(top))}`)] };
153
+ if (domain.length === 0) return refuseWorkTree(top, `the domain is EMPTY — no tracked and no untracked-not-ignored path under ${render(Buffer.from(top))}`);
142
154
  const attributes = git(ATTRIBUTES_ARGV, Buffer.concat(domain.flatMap((d) => [d.path, NUL])));
143
- if (attributes.failure) return { code: 1, lines: [refusalLine(attributes.failure)] };
155
+ if (attributes.failure) return refuseWorkTree(top, attributes.failure);
144
156
  const skipByAttribute = attributeSkips(attributes.stdout);
145
157
  // core.symlinks: exit 1 = unset = git's default (true); `false` = the host materialises a tracked
146
158
  // symlink as a regular file holding the target bytes — refusing it there would refuse forever.
147
159
  const symlinks = git(SYMLINKS_ARGV, undefined, [0, 1]);
148
- if (symlinks.failure) return { code: 1, lines: [refusalLine(symlinks.failure)] };
160
+ if (symlinks.failure) return refuseWorkTree(top, symlinks.failure);
149
161
  const symlinksMaterialised = symlinks.stdout.toString('utf8').trim() === 'false';
150
162
  // Sparse checkouts: a tracked path whose skip-worktree bit is set (`ls-files -v`, a tag that
151
163
  // uppercases to S — core-evidence's rule) may be ABSENT by design: a counted skip, never a refusal.
152
164
  const sparse = git(SPARSE_ARGV);
153
- if (sparse.failure) return { code: 1, lines: [refusalLine(sparse.failure)] };
165
+ if (sparse.failure) return refuseWorkTree(top, sparse.failure);
154
166
  const sparseSkip = new Set();
155
167
  for (const record of splitZ(sparse.stdout)) {
156
168
  if (record.length > 2 && String.fromCharCode(record[0]).toUpperCase() === 'S') sparseSkip.add(record.subarray(2).toString('hex'));
@@ -168,7 +180,7 @@ export const main = (argv, deps = {}) => {
168
180
  if (first === -1) first = i;
169
181
  count += 1;
170
182
  }
171
- if (first !== -1) findings.push(`${render(path)} ${surface} offset ${first}: ${hexByte(bytes[first])}${count > 1 ? ` (+${count - 1} more)` : ''}`);
183
+ if (first !== -1) findings.push(pathFinding(path, `${surface} offset ${first}: ${hexByte(bytes[first])}${count > 1 ? ` (+${count - 1} more)` : ''}`));
172
184
  };
173
185
  // An ABSENT path: a sparse (skip-worktree) tracked one is a counted skip; every other refuses.
174
186
  const settleAbsent = (path, tracked) => {
@@ -181,7 +193,7 @@ export const main = (argv, deps = {}) => {
181
193
  if (read.bytes) judge(read.bytes, surface, path);
182
194
  return true;
183
195
  }
184
- if (read.outcome === 'over-cap') refusals.push(`${render(path)}: over the read cap (${READ_CAP} bytes) — the gate read cap+1 bytes on the descriptor and stopped; ${surface === 'content' ? 'declare the path binary in .gitattributes or shrink it' : 'restore the link or shorten its target'}`);
196
+ if (read.outcome === 'over-cap') refusals.push(pathFinding(path, `over the read cap (${READ_CAP} bytes) — the gate read cap+1 bytes on the descriptor and stopped; ${surface === 'content' ? 'declare the path binary in .gitattributes or shrink it' : 'restore the link or shorten its target'}`));
185
197
  else if (read.outcome === 'absent') settleAbsent(path, tracked);
186
198
  else if (read.outcome === 'foreign') refusals.push(unreadable(path, `a ${read.className} where git named a ${named}`));
187
199
  else refusals.push(unreadable(path, read.code));
@@ -251,14 +263,25 @@ export const main = (argv, deps = {}) => {
251
263
  `control-bytes: work tree ${render(Buffer.from(top))}`,
252
264
  `paths judged: ${domain.length} · skipped by attribute: ${skippedByAttribute.length} · skipped by kind: ${skippedByKind} · findings: ${findings.length}`,
253
265
  ...skippedByAttribute.map((path) => `skipped by attribute: ${render(path)}`),
254
- ...findings,
255
- ...refusals.map(refusalLine),
256
266
  ];
257
- return { code: findings.length > 0 || refusals.length > 0 ? 1 : 0, lines };
267
+ const classes = [];
268
+ const remedies = [];
269
+ if (findings.length) {
270
+ classes.push(`${findings.length} control-byte finding(s)`);
271
+ remedies.push(CONTROL_BYTE_REMEDY);
272
+ }
273
+ if (refusals.length) {
274
+ classes.push(`${refusals.length} path(s) not judged`);
275
+ remedies.push(PATH_REMEDY);
276
+ }
277
+ if (!classes.length) return { code: 0, lines };
278
+ return { code: 1, lines: composeCheckerBlock({
279
+ name: CHECKER_NAME, root: top, failed: classes.join('; '),
280
+ findings: [...findings, ...refusals], remedies, after: lines,
281
+ }) };
258
282
  };
259
283
 
260
284
  if (isDirectRun(import.meta.url)) {
261
- const result = main(process.argv.slice(2));
262
- (result.code === 2 ? process.stderr : process.stdout).write(`${result.lines.join('\n')}\n`);
263
- process.exitCode = result.code;
285
+ runCheckerTail({ name: CHECKER_NAME, exitCode: 1, remedy: UNEXPECTED_REMEDY },
286
+ () => main(process.argv.slice(2)), process);
264
287
  }
@@ -0,0 +1,46 @@
1
+ import { composeCheckerBlock } from '../checker-block/index.mjs';
2
+ import { resolveKitDoc } from '../advisor-matrix.mjs';
3
+
4
+ export const CHECKER_NAME = 'doc-parity';
5
+ const DRIFT_REMEDY = 'update each doc above in the same edit as the code it binds, then re-run';
6
+
7
+ const structureLine = (structure) =>
8
+ ` ${structure.ok ? '✓' : '✗'} ${structure.constant} → ${structure.files[0].rel}${structure.ok ? '' : ` — ${structure.files[0].reason}`}`;
9
+
10
+ export const formatHuman = (results, structure) => {
11
+ const lines = ['doc-parity — code constants ⟷ references/modes/*.md contract (read-only, BUGFREE-3)'];
12
+ for (const r of results) {
13
+ for (const f of r.files) {
14
+ lines.push(` ${f.ok ? '✓' : '✗'} ${r.constant} → ${f.rel}${f.ok ? '' : ` — ${f.reason}`}`);
15
+ }
16
+ }
17
+ lines.push(structureLine(structure));
18
+ const failed = results.flatMap((r) => r.files.filter((f) => !f.ok).map((f) => `${r.constant} @ ${f.rel}`));
19
+ // The summary verdict derives from BOTH halves. A PASS token computed from the bindings alone read
20
+ // as a green report while the structure check below it said FAIL — the one surface that lied.
21
+ const green = failed.length === 0 && structure.ok;
22
+ lines.push(` check: ${green ? 'PASS' : 'FAIL'} — ${failed.length === 0 ? `${results.length} binding(s) consistent` : `${failed.length} drifted binding(s): ${failed.join('; ')}`}, structure ${structure.ok ? 'PASS' : 'FAIL'}`);
23
+ return lines.join('\n');
24
+ };
25
+
26
+ export const formatCheckPass = (results) =>
27
+ `doc-parity check: PASS — ${results.length} binding(s) consistent; the advisor matrix structure corresponds`;
28
+
29
+ const driftFinding = (constant, { rel, reason }) => ({
30
+ path: resolveKitDoc(rel), text: `${constant} — ${reason}`,
31
+ });
32
+
33
+ export const composeDriftBlock = ({ results, structure, cwd }) => {
34
+ const drifted = results.filter(({ ok }) => !ok);
35
+ const classes = [];
36
+ if (drifted.length) classes.push(`${drifted.length} drifted binding(s)`);
37
+ const findings = drifted.flatMap(({ constant, files }) =>
38
+ files.filter(({ ok }) => !ok).map((file) => driftFinding(constant, file)));
39
+ if (!structure.ok) {
40
+ classes.push('the advisor matrix structure drifted');
41
+ findings.push(driftFinding(structure.constant, structure.files[0]));
42
+ }
43
+ return composeCheckerBlock({
44
+ name: CHECKER_NAME, root: cwd, failed: classes.join('; '), findings, remedies: [DRIFT_REMEDY],
45
+ });
46
+ };
@@ -19,7 +19,11 @@
19
19
  // Read-only: never writes, never commits, never runs a subscription CLI, spawns nothing. Dependency-
20
20
  // free, Node >= 22. No side effects on import (the isDirectRun idiom).
21
21
 
22
+ import { resolve } from 'node:path';
23
+ import { composeUsageRefusal } from '../references/scripts/shared/index.mjs';
22
24
  import { EXIT as DOCTOR_EXIT, STATUS as DOCTOR_STATUS, TRUSTED_DIRS as DOCTOR_TRUSTED_DIRS } from './autonomy-doctor.mjs';
25
+ import { runCheckerTail } from './checker-block/index.mjs';
26
+ import { CHECKER_NAME, formatHuman, formatCheckPass, composeDriftBlock } from './doc-parity/index.mjs';
23
27
  import {
24
28
  RECOMMENDATIONS_SECTION_HEADER,
25
29
  RECOMMENDATIONS_EMPTY_LINE,
@@ -96,9 +100,6 @@ const STATUS_DOC = 'references/modes/status.md';
96
100
  // its table in, and a second copy here is exactly the drift this lint exists to catch.
97
101
  const DISPATCH_DOC = ADVISOR_MATRIX_DOC;
98
102
 
99
- // A typed usage failure (exit 2) for the CLI parser — the codebase's typed-error idiom (no classes).
100
- const usageFail = (message) => Object.assign(new Error(message), { exitCode: 2 });
101
-
102
103
  // ── the closed binding registry ──────────────────────────────────────────────────────
103
104
  // Each binding: { constant, value (live), token (value rendered into the doc's exact phrasing),
104
105
  // files[] (the contract docs that MUST carry the token) }. The token phrasings match the current
@@ -281,30 +282,12 @@ export { ADVISOR_MATRIX_DOC, ADVISOR_MATRIX_BEGIN, ADVISOR_MATRIX_END, parseAdvi
281
282
  // relative to the kit root.
282
283
  export const checkParity = (bindings = BINDINGS, readText = defaultReadText) => bindings.map((b) => checkBinding(b, readText));
283
284
 
284
- // ── rendering ───────────────────────────────────────────────────────────────────────
285
- const structureLine = (structure) =>
286
- ` ${structure.ok ? '✓' : '✗'} ${structure.constant} → ${structure.files[0].rel}${structure.ok ? '' : ` — ${structure.files[0].reason}`}`;
287
-
288
- const formatHuman = (results, structure) => {
289
- const lines = ['doc-parity — code constants ⟷ references/modes/*.md contract (read-only, BUGFREE-3)'];
290
- for (const r of results) {
291
- for (const f of r.files) {
292
- lines.push(` ${f.ok ? '✓' : '✗'} ${r.constant} → ${f.rel}${f.ok ? '' : ` — ${f.reason}`}`);
293
- }
294
- }
295
- lines.push(structureLine(structure));
296
- const failed = results.flatMap((r) => r.files.filter((f) => !f.ok).map((f) => `${r.constant} @ ${f.rel}`));
297
- // The summary verdict derives from BOTH halves. A PASS token computed from the bindings alone read
298
- // as a green report while the structure check below it said FAIL — the one surface that lied.
299
- const green = failed.length === 0 && structure.ok;
300
- lines.push(` check: ${green ? 'PASS' : 'FAIL'} — ${failed.length === 0 ? `${results.length} binding(s) consistent` : `${failed.length} drifted binding(s): ${failed.join('; ')}`}, structure ${structure.ok ? 'PASS' : 'FAIL'}`);
301
- return lines.join('\n');
302
- };
285
+ const UNEXPECTED_REMEDY = 'fix the cause the stack below names, then re-run';
286
+ const USAGE = 'Usage:\n node doc-parity.mjs [--check | --json]';
303
287
 
304
288
  const HELP = `doc-parity — deterministic doc-drift lint for the agent-workflow family (BUGFREE-3 / AD-049).
305
289
 
306
- Usage:
307
- node doc-parity.mjs [--check | --json]
290
+ ${USAGE}
308
291
 
309
292
  A CLOSED, exported registry binds each live code constant — the autonomy-doctor contract (the EXIT
310
293
  table, the status tokens, the trusted-dir allowlist), the recommendations/upgrade presentation
@@ -346,32 +329,29 @@ Read-only: never writes, never commits, spawns nothing. Exit codes: 0 pass (or p
346
329
  const KNOWN_ARGS = new Set(['--help', '-h', '--check', '--json']);
347
330
 
348
331
  export const main = (argv, ctx = {}) => {
332
+ if (argv.includes('--help') || argv.includes('-h')) return { code: 0, stdout: HELP, stderr: '' };
333
+ const unknown = argv.find((argument) => !KNOWN_ARGS.has(argument));
334
+ if (unknown !== undefined) {
335
+ const lines = composeUsageRefusal({ name: CHECKER_NAME, failed: `unknown argument: ${JSON.stringify(unknown)}`, usage: USAGE });
336
+ return { code: 2, stdout: lines.join('\n'), stderr: '' };
337
+ }
349
338
  const readText = ctx.readText ?? defaultReadText;
350
- try {
351
- if (argv.includes('--help') || argv.includes('-h')) return { code: 0, stdout: HELP, stderr: '' };
352
- const unknown = argv.find((a) => !KNOWN_ARGS.has(a));
353
- if (unknown !== undefined) throw usageFail(`unknown argument: ${unknown}`);
354
- const results = checkParity(BINDINGS, readText);
355
- const structure = checkMatrixStructure(readText);
356
- const failed = results.filter((r) => !r.ok);
357
- const green = failed.length === 0 && structure.ok;
358
- if (argv.includes('--json')) {
359
- return { code: argv.includes('--check') && !green ? 1 : 0, stdout: JSON.stringify({ results, structure, ok: green }, null, 2), stderr: '' };
360
- }
361
- if (argv.includes('--check')) {
362
- const bindingReason = failed.length === 0 ? `${results.length} binding(s) consistent` : `${failed.length} drifted binding(s): ${failed.map((r) => r.constant).join(', ')} — update the contract doc(s) in the SAME edit as the code`;
363
- const structureReason = structure.ok ? 'the advisor matrix structure corresponds' : `the advisor matrix structure DRIFTED — ${structure.files[0].reason}`;
364
- return { code: green ? 0 : 1, stdout: `doc-parity check: ${green ? 'PASS' : 'FAIL'} — ${bindingReason}; ${structureReason}`, stderr: '' };
365
- }
366
- return { code: 0, stdout: formatHuman(results, structure), stderr: '' };
367
- } catch (err) {
368
- return { code: err.exitCode ?? 1, stdout: '', stderr: `doc-parity: ${err.message}` };
339
+ const results = checkParity(BINDINGS, readText);
340
+ const structure = checkMatrixStructure(readText);
341
+ const green = results.every(({ ok }) => ok) && structure.ok;
342
+ const check = argv.includes('--check');
343
+ if (argv.includes('--json')) {
344
+ return { code: check && !green ? 1 : 0, stdout: JSON.stringify({ results, structure, ok: green }, null, 2), stderr: '' };
345
+ }
346
+ if (check) {
347
+ if (green) return { code: 0, stdout: formatCheckPass(results), stderr: '' };
348
+ const lines = composeDriftBlock({ results, structure, cwd: resolve(ctx.cwd ?? process.cwd()) });
349
+ return { code: 1, stdout: lines.join('\n'), stderr: '' };
369
350
  }
351
+ return { code: 0, stdout: formatHuman(results, structure), stderr: '' };
370
352
  };
371
353
 
372
354
  if (isDirectRun(import.meta.url)) {
373
- const r = main(process.argv.slice(2));
374
- if (r.stdout) process.stdout.write(r.stdout.endsWith('\n') ? r.stdout : `${r.stdout}\n`);
375
- if (r.stderr) process.stderr.write(r.stderr.endsWith('\n') ? r.stderr : `${r.stderr}\n`);
376
- process.exitCode = r.code;
355
+ runCheckerTail({ name: CHECKER_NAME, exitCode: 1, remedy: UNEXPECTED_REMEDY },
356
+ () => main(process.argv.slice(2)), process);
377
357
  }
@@ -54,6 +54,7 @@ import { isDirectRun } from './direct-run.mjs';
54
54
  import { ACTIVITIES, resolveActivityRecipe, composeReadiness, safeLine } from './recipes.mjs';
55
55
  import { surveyFamily, surveyGateHook } from './family-registry.mjs';
56
56
  import { probeSandboxMasks, needsMasksApply, patternToRel } from './sandbox-masks.mjs';
57
+ import { SKIP_REASON_CAP, composeSkip, renderSkip } from './advisor-skip/index.mjs';
57
58
  import { shellQuoteArg } from './review-state.mjs';
58
59
  import { isFinalCapableDeclaration } from './run-gates.mjs';
59
60
  import { loadDeclaration, canonicalCheckerGates, coverageProducerPrecedes, isKitOwnedCheckerGate, movableEarlierForm } from './gates-declaration.mjs';
@@ -323,7 +324,7 @@ export const WHATS = Object.freeze({
323
324
 
324
325
  // ── the shape contract (D2): registry strings AND composed items stay one line under the cap ────
325
326
  export const ITEM_LINE_CAP = 140;
326
- export const SKIP_REASON_CAP = 200;
327
+ export { SKIP_REASON_CAP };
327
328
 
328
329
  const oneLineOf = (text) => String(text).replace(/\s*[\r\n]+\s*/g, ' ').trim();
329
330
  // Scalar truncation-with-count — a capped value states what it dropped, never a silent cut.
@@ -1628,9 +1629,7 @@ export const buildRecommendations = ({ cwd, deps = {} } = {}) => {
1628
1629
  const root = resolve(cwd);
1629
1630
  const items = [];
1630
1631
  const skips = [];
1631
- // Skip reasons ride arbitrary Error.messages — normalized to ONE line and length-capped so a
1632
- // multiline or oversized message can never rebuild a prose wall (D2).
1633
- const skip = (key, err) => skips.push({ key, reason: truncatedTo(oneLineOf(err?.message ?? String(err)), SKIP_REASON_CAP) });
1632
+ const skip = (key, err) => skips.push(composeSkip(key, err)); // docs/ai/specs/kit/advisor-skip.md
1634
1633
  // The runtime shape backstop (D2): every COMPOSED item is validated at construction — a
1635
1634
  // violation surfaces through the stated-skip lane, never a crash, never a rendered violation.
1636
1635
  // `variant` defaults to the item key; a per-site arm passes its `<key>.<variant>` entry. It is
@@ -1723,7 +1722,7 @@ export const formatRecommendations = ({ items, skips }) => {
1723
1722
  });
1724
1723
  }
1725
1724
  for (const s of skips) {
1726
- lines.push(` ⚠ skipped item ${s.key} — probe failed: ${s.reason}`);
1725
+ for (const line of renderSkip(s)) lines.push(line);
1727
1726
  }
1728
1727
  return lines.join('\n');
1729
1728
  };
@@ -1740,7 +1739,8 @@ facts or its alternative, such as the bridge-tier missing-entries line or
1740
1739
  the worktrees-dir ack fallback) · the harness or kit check line · the exact consent-gated apply one-liner}. --cwd is
1741
1740
  REQUIRED (the target project is explicit, never inferred from the shell's current directory). The
1742
1741
  section renders present-even-when-empty ("${RECOMMENDATIONS_EMPTY_LINE}"); a probe failure is a
1743
- stated skipped-item line. Apply lines are cwd-independent (absolute tool paths, a pinned --cwd;
1742
+ stated skipped-item line, its whole reason below it whenever that line lost anything.
1743
+ Apply lines are cwd-independent (absolute tool paths, a pinned --cwd;
1744
1744
  the doctor item pins via a cd prefix; the ONE exception is the set-autonomy item — a
1745
1745
  conversational skill invocation labeled "run IN the target project") and preserve each writer's
1746
1746
  own consent semantics. The consented velocity-profile --bridge-tier seeds used bridges' code-mode
@@ -0,0 +1,30 @@
1
+ import { composeCheckerBlock } from '../checker-block/index.mjs';
2
+
3
+ export const CHECKER_NAME = 'release-scan';
4
+ export const UNEXPECTED_REMEDY = 'fix the cause the stack below names, then re-run';
5
+ const TARGET_REMEDY = 'fix or drop each mis-aimed target above as its finding says, then re-run';
6
+ const SCAN_REMEDY = 'remove each attribution, reviewer identity, and hardcoded version claim above, then re-run';
7
+
8
+ export const composeScanBlock = ({ cwd, misaimed, findings, after }) => {
9
+ const classes = [];
10
+ const remedies = [];
11
+ if (misaimed.length) {
12
+ classes.push(`${misaimed.length} mis-aimed target(s)`);
13
+ remedies.push(TARGET_REMEDY);
14
+ }
15
+ if (findings.length) {
16
+ classes.push(`${findings.length} finding(s)`);
17
+ remedies.push(SCAN_REMEDY);
18
+ }
19
+ return composeCheckerBlock({
20
+ name: CHECKER_NAME,
21
+ root: cwd,
22
+ failed: classes.join('; '),
23
+ findings: [
24
+ ...misaimed.map(({ path, status, remedy }) => ({ path, text: `${status} — ${remedy}` })),
25
+ ...findings.map(({ file, line, kind, detail }) => ({ path: file, line, text: `${kind} — ${detail}` })),
26
+ ],
27
+ remedies,
28
+ after,
29
+ });
30
+ };
@@ -10,9 +10,12 @@
10
10
  //
11
11
  // Pure `scanText` for unit fixtures; `scanPaths`/CLI for the release tree. Dependency-free, Node >= 22.
12
12
 
13
- import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
13
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
14
14
  import { join, extname, basename, resolve } from 'node:path';
15
+ import { composeUsageRefusal } from '../references/scripts/shared/index.mjs';
16
+ import { runCheckerTail } from './checker-block/index.mjs';
15
17
  import { isDirectRun } from './direct-run.mjs';
18
+ import { CHECKER_NAME, UNEXPECTED_REMEDY, composeScanBlock } from './release-scan/index.mjs';
16
19
 
17
20
  export const ALLOWLIST = [
18
21
  'codex-cli-bridge',
@@ -204,16 +207,25 @@ export const TARGET = Object.freeze({
204
207
 
205
208
  const GLOB_META_RE = /[*?[\]]/;
206
209
 
210
+ const statTarget = (path) => {
211
+ try {
212
+ return statSync(path);
213
+ } catch (error) {
214
+ if (error?.code !== 'ENOENT') throw error;
215
+ return null;
216
+ }
217
+ };
218
+
207
219
  // PURE-ish (one fs read): classify ONE caller-named target and collect the files it contributes.
208
220
  // Every zero-contribution status names its own cause, so the refusal can state the remedy rather
209
221
  // than a bare count (a count without a location is the defect class this family bans).
210
222
  export const classifyTarget = (path) => {
211
- if (!existsSync(path)) {
223
+ const st = statTarget(path);
224
+ if (st === null) {
212
225
  return GLOB_META_RE.test(path)
213
226
  ? { path, status: TARGET.unmatchedGlob, files: [] }
214
227
  : { path, status: TARGET.missing, files: [] };
215
228
  }
216
- const st = statSync(path);
217
229
  const name = basename(path);
218
230
  if (st.isDirectory() && EXCLUDE_DIR_NAMES.has(name)) return { path, status: TARGET.excluded, files: [] };
219
231
  if (st.isFile() && (EXCLUDE_FILE_NAMES.has(name) || !TEXT_EXT.has(extname(path)) || path.endsWith('.tgz'))) {
@@ -244,34 +256,43 @@ const findingsIn = (targets, opts) => {
244
256
 
245
257
  export const scanPaths = (paths, opts = {}) => findingsIn(paths.map((p) => classifyTarget(resolve(p))), opts);
246
258
 
247
- export const main = (argv) => {
259
+ const USAGE = 'usage: release-scan.mjs [--report] <path>...';
260
+
261
+ export const runScan = (argv, cwd = process.cwd()) => {
248
262
  const reportOnly = argv.includes('--report');
249
263
  const paths = argv.filter((a) => a !== '--report');
250
264
  if (paths.length === 0) {
251
- console.error('usage: release-scan.mjs [--report] <path>...');
252
- return 2;
265
+ return { code: 2, lines: composeUsageRefusal({ name: CHECKER_NAME, failed: 'no path was given to scan', usage: USAGE }) };
253
266
  }
254
- const targets = paths.map((p) => classifyTarget(resolve(p)));
255
- for (const target of targets) {
256
- if (target.status === TARGET.unmatchedGlob) {
257
- console.log(`[release-scan] skipped ${target.path} — no file matched this glob (an optional target, stated not silent).`);
258
- }
259
- }
260
- const misaimed = targets.filter((target) => TARGET_REMEDY[target.status] !== undefined);
261
- for (const target of misaimed) {
262
- console.log(`[release-scan] target ${target.path} contributed NO file (${target.status}) — ${TARGET_REMEDY[target.status]}`);
267
+ const targets = paths.map((path) => classifyTarget(resolve(cwd, path)));
268
+ const skipped = targets.filter(({ status }) => status === TARGET.unmatchedGlob)
269
+ .map(({ path }) => `[release-scan] skipped ${path} — no file matched this glob (an optional target, stated not silent).`);
270
+ const misaimed = targets.filter(({ status }) => TARGET_REMEDY[status] !== undefined)
271
+ .map(({ path, status }) => ({ path, status, remedy: TARGET_REMEDY[status] }));
272
+ const findings = findingsIn(targets);
273
+ if (findings.length === 0 && misaimed.length === 0) {
274
+ return { code: 0, lines: [...skipped, '[release-scan] clean — no AI attribution or reviewer-round identity found.'] };
263
275
  }
264
- const report = findingsIn(targets);
265
- for (const r of report) console.log(`[${r.kind}] ${r.file}:${r.line} — ${r.detail}`);
276
+ if (!reportOnly) return { code: 1, lines: composeScanBlock({ cwd: resolve(cwd), misaimed, findings, after: skipped }) };
277
+ const lines = [
278
+ ...skipped,
279
+ ...misaimed.map(({ path, status, remedy }) => `[release-scan] target ${path} contributed NO file (${status}) — ${remedy}`),
280
+ ...findings.map(({ kind, file, line, detail }) => `[${kind}] ${file}:${line} — ${detail}`),
281
+ ];
266
282
  if (misaimed.length > 0) {
267
- console.log(`\n[release-scan] ${misaimed.length} mis-aimed target(s) — this run proves nothing about them, so the clean verdict is refused.`);
268
- }
269
- if (report.length > 0) console.log(`\n[release-scan] ${report.length} finding(s).`);
270
- if (report.length === 0 && misaimed.length === 0) {
271
- console.log('[release-scan] clean — no AI attribution or reviewer-round identity found.');
272
- return 0;
283
+ lines.push('', `[release-scan] ${misaimed.length} mis-aimed target(s) — this run proves nothing about them, so the clean verdict is refused.`);
273
284
  }
274
- return reportOnly ? 0 : 1;
285
+ if (findings.length > 0) lines.push('', `[release-scan] ${findings.length} finding(s).`);
286
+ return { code: 0, lines };
287
+ };
288
+
289
+ export const main = (argv) => {
290
+ const { code, lines } = runScan(argv);
291
+ for (const line of lines) console.log(line);
292
+ return code;
275
293
  };
276
294
 
277
- if (isDirectRun(import.meta.url)) process.exitCode = main(process.argv.slice(2));
295
+ if (isDirectRun(import.meta.url)) {
296
+ runCheckerTail({ name: CHECKER_NAME, exitCode: 1, remedy: UNEXPECTED_REMEDY },
297
+ () => runScan(process.argv.slice(2)), process);
298
+ }
@@ -42,6 +42,7 @@ import { isNeverCommittableStat, shellQuoteArg } from './review-state.mjs';
42
42
  import { assertContainedRealPath } from './fs-safe.mjs';
43
43
  import { GIT_MAX_BUFFER } from './git-env.mjs';
44
44
  import { foreignMountTargets } from './mount-masks.mjs';
45
+ import { jsonForLine } from './source-size-refusal.mjs';
45
46
 
46
47
  export const MASKS_FENCE_START = '# >>> agent-workflow sandbox-masks — managed block, fully REPLACED by the kit sandbox-masks lane; do not hand-edit inside >>>';
47
48
  export const MASKS_FENCE_END = '# <<< agent-workflow sandbox-masks <<<';
@@ -225,7 +226,7 @@ export const probeSandboxMasks = ({ cwd = process.cwd(), lstat = lstatSync, list
225
226
  const fence = findMasksFence(lines);
226
227
  const staleReal = fence.state === 'ok' ? revalidateFence(fence.body, { root, lstat: lstatOnce, readMountinfo: once }) : [];
227
228
  const leftovers = clearOnly ? [] : staleReal.filter((rel) => isLeftoverStat(lstatOnce(join(root, rel))));
228
- if (leftovers.length > 0) throw fail(1, [...staleReal.filter((rel) => !leftovers.includes(rel)).map(staleRealLine), ...leftovers.map(leftoverLine)].join('\n'));
229
+ if (leftovers.length > 0) throw fail(1, [...formatGroup(staleRealHead, staleReal.filter((rel) => !leftovers.includes(rel))), ...formatGroup(leftoverHead, leftovers)].join('\n'));
229
230
  const applyCmd = `node ${shellQuoteArg(join(HERE, 'sandbox-masks.mjs'))} --cwd ${shellQuoteArg(root)} --apply`;
230
231
  return { root, excludeFile, gitCommonDir, content, lines, fence, masks, unrenderable, mountOnly, mountSignal, staleReal, applyCmd };
231
232
  };
@@ -281,8 +282,9 @@ export const planApply = (probe, { clear = false } = {}) => {
281
282
 
282
283
  // ── rendering ───────────────────────────────────────────────────────────────────────
283
284
 
284
- const staleRealLine = (rel) => ` ⚠ fenced entry became a REAL path: ${rel} — delete its line from the managed block BEFORE relying on git for this path: an excluded real file is silently skipped by bulk staging (git add -A / git add .), so it stays OUT of your commits, and an explicit git add refuses it without -f; .git/info/exclude never warns`;
285
- const leftoverLine = (rel) => ` ⚠ refusing: fenced entry ${rel} is an empty read-only file no arm calls a mask, so neither verdict is given — a running sandbox's mask: re-run once no other sandboxed command runs; litter a sandbox left: remove the file outside the sandbox and keep its line; a real file: delete its line`;
285
+ const staleRealHead = (n) => ` ⚠ ${n} fenced entr(ies) became REAL path(s) — delete each one's line from the managed block BEFORE relying on git for it: an excluded real file is silently skipped by bulk staging (git add -A / git add .), so it stays OUT of your commits, and an explicit git add refuses it without -f; .git/info/exclude never warns:`;
286
+ const leftoverHead = (n) => ` ⚠ refusing: ${n} fenced entr(ies) are empty read-only files no arm calls a mask, so neither verdict is given — a running sandbox's mask: re-run once no other sandboxed command runs; litter a sandbox left: remove the file outside the sandbox and keep its line; a real file: delete its line:`;
287
+ const formatGroup = (sentence, paths) => paths.length === 0 ? [] : [sentence(paths.length), ...paths.map((rel) => ' ' + jsonForLine(rel))];
286
288
 
287
289
  const formatProbe = (probe) => {
288
290
  const lines = [
@@ -294,7 +296,7 @@ const formatProbe = (probe) => {
294
296
  lines.push(` masks visible now: ${probe.masks.length === 0 ? '0 (outside the sandbox or clean)' : ''}`);
295
297
  for (const m of probe.masks) lines.push(` · ${m}${probe.mountOnly.includes(m) ? ' (mount-only: it rides git add -A and the review fingerprint while git does not ignore it)' : ''}`);
296
298
  if (probe.mountSignal === 'absent') lines.push(' mount signal: not read on this platform — only device/FIFO/socket masks are judged');
297
- lines.push(...probe.staleReal.map(staleRealLine));
299
+ lines.push(...formatGroup(staleRealHead, probe.staleReal));
298
300
  for (const rel of probe.unrenderable) {
299
301
  lines.push(` ⚠ mask name carries a newline or ends with a tab and cannot be expressed as ONE exclude rule — NOT written (the mask itself stays untracked): ${JSON.stringify(rel)}`);
300
302
  }