mandrel 2.72.0 → 2.74.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/.agents/README.md CHANGED
@@ -355,6 +355,7 @@ what keeps that footer refused. The execution-model contract is owned by
355
355
  | [`scripts/lib/checks/`](scripts/lib/checks/) | Discovery-based self-healing checks registry for preflight, the `diagnose.js` viewer, and retro surfaces. |
356
356
  | [`schemas/`](schemas/) | JSON Schema contracts for config, manifests, reports, and persisted runtime artefacts. |
357
357
  | [`templates/`](templates/) | Prompt and planning templates used by the orchestration flow. |
358
+ | [`mods/`](mods/) | Beta, opt-in Claude Code mods. Inert until a developer loads one; see [`docs/runbooks/mods.md`](docs/runbooks/mods.md). |
358
359
 
359
360
  ---
360
361
 
@@ -378,6 +379,8 @@ what keeps that footer refused. The execution-model contract is owned by
378
379
  | Bootstrap script (project + GitHub setup) | [`scripts/bootstrap.js`](scripts/bootstrap.js) |
379
380
  | Adopt the QA workflows (`/qa-explore`, `/qa-assist`, `/qa-run`) in your project | [§ Adopting the QA harness](#adopting-the-qa-harness) |
380
381
  | Coordinate two operators on the same repo (lease model) | [§ Multi-developer coordination](#multi-developer-coordination) |
382
+ | Opt into the beta `mandrel-status` band above the prompt | [`docs/runbooks/mods.md`](docs/runbooks/mods.md) |
383
+ | Operator runbooks (listed at the end of every `mandrel sync` / `init` / `update`) | [`docs/runbooks/`](docs/runbooks/) |
381
384
 
382
385
  ---
383
386
 
@@ -0,0 +1,95 @@
1
+ # Claude Code mods (beta)
2
+
3
+ > **Beta, optional, read-only.** Mandrel works the same with or without a
4
+ > mod. Nothing in Mandrel loads, references or depends on one, and no
5
+ > `.agentrc.json` key turns one on. The decision record is
6
+ > [ADR `20261002-5544`](https://github.com/dsj1984/mandrel/blob/main/docs/decisions.md#adr-20261002-5544-claude-code-mods-are-a-beta-optional-read-only-add-on).
7
+
8
+ A Claude Code mod is a plugin of function hooks: a module that draws on
9
+ Claude Code's own surfaces (a band above the prompt, a pane, a toast) and
10
+ reacts to session events. Mandrel ships its mods under `.agents/mods/`, so
11
+ `mandrel sync` copies them into every consumer checkout. A mod stays inert
12
+ until a developer loads it. This runbook is listed at the end of every
13
+ `mandrel sync`, `init` and `update`, like every file in `docs/runbooks/`.
14
+
15
+ ## `mandrel-status`
16
+
17
+ [`mods/mandrel-status/`](../../mods/mandrel-status/) draws one dim line above
18
+ the prompt while you work in a Mandrel checkout:
19
+
20
+ | State on disk | The line |
21
+ | --- | --- |
22
+ | A `.worktrees/story-<id>/` with no newer terminal envelope | `mandrel · Story #<id> implementing` |
23
+ | …and close has written `close-gates-<id>.log` | `mandrel · Story #<id> closing` |
24
+ | …and that log has been quiet for 10 minutes | `… · stalled? no gate output for <n>m` |
25
+ | Otherwise, the newest `story-deliver-terminal-<id>.json` from the last 2 hours | `mandrel · Story #<id> <status> · PR #<n> checks <state> · <elapsed>` |
26
+ | None of the above, or no `.agents/` in the working directory | nothing |
27
+
28
+ It also toasts once when a terminal envelope appears with `status` `landed`
29
+ or `blocked`. Results already on disk when the session starts are not
30
+ toasted, and a hot reload does not repeat one.
31
+
32
+ The files sit under `<tempRoot>/orchestration/`. `tempRoot` is
33
+ `project.paths.tempRoot` from `.agentrc.local.json`, then `.agentrc.json`,
34
+ and defaults to `temp`. It refreshes on session start, after each turn and
35
+ every 15 seconds.
36
+
37
+ ### Turn it on
38
+
39
+ Per developer, per machine. Pick one:
40
+
41
+ - **Every session:** add the folder's absolute path to
42
+ `CLAUDE_CODE_PLUGIN_DIRS` in the `env` block of `~/.claude/settings.json`
43
+ (separate several paths with the platform's path-list separator):
44
+
45
+ ```json
46
+ {
47
+ "env": {
48
+ "CLAUDE_CODE_PLUGIN_DIRS": "/absolute/path/to/project/.agents/mods/mandrel-status"
49
+ }
50
+ }
51
+ ```
52
+
53
+ Claude Code reads this variable from the process environment or from user
54
+ settings, never from a project's `.claude/settings.json`. A committed file
55
+ cannot switch the mod on for anyone else. In a directory with no `.agents/`
56
+ folder the mod draws nothing, so a user-wide entry is harmless elsewhere.
57
+
58
+ - **One session:** `claude --plugin-dir .agents/mods/mandrel-status`.
59
+
60
+ Turn it off by removing the entry or the flag.
61
+
62
+ ### The read-only invariant
63
+
64
+ A Mandrel mod may only read files (`$.fs.read`, `list`, `stat`, `exists`),
65
+ draw (`$.ui.*`), keep session state (`$.state`) and keep time (`$.clock`).
66
+ It hooks no `tool.call`, `prompt.submit`, `command.run` or `session.append`
67
+ event. It never writes files, spawns processes, calls the network or the
68
+ model. Guardrails stay in `.claude/settings.json` command hooks, which load
69
+ in environments where plugins do not. `claude plugin validate` lists every
70
+ hook and `$` call a mod makes. Check that list against this invariant when
71
+ you change one.
72
+
73
+ ### Develop and test
74
+
75
+ ```bash
76
+ claude plugin validate .agents/mods/mandrel-status
77
+ ```
78
+
79
+ ```bash
80
+ claude plugin test .agents/mods/mandrel-status
81
+ ```
82
+
83
+ The tests live in `__tests__/*.test.ts`. They answer the mod's file reads
84
+ from an in-memory checkout and drive the clock by hand. `npm test` does not
85
+ run them, since its tiers collect `*.test.js` only, and CI has no `claude`
86
+ binary. Run both commands locally before you push a change to a mod. The
87
+ npm package excludes `__tests__/`.
88
+
89
+ ## Removing mods
90
+
91
+ Delete `.agents/mods/`, this runbook, and its two rows in `.agents/README.md`. Then
92
+ mark the ADR Superseded. No other file references a mod, so no other gate
93
+ changes. Consumers lose the folder on their next `mandrel sync`, which
94
+ prunes files that are no longer in the payload. Anyone who set
95
+ `CLAUDE_CODE_PLUGIN_DIRS` should remove that entry.
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "mandrel-status",
3
+ "version": "0.1.0",
4
+ "description": "Beta, read-only: shows the current /mandrel-deliver Story above the prompt",
5
+ "author": {
6
+ "name": "Mandrel"
7
+ },
8
+ "types": "./types/index.d.ts"
9
+ }
@@ -0,0 +1 @@
1
+ { "modules": ["./register.tsx"] }
@@ -0,0 +1,234 @@
1
+ // mandrel-status — a beta, read-only Claude Code mod. It reads the state files
2
+ // /mandrel-deliver already writes and draws one line above the prompt. Nothing
3
+ // in Mandrel depends on it; see .agents/docs/runbooks/mods.md.
4
+
5
+ import type { EngineInterface, Register } from 'claude-code';
6
+ import { atom, read, update } from 'claude-code';
7
+
8
+ import type { InFlight, LastResult, Snapshot } from '../types';
9
+
10
+ const REFRESH_MS = 15_000;
11
+ const STALL_MS = 10 * 60_000;
12
+ const RECENT_MS = 2 * 60 * 60_000;
13
+ const WORKTREE = /^story-(\d+)$/;
14
+ const ENVELOPE = /^story-deliver-terminal-(\d+)\.json$/;
15
+ const GATE_LOG = /^close-gates-(\d+)\.log$/;
16
+ const ANNOUNCED = new Set(['landed', 'blocked']);
17
+
18
+ const EMPTY: Snapshot = { inFlight: null, last: null };
19
+ const snapshot = atom(
20
+ { plugin: 'mandrel-status', key: 'snapshot' } as const,
21
+ EMPTY,
22
+ );
23
+ const seen = atom(
24
+ { plugin: 'mandrel-status', key: 'seen' } as const,
25
+ [] as string[],
26
+ );
27
+ const isSeeded = atom(
28
+ { plugin: 'mandrel-status', key: 'isSeeded' } as const,
29
+ false,
30
+ );
31
+
32
+ type Stamped = { storyId: number; mtimeMs: number };
33
+
34
+ async function readJson($: EngineInterface, path: string): Promise<unknown> {
35
+ try {
36
+ return JSON.parse(await $.fs.read(path));
37
+ } catch {
38
+ return undefined;
39
+ }
40
+ }
41
+
42
+ function tempRootOf(config: unknown): string | undefined {
43
+ const value = (config as { project?: { paths?: { tempRoot?: unknown } } })
44
+ ?.project?.paths?.tempRoot;
45
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
46
+ }
47
+
48
+ /** `.agentrc.local.json` wins over `.agentrc.json`; `temp` when neither sets it. */
49
+ async function resolveTempRoot($: EngineInterface): Promise<string> {
50
+ return (
51
+ tempRootOf(await readJson($, '.agentrc.local.json')) ??
52
+ tempRootOf(await readJson($, '.agentrc.json')) ??
53
+ 'temp'
54
+ );
55
+ }
56
+
57
+ async function listMatching(
58
+ $: EngineInterface,
59
+ dir: string,
60
+ pattern: RegExp,
61
+ kind: 'file' | 'dir',
62
+ ): Promise<Stamped[]> {
63
+ const entries = await $.fs.list(dir).catch(() => []);
64
+ const found: Stamped[] = [];
65
+ for (const entry of entries) {
66
+ const match = pattern.exec(entry.name);
67
+ if (!match || entry.kind !== kind) continue;
68
+ const mtimeMs =
69
+ kind === 'file'
70
+ ? entry.mtimeMs
71
+ : await $.fs
72
+ .stat(`${dir}/${entry.name}`)
73
+ .then((stat) => stat.mtimeMs)
74
+ .catch(() => 0);
75
+ found.push({ storyId: Number(match[1]), mtimeMs });
76
+ }
77
+ return found;
78
+ }
79
+
80
+ const newest = (list: Stamped[]): Stamped | undefined =>
81
+ [...list].sort((a, b) => b.mtimeMs - a.mtimeMs)[0];
82
+
83
+ function pickInFlight(
84
+ worktrees: Stamped[],
85
+ envelopes: Stamped[],
86
+ gateLogs: Stamped[],
87
+ now: number,
88
+ ): InFlight | null {
89
+ const open = worktrees.filter((tree) => {
90
+ const envelope = envelopes.find((one) => one.storyId === tree.storyId);
91
+ return !envelope || envelope.mtimeMs < tree.mtimeMs;
92
+ });
93
+ const story = newest(open);
94
+ if (!story) return null;
95
+ const log = gateLogs.find((one) => one.storyId === story.storyId);
96
+ const idleMs = log ? now - log.mtimeMs : 0;
97
+ return {
98
+ storyId: story.storyId,
99
+ isClosing: Boolean(log),
100
+ stalledMinutes: idleMs > STALL_MS ? Math.floor(idleMs / 60_000) : null,
101
+ };
102
+ }
103
+
104
+ function toLastResult(storyId: number, raw: unknown): LastResult | null {
105
+ const envelope = raw as {
106
+ status?: unknown;
107
+ elapsedSeconds?: unknown;
108
+ pr?: { number?: unknown; checksStatus?: unknown } | null;
109
+ };
110
+ if (typeof envelope?.status !== 'string') return null;
111
+ const pr = envelope.pr ?? {};
112
+ return {
113
+ storyId,
114
+ status: envelope.status,
115
+ prNumber: typeof pr.number === 'number' ? pr.number : null,
116
+ checksStatus: typeof pr.checksStatus === 'string' ? pr.checksStatus : null,
117
+ elapsedSeconds:
118
+ typeof envelope.elapsedSeconds === 'number'
119
+ ? envelope.elapsedSeconds
120
+ : null,
121
+ };
122
+ }
123
+
124
+ async function scan(
125
+ $: EngineInterface,
126
+ ): Promise<{ next: Snapshot; latest?: Stamped }> {
127
+ if (!(await $.fs.exists('.agents').catch(() => false)))
128
+ return { next: EMPTY };
129
+ const orchestration = `${await resolveTempRoot($)}/orchestration`;
130
+ const now = await $.clock.now();
131
+ const [worktrees, files] = await Promise.all([
132
+ listMatching($, '.worktrees', WORKTREE, 'dir'),
133
+ $.fs.list(orchestration).catch(() => []),
134
+ ]);
135
+ const stamp = (pattern: RegExp): Stamped[] =>
136
+ files.flatMap((entry) => {
137
+ const match = pattern.exec(entry.name);
138
+ return match && entry.kind === 'file'
139
+ ? [{ storyId: Number(match[1]), mtimeMs: entry.mtimeMs }]
140
+ : [];
141
+ });
142
+ const envelopes = stamp(ENVELOPE);
143
+ const inFlight = pickInFlight(worktrees, envelopes, stamp(GATE_LOG), now);
144
+ const latest = newest(
145
+ envelopes.filter((one) => now - one.mtimeMs <= RECENT_MS),
146
+ );
147
+ const last = latest
148
+ ? toLastResult(
149
+ latest.storyId,
150
+ await readJson(
151
+ $,
152
+ `${orchestration}/story-deliver-terminal-${latest.storyId}.json`,
153
+ ),
154
+ )
155
+ : null;
156
+ return { next: { inFlight, last }, latest: last ? latest : undefined };
157
+ }
158
+
159
+ /** Toasts a landed or blocked result once; the first scan only records. */
160
+ async function announce(
161
+ $: EngineInterface,
162
+ next: Snapshot,
163
+ latest: Stamped | undefined,
164
+ ): Promise<void> {
165
+ const seeded = await read($, isSeeded);
166
+ if (!seeded) await update($, isSeeded, () => true);
167
+ if (!latest || !next.last) return;
168
+ const key = `${latest.storyId}:${latest.mtimeMs}`;
169
+ if ((await read($, seen)).includes(key)) return;
170
+ await update($, seen, (list) => [...list, key].slice(-50));
171
+ if (seeded && ANNOUNCED.has(next.last.status)) {
172
+ const pr = next.last.prNumber ? ` (PR #${next.last.prNumber})` : '';
173
+ $.ui.toast(`Story #${next.last.storyId} ${next.last.status}${pr}`);
174
+ }
175
+ }
176
+
177
+ async function refresh($: EngineInterface): Promise<void> {
178
+ try {
179
+ const { next, latest } = await scan($);
180
+ await update($, snapshot, () => next);
181
+ await announce($, next, latest);
182
+ } catch {
183
+ // Read-only and best effort: a failed scan leaves the last drawing up.
184
+ }
185
+ }
186
+
187
+ function describe({ inFlight, last }: Snapshot): string | null {
188
+ if (inFlight) {
189
+ const phase = inFlight.isClosing ? 'closing' : 'implementing';
190
+ const stall =
191
+ inFlight.stalledMinutes === null
192
+ ? ''
193
+ : ` · stalled? no gate output for ${inFlight.stalledMinutes}m`;
194
+ return `mandrel · Story #${inFlight.storyId} ${phase}${stall}`;
195
+ }
196
+ if (last) {
197
+ const pr = last.prNumber === null ? '' : ` · PR #${last.prNumber}`;
198
+ const checks = last.checksStatus ? ` checks ${last.checksStatus}` : '';
199
+ const took =
200
+ last.elapsedSeconds === null
201
+ ? ''
202
+ : ` · ${Math.floor(last.elapsedSeconds / 60)}m${last.elapsedSeconds % 60}s`;
203
+ return `mandrel · Story #${last.storyId} ${last.status}${pr}${checks}${took}`;
204
+ }
205
+ return null;
206
+ }
207
+
208
+ export const register: Register = (on) => {
209
+ on('session.start', async ($, e, next) => {
210
+ await refresh($);
211
+ $.clock.every(REFRESH_MS, () => {
212
+ void refresh($);
213
+ });
214
+ return next(e);
215
+ });
216
+
217
+ on('turn.complete', async ($, e, next) => {
218
+ await refresh($);
219
+ return next(e);
220
+ });
221
+
222
+ on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
223
+ const line = e.props.hasSurvey ? null : describe(await read($, snapshot));
224
+ if (line === null) return next(e);
225
+ const { Box, Text } = $.ui.resolve(e);
226
+ return (
227
+ <Box>
228
+ <Text dimColor wrap="truncate">
229
+ {line}
230
+ </Text>
231
+ </Box>
232
+ );
233
+ });
234
+ };
@@ -0,0 +1,34 @@
1
+ /** A Story whose worktree exists and whose close has not finished. */
2
+ export type InFlight = {
3
+ storyId: number;
4
+ /** True once close has written its gate log. */
5
+ isClosing: boolean;
6
+ /** Minutes since the gate log last changed, when over the stall limit. */
7
+ stalledMinutes: number | null;
8
+ };
9
+
10
+ /** The newest terminal envelope from the last two hours. */
11
+ export type LastResult = {
12
+ storyId: number;
13
+ status: string;
14
+ prNumber: number | null;
15
+ checksStatus: string | null;
16
+ elapsedSeconds: number | null;
17
+ };
18
+
19
+ export type Snapshot = {
20
+ inFlight: InFlight | null;
21
+ last: LastResult | null;
22
+ };
23
+
24
+ declare module 'claude-code' {
25
+ interface PluginState {
26
+ 'mandrel-status': {
27
+ snapshot: Snapshot;
28
+ /** `<storyId>:<mtimeMs>` of every envelope already seen. */
29
+ seen: string[];
30
+ /** False until the first scan, which records envelopes without a toast. */
31
+ isSeeded: boolean;
32
+ };
33
+ }
34
+ }
@@ -97,8 +97,13 @@ const WEB_FRAMEWORK_PACKAGES = Object.freeze([
97
97
 
98
98
  const WEB_ASSET_EXTENSIONS = Object.freeze(['.html', '.css', '.jsx', '.tsx']);
99
99
 
100
- /** A dependency's or fixture's asset says nothing about the consumer's own surface. */
100
+ /**
101
+ * A dependency's or fixture's asset says nothing about the consumer's own
102
+ * surface — nor does the synced Mandrel payload (`.agents/`), whose beta mods
103
+ * ship `.tsx` hook modules.
104
+ */
101
105
  const WEB_SCAN_SKIP_DIRS = Object.freeze([
106
+ '.agents',
102
107
  'node_modules',
103
108
  '.git',
104
109
  '.worktrees',
@@ -11,6 +11,8 @@ import { isCoverageFresh } from '../coverage-capture.js';
11
11
  import { loadCoverage as loadCoverageDefault } from '../coverage-utils.js';
12
12
  import { checkResolutionFloor, scanAndScore } from '../crap-utils.js';
13
13
  import { Logger } from '../Logger.js';
14
+ import { isIgnoredByGlobs } from '../maintainability-utils.js';
15
+ import { isScorableSourceFile } from '../source-extensions.js';
14
16
  import { parseDiffScopeFlag } from './diff-scope-cli.js';
15
17
  import {
16
18
  checkSeatResolution,
@@ -187,11 +189,60 @@ export function buildCrapUpdaterScorer(
187
189
  /** Stamp scopes a capture may have written; any one fresh stamp suffices. */
188
190
  const CAPTURE_SCOPES = ['full', 'incremental', 'affected'];
189
191
 
192
+ /**
193
+ * The coverage artifact when any capture stamp marks it fresh for the
194
+ * current tree; otherwise `null`.
195
+ *
196
+ * @param {{coveragePath: string, targetDirs: string[]}} options
197
+ * @param {{isFresh: Function, loadCoverage: Function, cwd: string}} deps
198
+ * @returns {object|null}
199
+ */
200
+ function loadFreshCoverage(options, { isFresh, loadCoverage, cwd }) {
201
+ const fresh = CAPTURE_SCOPES.some(
202
+ (requireScope) =>
203
+ isFresh({
204
+ coveragePath: options.coveragePath,
205
+ targetDirs: options.targetDirs,
206
+ cwd,
207
+ requireScope,
208
+ }).fresh,
209
+ );
210
+ return fresh ? loadCoverage(path.resolve(cwd, options.coveragePath)) : null;
211
+ }
212
+
213
+ /**
214
+ * Whether `file` (repo-relative) is one the CRAP scan would score: a scorable
215
+ * source under a `targetDirs` entry and not ignored. It may over-include
216
+ * against the walk's directory skips — that only keeps the refusal, never
217
+ * seats an unmeasured file.
218
+ *
219
+ * @param {string} file
220
+ * @param {{targetDirs: string[], ignoreGlobs: string[]}} options
221
+ * @param {string} cwd
222
+ * @returns {boolean}
223
+ */
224
+ function isInCrapScope(file, { targetDirs, ignoreGlobs }, cwd) {
225
+ if (!isScorableSourceFile(file)) return false;
226
+ const abs = path.resolve(cwd, file);
227
+ const underTarget = targetDirs.some((dir) => {
228
+ const rel = path.relative(path.resolve(cwd, dir), abs);
229
+ return (
230
+ rel !== '' &&
231
+ rel !== '..' &&
232
+ !rel.startsWith(`..${path.sep}`) &&
233
+ !path.isAbsolute(rel)
234
+ );
235
+ });
236
+ return underTarget && !isIgnoredByGlobs(abs, ignoreGlobs, cwd);
237
+ }
238
+
190
239
  /**
191
240
  * The `--seat-missing` scorer: refuses (throws {@link SeatRefusal}) unless
192
241
  * the coverage artifact is fresh for the current tree and every in-scope
193
242
  * method resolved a coverage entry — a wrong-coordinate row stays wrong even
194
- * when it is only inserted.
243
+ * when it is only inserted. A diff with no in-scope file seats nothing and
244
+ * never consults coverage: affected-mode capture rightly writes no artifact
245
+ * for it.
195
246
  *
196
247
  * @param {ReturnType<typeof resolveCrapUpdaterOptions>} options
197
248
  * @param {{loadCoverage: Function, scan?: Function, isFresh?: Function,
@@ -210,22 +261,13 @@ export function buildCrapSeatScorer(
210
261
  ) {
211
262
  const fixCommand = `node .agents/scripts/coverage-capture.js --cwd ${cwd}`;
212
263
  return async (files) => {
213
- const fresh = CAPTURE_SCOPES.some(
214
- (requireScope) =>
215
- isFresh({
216
- coveragePath: options.coveragePath,
217
- targetDirs: options.targetDirs,
218
- cwd,
219
- requireScope,
220
- }).fresh,
221
- );
222
- const coverage = fresh
223
- ? loadCoverage(path.resolve(cwd, options.coveragePath))
224
- : null;
264
+ const inScope = files.filter((file) => isInCrapScope(file, options, cwd));
265
+ if (inScope.length === 0) return [];
266
+ const coverage = loadFreshCoverage(options, { isFresh, loadCoverage, cwd });
225
267
  if (!coverage) {
226
268
  throw new SeatRefusal(
227
269
  `[CRAP] --seat-missing refused: no coverage artifact at ${options.coveragePath} is fresh for the current tree ` +
228
- `(method resolution unmeasured; unresolved files: ${files.join(', ')}).\n` +
270
+ `(method resolution unmeasured; unresolved files: ${inScope.join(', ')}).\n` +
229
271
  `Fix: re-capture coverage for the current tree — ${fixCommand}`,
230
272
  );
231
273
  }
@@ -235,7 +277,7 @@ export function buildCrapSeatScorer(
235
277
  requireCoverage: options.requireCoverage,
236
278
  cwd,
237
279
  ignoreGlobs: options.ignoreGlobs,
238
- scopeFiles: files,
280
+ scopeFiles: inScope,
239
281
  });
240
282
  reportScanSummary(summary, logger);
241
283
  const refusal = checkSeatResolution(summary.resolution, fixCommand);
@@ -67,17 +67,14 @@ export function isCrapGateEnabled(config) {
67
67
  }
68
68
 
69
69
  /**
70
- * The credited-run depositor predicate — the ONE home, shared by close's gate
71
- * registration and the worker's `story-handoff.js`, so the two cannot pick
72
- * different depositors: coverage-capture runs the suite when the CRAP gate is
73
- * on AND a `test:coverage` script exists; any other project takes the plain
74
- * `test` gate (the evidence-gate `npm test` credit).
70
+ * Coverage-capture registers when the CRAP gate is on AND a `test:coverage`
71
+ * script exists; {@link resolveCreditedDepositor} builds on it.
75
72
  *
76
73
  * @param {object|undefined|null} config - Canonical resolved config.
77
74
  * @param {Record<string, string>|null|undefined} scripts - `package.json` scripts.
78
75
  * @returns {boolean}
79
76
  */
80
- export function isCoverageCaptureActive(config, scripts) {
77
+ function isCoverageCaptureActive(config, scripts) {
81
78
  return isCrapGateEnabled(config) && hasNpmScript(scripts, 'test:coverage');
82
79
  }
83
80
 
@@ -281,6 +278,36 @@ function predictsIncrementalCaptureSkip({
281
278
  }
282
279
  }
283
280
 
281
+ /**
282
+ * The credited-run depositor, shared by close and `story-handoff.js`: a
283
+ * predicted incremental skip runs no suite, so it is never the depositor.
284
+ *
285
+ * @param {{
286
+ * config?: object,
287
+ * scripts?: Record<string, string>|null,
288
+ * cwd?: string,
289
+ * baseBranch?: string,
290
+ * getChangedFilesImpl?: typeof getChangedFiles,
291
+ * }} opts
292
+ * @returns {'coverage-capture'|'test'}
293
+ */
294
+ export function resolveCreditedDepositor({
295
+ config,
296
+ scripts,
297
+ cwd,
298
+ baseBranch,
299
+ getChangedFilesImpl,
300
+ }) {
301
+ if (!isCoverageCaptureActive(config, scripts)) return 'test';
302
+ const skip = predictsIncrementalCaptureSkip({
303
+ config,
304
+ cwd,
305
+ baseBranch,
306
+ ...(getChangedFilesImpl ? { getChangedFilesImpl } : {}),
307
+ });
308
+ return skip ? 'test' : 'coverage-capture';
309
+ }
310
+
284
311
  /**
285
312
  * Is the `test` gate already credited? Only consulted when coverage-capture is active.
286
313
  *
@@ -412,12 +439,13 @@ export function buildDefaultGates({
412
439
  // and brings the plain `test` gate back.
413
440
  const captureSkipPredicted =
414
441
  coverageCaptureActive &&
415
- predictsIncrementalCaptureSkip({
442
+ resolveCreditedDepositor({
416
443
  config,
444
+ scripts,
417
445
  cwd,
418
446
  baseBranch,
419
- ...(getChangedFilesImpl ? { getChangedFilesImpl } : {}),
420
- });
447
+ getChangedFilesImpl,
448
+ }) === 'test';
421
449
  if (captureSkipPredicted) {
422
450
  log?.(
423
451
  '[close-validation] coverage-capture will take the incremental skip (no changed file under the CRAP target dirs) — registering the plain `test` gate so this close still runs the suite.',
@@ -15,6 +15,7 @@ import {
15
15
  describeStampFreshness,
16
16
  planDeltaRefresh,
17
17
  readHeadCommit,
18
+ snapshotCapturedTree,
18
19
  } from './coverage-capture-delta.js';
19
20
  import { tryIncrementalCapture } from './coverage-capture-incremental.js';
20
21
 
@@ -109,24 +110,11 @@ function readChangedFiles({ getChangedFilesImpl, ref, cwd, logger }) {
109
110
  }
110
111
  }
111
112
 
112
- /** The tree a run is about to measure: its source digest and HEAD commit. */
113
- function snapshotTree({
114
- args,
115
- crap,
116
- computeContentDigestImpl,
117
- readHeadCommitImpl,
118
- }) {
119
- return {
120
- preDigest: computeContentDigestImpl(args.cwd, crap.targetDirs),
121
- commit: readHeadCommitImpl(args.cwd),
122
- };
123
- }
124
-
125
113
  /**
126
114
  * Run the affected script against `baseRef`. The pre-spawn digest and
127
115
  * commit are what the stamp records; see `stampCapturedTree`.
128
116
  *
129
- * @returns {Promise<{ code: number, preDigest: string | null, commit: string | null }>}
117
+ * @returns {Promise<{ code: number, preDigest: string | null, preTreeDigest: string | null, commit: string | null }>}
130
118
  */
131
119
  async function runScoped({
132
120
  crap,
@@ -139,8 +127,8 @@ async function runScoped({
139
127
  readHeadCommitImpl,
140
128
  logger,
141
129
  }) {
142
- const tree = snapshotTree({
143
- args,
130
+ const tree = snapshotCapturedTree({
131
+ cwd: args.cwd,
144
132
  crap,
145
133
  computeContentDigestImpl,
146
134
  readHeadCommitImpl,
@@ -206,6 +194,7 @@ async function captureAndMerge(opts) {
206
194
  cwd: opts.args.cwd,
207
195
  scope: 'affected',
208
196
  preDigest: run.preDigest,
197
+ preTreeDigest: run.preTreeDigest,
209
198
  commit: run.commit,
210
199
  ...opts.stamp,
211
200
  });
@@ -6,7 +6,11 @@
6
6
  */
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
- import { captureStampPath, computeContentDigest } from './coverage-capture.js';
9
+ import {
10
+ captureStampPath,
11
+ computeContentDigest,
12
+ computeTreeDigest,
13
+ } from './coverage-capture.js';
10
14
  import { gitSpawn } from './git-utils.js';
11
15
 
12
16
  /** Basenames whose change moves coverage beyond the files it names. */
@@ -31,6 +35,26 @@ export function readHeadCommit(cwd, io = {}) {
31
35
  return /^[0-9a-f]{40,64}$/.test(sha) ? sha : null;
32
36
  }
33
37
 
38
+ /**
39
+ * The tree a capture is about to measure, taken before the spawn: what
40
+ * `stampCapturedTree` records — both digests and the HEAD commit.
41
+ *
42
+ * @param {{ cwd: string, crap: { targetDirs: string[], coveragePath: string }, computeContentDigestImpl: typeof computeContentDigest, readHeadCommitImpl?: typeof readHeadCommit }} opts
43
+ * @returns {{ preDigest: string | null, preTreeDigest: string | null, commit: string | null }}
44
+ */
45
+ export function snapshotCapturedTree({
46
+ cwd,
47
+ crap,
48
+ computeContentDigestImpl,
49
+ readHeadCommitImpl = readHeadCommit,
50
+ }) {
51
+ return {
52
+ preDigest: computeContentDigestImpl(cwd, crap.targetDirs),
53
+ preTreeDigest: computeTreeDigest(cwd, crap.coveragePath),
54
+ commit: readHeadCommitImpl(cwd),
55
+ };
56
+ }
57
+
34
58
  /** @returns {Record<string, unknown> | null} */
35
59
  function readCaptureStamp(cwd, coveragePath, io = {}) {
36
60
  const readFileSync = io.readFileSync ?? fs.readFileSync;
@@ -10,6 +10,7 @@ import {
10
10
  import {
11
11
  describeStampFreshness,
12
12
  readHeadCommit,
13
+ snapshotCapturedTree,
13
14
  } from './coverage-capture-delta.js';
14
15
 
15
16
  /**
@@ -97,9 +98,12 @@ export async function runFullScopeCapture({
97
98
  logger.info(
98
99
  `[coverage-capture] Coverage at ${crap.coveragePath} is ${describeFreshness(freshness, crap.targetDirs)}; running npm run test:coverage… ${detail}`,
99
100
  );
100
- // Pre-spawn digest and commit; see `stampCapturedTree`.
101
- const preDigest = computeContentDigestImpl(args.cwd, crap.targetDirs);
102
- const commit = readHeadCommitImpl(args.cwd);
101
+ const tree = snapshotCapturedTree({
102
+ cwd: args.cwd,
103
+ crap,
104
+ computeContentDigestImpl,
105
+ readHeadCommitImpl,
106
+ });
103
107
  const code = await runCaptureImpl({
104
108
  cwd: args.cwd,
105
109
  coveragePath: crap.coveragePath,
@@ -111,11 +115,10 @@ export async function runFullScopeCapture({
111
115
  if (code !== 0) return reportCaptureFailure(code, logger);
112
116
 
113
117
  stampCapturedTree({
114
- preDigest,
118
+ ...tree,
115
119
  cwd: args.cwd,
116
120
  targetDirs: crap.targetDirs,
117
121
  coveragePath: crap.coveragePath,
118
- commit,
119
122
  computeContentDigestImpl,
120
123
  writeCaptureStampImpl,
121
124
  logger,
@@ -5,6 +5,7 @@ import { reportCaptureFailure, stampCapturedTree } from './coverage-capture.js';
5
5
  import {
6
6
  describeStampFreshness,
7
7
  readHeadCommit,
8
+ snapshotCapturedTree,
8
9
  } from './coverage-capture-delta.js';
9
10
 
10
11
  /**
@@ -99,9 +100,12 @@ export async function tryIncrementalCapture({
99
100
  logger.info(
100
101
  `[coverage-capture] Incremental mode: ${scopedFiles.length} changed file(s) under [${crap.targetDirs.join(', ')}] — capturing… ${detail}`,
101
102
  );
102
- // Pre-spawn digest and commit; see `stampCapturedTree`.
103
- const preDigest = computeContentDigestImpl(args.cwd, crap.targetDirs);
104
- const commit = readHeadCommitImpl(args.cwd);
103
+ const tree = snapshotCapturedTree({
104
+ cwd: args.cwd,
105
+ crap,
106
+ computeContentDigestImpl,
107
+ readHeadCommitImpl,
108
+ });
105
109
  const code = await runCaptureImpl({
106
110
  cwd: args.cwd,
107
111
  coveragePath: crap.coveragePath,
@@ -112,14 +116,13 @@ export async function tryIncrementalCapture({
112
116
  if (code !== 0) return reportCaptureFailure(code, logger);
113
117
 
114
118
  stampCapturedTree({
115
- preDigest,
119
+ ...tree,
116
120
  cwd: args.cwd,
117
121
  targetDirs: crap.targetDirs,
118
122
  coveragePath: crap.coveragePath,
119
123
  scope: 'incremental',
120
124
  files: scopedFiles,
121
125
  ref,
122
- commit,
123
126
  computeContentDigestImpl,
124
127
  writeCaptureStampImpl,
125
128
  logger,
@@ -85,16 +85,24 @@ export function captureStampPath(cwd, coveragePath) {
85
85
  * cwd: string,
86
86
  * readFileSync: typeof fs.readFileSync,
87
87
  * porcelain: string,
88
- * }} opts `porcelain` is raw `git status --porcelain` output.
89
- * @returns {number} Count of scorable dirty files folded in.
88
+ * select?: (file: string) => boolean,
89
+ * }} opts `porcelain` is raw `git status --porcelain` output; `select`
90
+ * picks which dirty paths fold in (default: scorable sources).
91
+ * @returns {number} Count of selected dirty files folded in.
90
92
  */
91
- function foldDirtySources({ hash, cwd, readFileSync, porcelain }) {
93
+ function foldDirtySources({
94
+ hash,
95
+ cwd,
96
+ readFileSync,
97
+ porcelain,
98
+ select = (file) => SCORABLE_SOURCE_EXT_RE.test(file),
99
+ }) {
92
100
  let count = 0;
93
101
  for (const line of porcelain.split('\n').filter((l) => l.length > 3)) {
94
102
  let file = line.slice(3).trim();
95
103
  if (file.includes(' -> ')) file = file.split(' -> ').pop();
96
104
  file = file.replace(/^"|"$/g, '');
97
- if (!SCORABLE_SOURCE_EXT_RE.test(file)) continue;
105
+ if (!select(file)) continue;
98
106
  count += 1;
99
107
  hash.update(`\0${file}\0`);
100
108
  try {
@@ -153,6 +161,81 @@ export function computeContentDigest(cwd, targetDirs, io = {}) {
153
161
  }
154
162
  }
155
163
 
164
+ /** Gate-written output: a baseline-refresh commit must not void the run it records. */
165
+ const SUITE_DIGEST_EXCLUDED_DIRS = Object.freeze(['baselines']);
166
+
167
+ /** @param {string|null|undefined} coveragePath */
168
+ function suiteDigestExcludedDirs(coveragePath) {
169
+ const coverageDir = path.posix.dirname(
170
+ String(coveragePath ?? '').replace(/\\/g, '/'),
171
+ );
172
+ return [...SUITE_DIGEST_EXCLUDED_DIRS, coverageDir].filter(
173
+ (dir) => dir !== '.' && dir.length > 0,
174
+ );
175
+ }
176
+
177
+ /**
178
+ * The changed paths that move {@link computeTreeDigest}, so spend the stamp.
179
+ *
180
+ * @param {string[]} files
181
+ * @param {string|null} [coveragePath]
182
+ * @returns {string[]}
183
+ */
184
+ export function filterSuiteInputPaths(files, coveragePath = null) {
185
+ const dirs = suiteDigestExcludedDirs(coveragePath);
186
+ return (Array.isArray(files) ? files : []).filter((file) => {
187
+ const norm = String(file).replace(/\\/g, '/');
188
+ return !dirs.some((dir) => norm === dir || norm.startsWith(`${dir}/`));
189
+ });
190
+ }
191
+
192
+ /**
193
+ * Digest of every suite input: tracked and dirty paths (untracked included)
194
+ * at any extension, minus the baselines and the coverage directory. The
195
+ * source digest says the artifact matches the sources; this one says the
196
+ * suite ran on this tree. `null` (no git) never matches.
197
+ *
198
+ * @param {string} cwd
199
+ * @param {string} coveragePath
200
+ * @param {{ spawnSync?: typeof spawnSync, readFileSync?: typeof fs.readFileSync }} [io]
201
+ * @returns {string | null}
202
+ */
203
+ export function computeTreeDigest(cwd, coveragePath, io = {}) {
204
+ const spawn = io.spawnSync ?? spawnSync;
205
+ const readFileSync = io.readFileSync ?? fs.readFileSync;
206
+ const pathspec = [
207
+ '--',
208
+ '.',
209
+ ...suiteDigestExcludedDirs(coveragePath).map((dir) => `:(exclude)${dir}`),
210
+ ];
211
+ const git = (...args) => {
212
+ const res = spawn('git', args, { cwd, encoding: 'utf8' });
213
+ if (res?.error || res?.status !== 0) {
214
+ throw res?.error ?? new Error(res?.stderr || `git ${args[0]} failed`);
215
+ }
216
+ return res.stdout ?? '';
217
+ };
218
+ try {
219
+ const hash = crypto.createHash('sha256');
220
+ hash.update(git('ls-files', '-s', ...pathspec));
221
+ foldDirtySources({
222
+ hash,
223
+ cwd,
224
+ readFileSync,
225
+ porcelain: git(
226
+ 'status',
227
+ '--porcelain',
228
+ '--untracked-files=all',
229
+ ...pathspec,
230
+ ),
231
+ select: () => true,
232
+ });
233
+ return hash.digest('hex');
234
+ } catch {
235
+ return null;
236
+ }
237
+ }
238
+
156
239
  /** @param {string} value */
157
240
  const nonEmpty = (value) => typeof value === 'string' && value.length > 0;
158
241
 
@@ -187,6 +270,7 @@ function definedOnly(fields) {
187
270
  * files?: string[],
188
271
  * ref?: string,
189
272
  * commit?: string | null,
273
+ * treeDigest?: string | null,
190
274
  * writeFileSync?: typeof fs.writeFileSync,
191
275
  * }} opts
192
276
  * @returns {boolean} True when the stamp was written.
@@ -199,12 +283,14 @@ export function writeCaptureStamp({
199
283
  files,
200
284
  ref,
201
285
  commit,
286
+ treeDigest,
202
287
  writeFileSync = fs.writeFileSync,
203
288
  }) {
204
289
  if (typeof digest !== 'string' || digest.length === 0) return false;
205
290
  const payload = {
206
291
  digest,
207
292
  capturedAt: new Date().toISOString(),
293
+ treeDigest,
208
294
  ...optionalStampFields({ scope, files, ref, commit }),
209
295
  };
210
296
  try {
@@ -224,7 +310,7 @@ const PARTIAL_STAMP_SCOPES = new Set(['incremental', 'affected']);
224
310
  /**
225
311
  * @param {{digest?: unknown, scope?: unknown} | null} stamp
226
312
  * @param {'full' | 'incremental' | 'affected'} requireScope
227
- * @returns {{ digest: string } | { scopeMismatch: true } | null} `null`
313
+ * @returns {{ digest: string, treeDigest: string | null } | { scopeMismatch: true } | null} `null`
228
314
  * means no usable stamp: nothing vouches for the artifact.
229
315
  */
230
316
  function readStampForScope(stamp, requireScope) {
@@ -234,7 +320,25 @@ function readStampForScope(stamp, requireScope) {
234
320
  if (PARTIAL_STAMP_SCOPES.has(stamp.scope) && stamp.scope !== requireScope) {
235
321
  return { scopeMismatch: true };
236
322
  }
237
- return { digest: stamp.digest };
323
+ return {
324
+ digest: stamp.digest,
325
+ treeDigest: nonEmpty(stamp.treeDigest) ? stamp.treeDigest : null,
326
+ };
327
+ }
328
+
329
+ /**
330
+ * @param {{ resolved: { digest: string, treeDigest: string | null }, current: string, computeTree: typeof computeTreeDigest, cwd: string, coveragePath: string }} opts
331
+ * @returns {boolean}
332
+ */
333
+ function stampMatchesTree({
334
+ resolved,
335
+ current,
336
+ computeTree,
337
+ cwd,
338
+ coveragePath,
339
+ }) {
340
+ if (current !== resolved.digest || resolved.treeDigest === null) return false;
341
+ return computeTree(cwd, coveragePath) === resolved.treeDigest;
238
342
  }
239
343
 
240
344
  /**
@@ -244,6 +348,7 @@ function readStampForScope(stamp, requireScope) {
244
348
  * `no-sources` (empty source set — "found nothing" is not "nothing changed")
245
349
  * outranks `unstamped`. A partial (incremental / affected) stamp satisfies
246
350
  * only a probe of its own scope; a stamp with no `scope` is full-scope.
351
+ * Fresh needs both digests; a stamp without a tree digest is `stale`.
247
352
  *
248
353
  * @param {{
249
354
  * coveragePath: string,
@@ -255,6 +360,7 @@ function readStampForScope(stamp, requireScope) {
255
360
  * existsSync?: typeof fs.existsSync,
256
361
  * readFileSync?: typeof fs.readFileSync,
257
362
  * computeDigest?: typeof computeContentDigest,
363
+ * computeTree?: typeof computeTreeDigest,
258
364
  * }} opts
259
365
  * @returns {{ fresh: boolean, reason: 'missing' | 'stale' | 'fresh' | 'no-sources' | 'scope-mismatch' | 'unstamped' }}
260
366
  */
@@ -268,6 +374,7 @@ export function isCoverageFresh({
268
374
  existsSync = fs.existsSync,
269
375
  readFileSync = fs.readFileSync,
270
376
  computeDigest = computeContentDigest,
377
+ computeTree = computeTreeDigest,
271
378
  }) {
272
379
  const absCoverage = path.resolve(cwd, coveragePath);
273
380
  if (!existsSync(absCoverage)) return { fresh: false, reason: 'missing' };
@@ -287,7 +394,13 @@ export function isCoverageFresh({
287
394
  if (resolved) {
288
395
  const current = computeDigest(cwd, targetDirs);
289
396
  if (typeof current === 'string' && current.length > 0) {
290
- return current === resolved.digest
397
+ return stampMatchesTree({
398
+ resolved,
399
+ current,
400
+ computeTree,
401
+ cwd,
402
+ coveragePath,
403
+ })
291
404
  ? { fresh: true, reason: 'fresh' }
292
405
  : { fresh: false, reason: 'stale' };
293
406
  }
@@ -379,6 +492,7 @@ export function creditedCapture(runCaptureFn, { requireCredited, logger }) {
379
492
  * files?: string[],
380
493
  * ref?: string,
381
494
  * commit?: string | null,
495
+ * preTreeDigest?: string | null,
382
496
  * computeContentDigestImpl: typeof computeContentDigest,
383
497
  * writeCaptureStampImpl: typeof writeCaptureStamp,
384
498
  * logger: { info: Function, warn: Function, error: Function },
@@ -394,6 +508,7 @@ export function stampCapturedTree({
394
508
  files,
395
509
  ref,
396
510
  commit,
511
+ preTreeDigest,
397
512
  computeContentDigestImpl,
398
513
  writeCaptureStampImpl,
399
514
  logger,
@@ -412,7 +527,13 @@ export function stampCapturedTree({
412
527
  cwd,
413
528
  coveragePath,
414
529
  digest: preDigest,
415
- ...definedOnly({ scope, files, ref, commit: commit || undefined }),
530
+ ...definedOnly({
531
+ scope,
532
+ files,
533
+ ref,
534
+ commit: commit || undefined,
535
+ treeDigest: preTreeDigest || undefined,
536
+ }),
416
537
  });
417
538
  if (written) {
418
539
  logger.info(
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { getQuality } from '../../../config/quality.js';
11
11
  import { resolveConfig } from '../../../config-resolver.js';
12
- import { filterFilesUnderTargets } from '../../../coverage-capture.js';
12
+ import { filterSuiteInputPaths } from '../../../coverage-capture.js';
13
13
  import { syncBranchFromBase } from '../../../git/sync-from-base.js';
14
14
  import { Logger } from '../../../Logger.js';
15
15
  import { AGENT_LABELS } from '../../../label-constants.js';
@@ -85,7 +85,7 @@ export async function runBaseSyncPhase({
85
85
  for (const line of buildStampInvalidatedWarning({
86
86
  baseBranch,
87
87
  result: syncResult,
88
- targetDirs: resolveCrapTargetDirs(resolveConfigImpl, syncCwd),
88
+ coveragePath: resolveCoveragePath(resolveConfigImpl, syncCwd),
89
89
  })) {
90
90
  progress('SYNC', line);
91
91
  }
@@ -127,17 +127,17 @@ function resolveHandedBack({ result, baseConfirmed, handBack }) {
127
127
  }
128
128
 
129
129
  /**
130
- * The CRAP scoring scope, or `[]` when unresolvable.
130
+ * The coverage artifact path, or `null` when unresolvable.
131
131
  *
132
132
  * @param {typeof resolveConfig} resolveConfigImpl
133
133
  * @param {string} cwd
134
- * @returns {string[]}
134
+ * @returns {string|null}
135
135
  */
136
- function resolveCrapTargetDirs(resolveConfigImpl, cwd) {
136
+ function resolveCoveragePath(resolveConfigImpl, cwd) {
137
137
  try {
138
- return getQuality(resolveConfigImpl({ cwd }))?.crap?.targetDirs ?? [];
138
+ return getQuality(resolveConfigImpl({ cwd }))?.crap?.coveragePath ?? null;
139
139
  } catch {
140
- return [];
140
+ return null;
141
141
  }
142
142
  }
143
143
 
@@ -146,21 +146,19 @@ const WARNED_PATH_LIMIT = 12;
146
146
  /**
147
147
  * Warn that the sync spent pre-push credit, or `[]` when it changed nothing.
148
148
  * Gate evidence is keyed on the tree, so any tracked path spends it; the
149
- * full-suite capture stamp is spent only by a path under `crap.targetDirs`.
149
+ * full-suite capture stamp is spent by any path its tree digest reads —
150
+ * everything but baseline JSON and the coverage artifact.
150
151
  * A content-changing fast-forward warns just as a merge does.
151
152
  *
152
- * @param {{ baseBranch: string, result: { kind?: string, changedPaths?: string[] }, targetDirs?: string[] }} args
153
+ * @param {{ baseBranch: string, result: { kind?: string, changedPaths?: string[] }, coveragePath?: string|null }} args
153
154
  * @returns {string[]} Progress lines, in order. Empty when nothing changed.
154
155
  */
155
- function buildStampInvalidatedWarning({ baseBranch, result, targetDirs }) {
156
+ function buildStampInvalidatedWarning({ baseBranch, result, coveragePath }) {
156
157
  const changed = Array.isArray(result?.changedPaths)
157
158
  ? result.changedPaths
158
159
  : [];
159
160
  if (changed.length === 0) return [];
160
- const dirs = Array.isArray(targetDirs) ? targetDirs : [];
161
- // An unresolvable scope cannot prove the stamp survived: fail closed.
162
- const scored =
163
- dirs.length === 0 ? changed : filterFilesUnderTargets(changed, dirs);
161
+ const scored = filterSuiteInputPaths(changed, coveragePath);
164
162
  const shown = changed.slice(0, WARNED_PATH_LIMIT);
165
163
  const overflow = changed.length - shown.length;
166
164
  return [
@@ -170,11 +168,10 @@ function buildStampInvalidatedWarning({ baseBranch, result, targetDirs }) {
170
168
  `That evidence cannot be credited; those gates re-run below.`,
171
169
  scored.length > 0
172
170
  ? `⚠️ The full-suite capture stamp is spent too: ${scored.length} of ` +
173
- `those path(s) fall under the CRAP target dirs [${dirs.join(', ')}], ` +
171
+ `those path(s) are suite inputs (anything but baseline JSON), ` +
174
172
  `so the suite re-runs against the merged tree. This is expected, not a fault.`
175
- : `⚠️ The full-suite capture stamp SURVIVES: no merged path falls under ` +
176
- `the CRAP target dirs [${dirs.join(', ')}], so the coverage artifact still ` +
177
- `describes this tree and the suite is not re-run.`,
173
+ : `⚠️ The full-suite capture stamp SURVIVES: every merged path is ` +
174
+ `baseline JSON, so the suite already ran on this tree and is not re-run.`,
178
175
  ...shown.map((f) => `⚠️ ${f}`),
179
176
  ...(overflow > 0 ? [`⚠️ …and ${overflow} more`] : []),
180
177
  ];
@@ -25,8 +25,8 @@ import { fileURLToPath } from 'node:url';
25
25
  import { spawnCaptureAsync } from '../child-exec.js';
26
26
  import { resolveLintCommand } from '../close-validation/commands.js';
27
27
  import {
28
- isCoverageCaptureActive,
29
28
  isCrapGateEnabled,
29
+ resolveCreditedDepositor,
30
30
  } from '../close-validation/gates.js';
31
31
  import {
32
32
  orchestrationLogDir,
@@ -65,7 +65,9 @@ const EXIT_CODES = Object.freeze({
65
65
  /** The § 5 output signals — a depositor that prints none deposited nothing. */
66
66
  const SIGNALS = Object.freeze({
67
67
  captureRan: /Wrote content-digest capture stamp/,
68
- captureFresh: /skipping capture/,
68
+ // A `no changed files … — skipping capture` line ran no suite: not credit.
69
+ captureFresh:
70
+ /\bis fresh(?: \((?:incremental|affected)\))? — skipping capture/,
69
71
  testRan: /✓ test passed/,
70
72
  testFresh: /⏭ test skipped/,
71
73
  seated: /seated:\s*(\d+)/,
@@ -320,11 +322,12 @@ async function stepBaseMerge(ctx) {
320
322
  /**
321
323
  * The depositor close will credit, from the one shared predicate.
322
324
  *
323
- * @param {{ config: object, scripts: Record<string, string>|null }} args
325
+ * @param {{ config: object, scripts: Record<string, string>|null, cwd: string, getChangedFilesImpl?: Function }} args
324
326
  * @returns {'coverage-capture'|'test'}
325
327
  */
326
- function selectCreditedDepositor({ config, scripts }) {
327
- return isCoverageCaptureActive(config, scripts) ? 'coverage-capture' : 'test';
328
+ function selectCreditedDepositor({ config, ...probe }) {
329
+ const baseBranch = config?.project?.baseBranch ?? 'main';
330
+ return resolveCreditedDepositor({ config, baseBranch, ...probe });
328
331
  }
329
332
 
330
333
  /** @param {object} ctx @returns {Promise<StepResult>} */
@@ -421,7 +424,7 @@ async function commitSeatedRows(ctx, total, evidencePath) {
421
424
  const creditedPrior = ctx.state.creditHead === ctx.head;
422
425
  ctx.head = headSha(ctx) ?? ctx.head;
423
426
  ctx.state.seatHead = ctx.head;
424
- // The capture stamp digests scorable sources only, so a baseline-JSON-only
427
+ // Both capture-stamp digests leave `baselines/` out, so a baseline-JSON-only
425
428
  // commit keeps the credit it already holds.
426
429
  if (creditedPrior && ctx.depositor === 'coverage-capture') {
427
430
  ctx.state.creditHead = ctx.head;
@@ -652,7 +655,7 @@ async function stepReview(ctx) {
652
655
  /**
653
656
  * The run's step order. On the evidence-gate path the `test` credit is keyed
654
657
  * on the tree, so seating (static MI) goes first and cannot void it; the
655
- * capture stamp digests scorable sources only, so a baseline seat after it
658
+ * capture stamp's digests leave `baselines/` out, so a baseline seat after it
656
659
  * keeps the stamp fresh.
657
660
  *
658
661
  * @param {'coverage-capture'|'test'} depositor
@@ -748,6 +751,7 @@ async function defaultBlock({
748
751
  * probeReview?: typeof probeHeldReviewDiff,
749
752
  * computeReview: (input: { storyId: number, cwd: string, config: object }) => Promise<{ written: boolean, path?: string, reason?: string, deposit?: object }>,
750
753
  * readPackageScriptsFn?: typeof readPackageScripts,
754
+ * getChangedFilesFn?: typeof import('../changed-files.js').getChangedFiles,
751
755
  * block?: (args: { storyId: number, config: object, reason: string, detail: string }) => Promise<void>,
752
756
  * createProviderFn?: Function,
753
757
  * progress?: (tag: string, msg: string) => void,
@@ -763,6 +767,7 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
763
767
  probeReview = probeHeldReviewDiff,
764
768
  computeReview,
765
769
  readPackageScriptsFn = readPackageScripts,
770
+ getChangedFilesFn,
766
771
  createProviderFn,
767
772
  progress = () => {},
768
773
  logDir = orchestrationLogDir(config),
@@ -796,6 +801,8 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
796
801
  depositor: selectCreditedDepositor({
797
802
  config,
798
803
  scripts: readPackageScriptsFn(cwd),
804
+ cwd,
805
+ getChangedFilesImpl: getChangedFilesFn,
799
806
  }),
800
807
  writeEvidence: (name, text) => {
801
808
  const file = path.join(logDir, `story-handoff-${storyId}-${name}.log`);
@@ -397,8 +397,15 @@ Digest § 5 states the rule and both invocations; this is what surrounds them.
397
397
  covers this change set` and pays the whole suite on the serialized tail. The
398
398
  worker's capture writes the content-digest stamp in the worktree, and
399
399
  close's capture then exits on its freshness probe without spawning
400
- `test:coverage`. A base-sync that merges a path under `crap.targetDirs`
401
- spends the stamp, and close re-captures.
400
+ `test:coverage`. The stamp holds two digests — the scorable sources and
401
+ every suite input (all tracked and dirty paths but `baselines/` and the
402
+ coverage directory) — so any later commit or base-sync outside baseline
403
+ JSON spends it, and close re-captures.
404
+ - **Predicted skip.** With `incrementalCoverage.skipWhenUnchanged` on and no
405
+ changed file under `crap.targetDirs`, the capture would run nothing, so
406
+ the shared predicate (`resolveCreditedDepositor`) picks the `test`
407
+ depositor for both close and the handoff. A `no changed files … —
408
+ skipping capture` line is never credit.
402
409
  - **Runner shapes.** A bare `npm test` earns the `test` credit **only** where
403
410
  the project's test script routes through mandrel's own runner, which prints
404
411
  the outcome. On any other runner it deposits nothing and prints nothing, so
@@ -425,9 +432,9 @@ Digest § 5 states the rule and both invocations; this is what surrounds them.
425
432
  over the in-scope files is exactly 100% — a lower rate means the artifact's
426
433
  coordinates predate the tree. The refusal names the rate, the unresolved
427
434
  files and the fix: re-run the digest § 5 capture, then seat.
428
- - **Seat order vs credit.** The capture stamp digests scorable sources only,
429
- so a baseline-JSON-only seat commit leaves it fresh and the capture credit
430
- stands. The evidence-gate `test` credit is keyed on the tree, so on that
435
+ - **Seat order vs credit.** Neither capture-stamp digest reads
436
+ `baselines/`, so a baseline-JSON-only seat commit leaves it fresh and the
437
+ capture credit stands. The evidence-gate `test` credit is keyed on the tree, so on that
431
438
  path the handoff seats first — MI is static and needs no coverage — then
432
439
  runs the suite.
433
440
 
@@ -214,6 +214,10 @@ between the installed and target versions:
214
214
  contradict a tightened rule.
215
215
  2. **Project-specific runbooks.** Sweep any docs that paraphrase framework
216
216
  workflows for renamed flags / changed exit codes / removed scripts.
217
+ 3. **Framework runbooks.** Step 1's sync output ends with one
218
+ `📖 Runbook:` line per file in `.agents/docs/runbooks/`. Read each one
219
+ the changelog touches and relay any opt-in or action it describes to the
220
+ operator. Never enable an opt-in on their behalf.
217
221
 
218
222
  Do not invent updates — silence is a valid review outcome. Stage every
219
223
  consumer-side edit alongside the dependency bump so the upgrade and the
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,26 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.74.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.73.0...mandrel-v2.74.0) (2026-10-02)
19
+
20
+
21
+ ### Added
22
+
23
+ * add a runbook index: mandrel sync (and so init/update/postinstall) list… ([#5547](https://github.com/dsj1984/mandrel/issues/5547)) ([#5549](https://github.com/dsj1984/mandrel/issues/5549)) ([f768059](https://github.com/dsj1984/mandrel/commit/f768059f7d7229c8d8c32b773b9f8e26fecec30b))
24
+ * beta: opt-in read-only Claude Code mod showing /mandrel-deliver status above the prompt ([#5544](https://github.com/dsj1984/mandrel/issues/5544)) ([#5545](https://github.com/dsj1984/mandrel/issues/5545)) ([1fa4f1f](https://github.com/dsj1984/mandrel/commit/1fa4f1f518bf20df116f1479e2db1c8cc0c2a74c))
25
+
26
+
27
+ ### Fixed
28
+
29
+ * coverage-capture credit must only vouch for a tree the suite actually ran on ([#5548](https://github.com/dsj1984/mandrel/issues/5548)) ([#5550](https://github.com/dsj1984/mandrel/issues/5550)) ([fea9553](https://github.com/dsj1984/mandrel/commit/fea955352f2524e3546cd559b4f457b017d4f9f5))
30
+
31
+ ## [2.73.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.72.0...mandrel-v2.73.0) (2026-10-02)
32
+
33
+
34
+ ### Fixed
35
+
36
+ * **baselines:** CRAP --seat-missing seats nothing, without demanding coverage, when no diff file is in the gate's scope ([#5540](https://github.com/dsj1984/mandrel/issues/5540)) ([#5541](https://github.com/dsj1984/mandrel/issues/5541)) ([169798e](https://github.com/dsj1984/mandrel/commit/169798ef90e32030148203e8e881f60ee907e404))
37
+
18
38
  ## [2.72.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.71.0...mandrel-v2.72.0) (2026-10-01)
19
39
 
20
40
 
package/lib/cli/sync.js CHANGED
@@ -30,6 +30,13 @@ export const LOCAL_ZONE_DIR = 'local';
30
30
  /** Consumer local-override basenames (`instructions.local.md`, …). */
31
31
  export const LOCAL_OVERRIDE_RE = /\.local\.[^.]+$/;
32
32
 
33
+ /**
34
+ * `.agents/`-relative directory of the operator runbooks every sync lists in
35
+ * its closing report, so `init`, `update` and the npm postinstall surface them
36
+ * too. Adding or deleting a file here is the whole registration.
37
+ */
38
+ export const RUNBOOKS_DIR = path.join('docs', 'runbooks');
39
+
33
40
  /** `.agents/`-relative path of the version marker written after each sync. */
34
41
  export const VERSION_MARKER_RELATIVE_PATH = '.mandrel-version';
35
42
 
@@ -290,6 +297,11 @@ export function runSync({
290
297
  } else {
291
298
  write(`✅ Installed ${payloadFiles.length} file(s) into ./.agents/\n`);
292
299
  }
300
+ for (const runbook of listRunbooks(payloadFiles, (rel) =>
301
+ fs.readFileSync(path.join(destRoot, rel), 'utf8'),
302
+ )) {
303
+ write(`📖 Runbook: ${runbook.title} — ${runbook.path}\n`);
304
+ }
293
305
  return {
294
306
  copied: payloadFiles.length,
295
307
  planned: payloadFiles.length,
@@ -298,6 +310,32 @@ export function runSync({
298
310
  };
299
311
  }
300
312
 
313
+ /**
314
+ * The payload's runbooks, each titled by its first `# ` heading (its file name
315
+ * when it has none), in path order.
316
+ *
317
+ * @param {string[]} payloadFiles - `.agents/`-relative payload paths.
318
+ * @param {(rel: string) => string} readText - reads one payload file.
319
+ * @returns {{ title: string, path: string }[]}
320
+ */
321
+ export function listRunbooks(payloadFiles, readText) {
322
+ return payloadFiles
323
+ .filter((rel) => path.dirname(rel) === RUNBOOKS_DIR && rel.endsWith('.md'))
324
+ .sort()
325
+ .map((rel) => {
326
+ let title;
327
+ try {
328
+ title = /^# (.+)$/m.exec(readText(rel))?.[1]?.trim();
329
+ } catch {
330
+ title = undefined;
331
+ }
332
+ return {
333
+ title: title || path.basename(rel, '.md'),
334
+ path: path.join(AGENTS_DIR, rel).split(path.sep).join('/'),
335
+ };
336
+ });
337
+ }
338
+
301
339
  /**
302
340
  * @param {string[]} argv - Subcommand arguments (after `mandrel sync`).
303
341
  * @returns {Promise<void>}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandrel",
3
- "version": "2.72.0",
3
+ "version": "2.74.0",
4
4
  "description": "Claude Code-first opinionated workflow framework: instructions, skills, rules, and SDLC workflows that govern AI coding assistants.",
5
5
  "files": [
6
6
  ".agents/",