mandrel 2.73.0 → 2.75.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.
@@ -0,0 +1,90 @@
1
+ /** The six stages of a /mandrel-deliver Story, in order. */
2
+ export type StageName =
3
+ | 'start'
4
+ | 'build'
5
+ | 'check'
6
+ | 'handoff'
7
+ | 'close'
8
+ | 'merge';
9
+
10
+ /** One stage as the Details pane lists it; times in epoch milliseconds. */
11
+ export type StageRow = {
12
+ name: StageName;
13
+ startedAt: number | null;
14
+ /** The next stage's start, or null while this one is current or pending. */
15
+ endedAt: number | null;
16
+ };
17
+
18
+ /** One close phase: its recorded duration and the learned median, in seconds. */
19
+ export type PhaseRow = {
20
+ name: string;
21
+ seconds: number | null;
22
+ usualSeconds: number | null;
23
+ };
24
+
25
+ /** The Story the band follows: in flight, or the newest recent result. */
26
+ export type Focus = {
27
+ storyId: number;
28
+ title: string | null;
29
+ /** `in-flight`, or the terminal envelope's `status`. */
30
+ status: string;
31
+ stage: StageName;
32
+ /** The current stage's step detail, already worded. */
33
+ detail: string;
34
+ stages: StageRow[];
35
+ handoffSteps: { name: string; at: number }[];
36
+ closePhases: PhaseRow[];
37
+ prNumber: number | null;
38
+ checksStatus: string | null;
39
+ /** The envelope's `elapsedSeconds`, for a finished result. */
40
+ elapsedSeconds: number | null;
41
+ /** Milliseconds into the current phase, while in flight. */
42
+ phaseElapsedMs: number | null;
43
+ /** The learned median of the current phase, once it has 3+ samples. */
44
+ usualMs: number | null;
45
+ isStalled: boolean;
46
+ /** Minutes the gate log has been quiet, when the 10-minute rule fired. */
47
+ idleMinutes: number | null;
48
+ /** `blocked.blockClass` or `failure.reason`. */
49
+ problem: string | null;
50
+ nextCommand: string | null;
51
+ /** Bullets in `follow-ups-rollup-<id>.md`, when it exists. */
52
+ followUps: number | null;
53
+ };
54
+
55
+ /** The newest live multi-Story run ledger. */
56
+ export type RunLine = {
57
+ landed: number;
58
+ total: number;
59
+ current: { storyId: number; stage: string } | null;
60
+ queued: number;
61
+ };
62
+
63
+ export type Snapshot = {
64
+ focus: Focus | null;
65
+ run: RunLine | null;
66
+ /** When the scan ran, epoch milliseconds; 0 before the first. */
67
+ scannedAt: number;
68
+ };
69
+
70
+ /** Per close phase: the median of the newest terminal envelopes' timings. */
71
+ export type Learned = {
72
+ /** When the medians were last computed; 0 before the first pass. */
73
+ at: number;
74
+ phases: Record<string, { medianSeconds: number; samples: number }>;
75
+ };
76
+
77
+ declare module 'claude-code' {
78
+ interface PluginState {
79
+ 'mandrel-status': {
80
+ snapshot: Snapshot;
81
+ /** `<storyId>:<mtimeMs>` of every envelope already seen. */
82
+ seen: string[];
83
+ /** False until the first scan, which records envelopes without a toast. */
84
+ isSeeded: boolean;
85
+ learned: Learned;
86
+ /** The focus Story the person hid the band for; it shows again on a new one. */
87
+ hiddenFor: number | null;
88
+ };
89
+ }
90
+ }
@@ -0,0 +1,48 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/dsj1984/mandrel/blob/main/.agents/schemas/story-progress.schema.json",
4
+ "title": "story-progress",
5
+ "description": "The live progress record a Story's handoff and close rewrite at every step or phase change (Story #5553), at <tempRoot>/orchestration/story-progress-<id>.json. It exists because push, PR, review, auto-merge and the merge wait leave nothing on disk until the terminal envelope. Advisory only: nothing in Mandrel reads it to decide anything, every write is best effort, and each write is atomic (a <file>.tmp sibling renamed over the target).",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": [
9
+ "kind",
10
+ "storyId",
11
+ "stage",
12
+ "phase",
13
+ "stageStartedAt",
14
+ "phaseStartedAt",
15
+ "prNumber",
16
+ "updatedAt"
17
+ ],
18
+ "properties": {
19
+ "kind": { "type": "string", "const": "story-progress" },
20
+ "storyId": { "type": "integer", "minimum": 1 },
21
+ "stage": {
22
+ "type": "string",
23
+ "enum": ["handoff", "close"],
24
+ "description": "handoff — the worker's story-handoff.js run; close — single-story-close.js."
25
+ },
26
+ "phase": {
27
+ "type": "string",
28
+ "minLength": 1,
29
+ "description": "For close, the phase name close passes to setPhase (the phaseDurations keys). For handoff, the step name: preflight, base-merge, credited-run, seat, push, review."
30
+ },
31
+ "stageStartedAt": {
32
+ "type": "string",
33
+ "format": "date-time",
34
+ "description": "When this handoff or close run started; fixed for the run."
35
+ },
36
+ "phaseStartedAt": {
37
+ "type": "string",
38
+ "format": "date-time",
39
+ "description": "When the current phase started; resets on each phase change."
40
+ },
41
+ "prNumber": {
42
+ "type": ["integer", "null"],
43
+ "minimum": 1,
44
+ "description": "The Story PR's number from the moment close parses it; null before then and throughout handoff."
45
+ },
46
+ "updatedAt": { "type": "string", "format": "date-time" }
47
+ }
48
+ }
@@ -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',
@@ -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.',
@@ -229,6 +229,21 @@ export function storyReviewDepositPath(sid, config) {
229
229
  );
230
230
  }
231
231
 
232
+ /**
233
+ * Live phase record for a Story's handoff or close. The trailing
234
+ * `-<id>` keys it to the Story for the retention purge.
235
+ *
236
+ * @param {number} sid
237
+ * @param {object} [config]
238
+ * @returns {string}
239
+ */
240
+ export function storyProgressPath(sid, config) {
241
+ return path.join(
242
+ orchestrationLogDir(config),
243
+ `story-progress-${storyId(sid)}.json`,
244
+ );
245
+ }
246
+
232
247
  const runId = (id) => {
233
248
  if (!Number.isInteger(id) || id <= 0) {
234
249
  throw new Error(`[temp-paths] runId must be a positive integer; got ${id}`);
@@ -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(