@diffci.com/diffci 0.3.30 → 0.3.31

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.
Files changed (34) hide show
  1. package/dist-client/src/client/cli.js +26 -1
  2. package/dist-client/src/client/command-batches.d.ts +5 -0
  3. package/dist-client/src/client/command-batches.js +9 -0
  4. package/dist-client/src/client/coverage-map.d.ts +46 -0
  5. package/dist-client/src/client/coverage-map.js +213 -0
  6. package/dist-client/src/client/failure-baseline.js +0 -0
  7. package/dist-client/src/client/observe.js +3 -0
  8. package/dist-client/src/client/report.d.ts +3 -0
  9. package/dist-client/src/client/verify.d.ts +4 -0
  10. package/dist-client/src/client/verify.js +32 -2
  11. package/node_modules/@diffci.com/core/dist/git/git-diff.js +59 -0
  12. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  13. package/node_modules/@diffci.com/core/dist/git/types.d.ts +4 -0
  14. package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +11 -0
  15. package/node_modules/@diffci.com/core/dist/planner/test-command.js +65 -9
  16. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  17. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +10 -1
  18. package/node_modules/@diffci.com/core/dist/repo/file-references.js +57 -16
  19. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  20. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +3 -0
  21. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +7 -0
  22. package/node_modules/@diffci.com/core/dist/repo/impact.js +43 -16
  23. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  24. package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.d.ts +1 -1
  25. package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.js +48 -5
  26. package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.js.map +1 -1
  27. package/node_modules/@diffci.com/core/src/git/git-diff.ts +48 -0
  28. package/node_modules/@diffci.com/core/src/git/types.ts +4 -0
  29. package/node_modules/@diffci.com/core/src/planner/test-command.ts +54 -9
  30. package/node_modules/@diffci.com/core/src/repo/file-references.ts +60 -18
  31. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +3 -0
  32. package/node_modules/@diffci.com/core/src/repo/impact.ts +39 -16
  33. package/node_modules/@diffci.com/core/src/repo/test-fixture-ownership.ts +39 -5
  34. package/package.json +2 -2
@@ -54,6 +54,7 @@ import { observerIdentity } from "./package-identity.js";
54
54
  import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js";
55
55
  import { buildMissReport, formatMissReportMarkdown, parseJunit } from "./enforce-misses.js";
56
56
  import { appendOutcome, formatOutcomeSummary, outcomeLogPath, readOutcomes, summarizeOutcomes } from "./outcome-log.js";
57
+ import { buildCoverageMap, formatCoverageRun } from "./coverage-map.js";
57
58
  import { confidenceCurve, formatConfidenceCurve } from "./test-ranking.js";
58
59
  import { parseShard, readTimings, timingsFromOutcomes } from "./test-shards.js";
59
60
  import { findReceipt, findWindowStart, inferRerunArgs, mergedPullRequests, MISS_REPORT_FILE, rerunFailingFiles, spawnRunner, } from "./enforce-misses-collect.js";
@@ -392,6 +393,7 @@ async function runVerifyCommand(flags, env) {
392
393
  reuse: flags["no-reuse"] !== true && env.DIFFCI_REUSE !== "0",
393
394
  rank: flags["no-rank"] !== true && env.DIFFCI_RANK !== "0",
394
395
  failFast: flags["fail-fast"] === true,
396
+ coverage: flags["no-coverage"] !== true && env.DIFFCI_COVERAGE !== "0",
395
397
  ...(shard ? { shard } : {}),
396
398
  ...(timings ? { timings } : {}),
397
399
  };
@@ -419,6 +421,17 @@ async function runVerifyCommand(flags, env) {
419
421
  }
420
422
  return verificationExitCode(report);
421
423
  }
424
+ function runCoverageCommand(flags, env) {
425
+ const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
426
+ const command = stringFlag(flags, "command") ?? inferFullCommand(repoPath).command;
427
+ if (!command) {
428
+ console.error(`diffci coverage: no full test command could be inferred for ${repoPath}; pass --command`);
429
+ return 2;
430
+ }
431
+ const run = buildCoverageMap(repoPath, command, { timeoutMs: numberFlag(flags, "timeout-ms") ?? 60 * 60 * 1000 });
432
+ console.log(flags.json === true ? JSON.stringify({ ...(run.path ? { path: run.path } : {}), ...(run.error ? { error: run.error } : {}), exit_code: run.execution.exitCode, ...(run.map ? { tests: Object.keys(run.map.tests).length } : {}) }, null, 2) : formatCoverageRun(run));
433
+ return run.map ? 0 : 1;
434
+ }
422
435
  function runOutcomesCommand(flags, env) {
423
436
  const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
424
437
  const path = outcomeLogPath(repoPath);
@@ -559,6 +572,11 @@ function summarise(report, executionFollows = false) {
559
572
  lines.push(` graph: ${result.graph.nodes} nodes, confidence ${result.graph.effectiveConfidence ?? result.graph.confidence}`);
560
573
  if (result.fallbackReasons.length > 0) {
561
574
  lines.push(` fallback: ${result.fallbackReasons.join("; ")}`);
575
+ for (const [path, blockers] of Object.entries(result.fallbackDetails ?? {})) {
576
+ lines.push(` why ${path} is unknown:`);
577
+ for (const blocker of blockers)
578
+ lines.push(` - ${blocker}`);
579
+ }
562
580
  }
563
581
  for (const command of result.proposedCommands)
564
582
  lines.push(` would have run: ${command}`);
@@ -1140,7 +1158,7 @@ Usage:
1140
1158
  diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
1141
1159
  [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--no-checks | --checks]
1142
1160
  [--share-usage] [--no-send] [--no-log] [--no-reuse] [--no-rank] [--fail-fast]
1143
- [--shard <i/N> [--timings <file>]]
1161
+ [--shard <i/N> [--timings <file>]] [--no-coverage]
1144
1162
  diffci telemetry [--mode off|anonymous|installations] [--internal-usage]
1145
1163
  diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
1146
1164
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
@@ -1166,6 +1184,7 @@ Usage:
1166
1184
  diffci enforce-misses --junit <file> --out-dir <dir> [--repository <owner/name>] [--repo <path>]
1167
1185
  [--head <sha>] [--rerun-junit <file>] [--open-issue]
1168
1186
  diffci outcomes [--repo <path>] [--curve | --timings] [--json]
1187
+ diffci coverage [--repo <path>] [--command <cmd>] [--timeout-ms <ms>] [--json]
1169
1188
  diffci version
1170
1189
 
1171
1190
  init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json. It also
@@ -1214,6 +1233,9 @@ failed before in that log, or that the change edited, run first (--no-rank keeps
1214
1233
  selection in an N-job CI matrix; every job splits it the same way, balanced by --timings (a file from
1215
1234
  diffci outcomes --timings that every job reads) or else by file count. The full suite, test-script phases
1216
1235
  and a selection that cannot be split run in shard 1.
1236
+ coverage runs the full node:test suite once under a probe and V8 coverage and keeps, per test file, the files
1237
+ it loaded, read or listed in .git/diffci/coverage-map.json. verify then also runs tests that map connects to a
1238
+ changed file when the dependency graph did not select them; it only ever adds tests (--no-coverage ignores it).
1217
1239
  outcomes summarises that log: results, selected and full runs, top full-run reasons, agents, and possible
1218
1240
  misses (a selected run that passed and a later full run of the same tree that failed). --curve replays the
1219
1241
  failing runs to show how soon the first failure is seen, ranked by history against path order. --timings
@@ -1296,6 +1318,9 @@ async function main() {
1296
1318
  case "enforce-misses":
1297
1319
  process.exitCode = runEnforceMisses(flags, env);
1298
1320
  return;
1321
+ case "coverage":
1322
+ process.exitCode = runCoverageCommand(flags, env);
1323
+ return;
1299
1324
  case "outcomes":
1300
1325
  process.exitCode = runOutcomesCommand(flags, env);
1301
1326
  return;
@@ -28,6 +28,11 @@ export declare function splitCommand(command: string, paths: readonly string[],
28
28
  * or undefined when `command` does not end in exactly selected paths and so cannot be cut safely.
29
29
  */
30
30
  export declare function subsetCommand(command: string, paths: readonly string[], keep: ReadonlySet<string>): string | null | undefined;
31
+ /**
32
+ * `command` with `extra` test files appended (coverage-map.ts), or undefined when `command` does not end in
33
+ * exactly the selected paths or an extra path would need quoting, so it cannot be extended safely.
34
+ */
35
+ export declare function appendToCommand(command: string, paths: readonly string[], extra: readonly string[]): string | undefined;
31
36
  /** `command` split so each part fits `limit`, or `[command]` when it fits or cannot be split safely. */
32
37
  export declare function batchCommand(command: string, paths: readonly string[], limit?: number): string[];
33
38
  /**
@@ -77,6 +77,15 @@ export function subsetCommand(command, paths, keep) {
77
77
  const kept = tail.tokens.filter((entry) => keep.has(entry.path));
78
78
  return kept.length ? `${tail.prefix} ${kept.map((entry) => entry.token).join(" ")}` : null;
79
79
  }
80
+ /**
81
+ * `command` with `extra` test files appended (coverage-map.ts), or undefined when `command` does not end in
82
+ * exactly the selected paths or an extra path would need quoting, so it cannot be extended safely.
83
+ */
84
+ export function appendToCommand(command, paths, extra) {
85
+ if (!selectedTail(command, paths) || !extra.every((path) => /^[\w./@+-]+$/.test(path)))
86
+ return undefined;
87
+ return `${command} ${extra.join(" ")}`;
88
+ }
80
89
  /** `command` split so each part fits `limit`, or `[command]` when it fits or cannot be split safely. */
81
90
  export function batchCommand(command, paths, limit = COMMAND_LINE_LIMIT) {
82
91
  if (command.length <= limit || paths.length === 0)
@@ -0,0 +1,46 @@
1
+ import { type CommandMeasurement } from "./verify-savings.js";
2
+ /**
3
+ * The coverage map (2026-11-06), the idea of Datadog Test Impact Analysis and pytest-testmon.
4
+ *
5
+ * WHY. The dependency graph sees imports. A test also reaches files it never imports: a fixture it reads
6
+ * by name, a directory it lists, a module loaded through a computed specifier or a framework. Those edges
7
+ * are the commonest reason a change runs the full suite, and the ones static analysis cannot find.
8
+ *
9
+ * WHAT. `diffci coverage` runs the full test command once with every `node --test` process (one per test
10
+ * file) under a probe and V8 coverage. The probe records the files the test reads and the directories it
11
+ * lists; V8 coverage records every module it loads, ESM included. The result, per test file, is kept in
12
+ * `<git common dir>/diffci/coverage-map.json` beside the outcome log, never committed and never sent.
13
+ *
14
+ * Phase A, the only use so far: a verify run adds the tests whose map entry names a changed file and the
15
+ * graph did not select. Adding a test is always safe, so a stale map costs time, never a miss. Replacing
16
+ * a full-suite fallback with what the map says (phase B) waits until a replay shows it loses no catches.
17
+ * Only node:test is supported: Vitest and Jest run many files in one worker, so reads cannot be told apart.
18
+ */
19
+ export declare const COVERAGE_MAP_SCHEMA: "diffci.coverage-map.v1";
20
+ export interface CoverageMap {
21
+ schema: typeof COVERAGE_MAP_SCHEMA;
22
+ produced_at: string;
23
+ command: string;
24
+ /** Repository-relative files each test file loaded or read, and directories (ending in `/`) it listed. */
25
+ tests: Record<string, string[]>;
26
+ }
27
+ export declare function coverageMapPath(repoPath: string): string | undefined;
28
+ export declare function readCoverageMap(repoPath: string): CoverageMap | undefined;
29
+ export interface CoverageRun {
30
+ map?: CoverageMap;
31
+ path?: string;
32
+ execution: CommandMeasurement;
33
+ error?: string;
34
+ }
35
+ /** Runs `command` under the probe and V8 coverage, and writes the map. */
36
+ export declare function buildCoverageMap(repoPath: string, command: string, options: {
37
+ timeoutMs: number;
38
+ tailBytes?: number;
39
+ nodeOptions?: string;
40
+ }): CoverageRun;
41
+ /** Tests whose map entry names one of `changed` (or lists a directory holding one), that `selected` lacks. */
42
+ export declare function coverageAdditions(map: CoverageMap, changed: readonly string[], selected: readonly string[]): Array<{
43
+ test: string;
44
+ changed_file: string;
45
+ }>;
46
+ export declare function formatCoverageRun(run: CoverageRun): string;
@@ -0,0 +1,213 @@
1
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { isAbsolute, join, relative, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { outcomeLogPath } from "./outcome-log.js";
6
+ import { measureCommand } from "./verify-savings.js";
7
+ /**
8
+ * The coverage map (2026-11-06), the idea of Datadog Test Impact Analysis and pytest-testmon.
9
+ *
10
+ * WHY. The dependency graph sees imports. A test also reaches files it never imports: a fixture it reads
11
+ * by name, a directory it lists, a module loaded through a computed specifier or a framework. Those edges
12
+ * are the commonest reason a change runs the full suite, and the ones static analysis cannot find.
13
+ *
14
+ * WHAT. `diffci coverage` runs the full test command once with every `node --test` process (one per test
15
+ * file) under a probe and V8 coverage. The probe records the files the test reads and the directories it
16
+ * lists; V8 coverage records every module it loads, ESM included. The result, per test file, is kept in
17
+ * `<git common dir>/diffci/coverage-map.json` beside the outcome log, never committed and never sent.
18
+ *
19
+ * Phase A, the only use so far: a verify run adds the tests whose map entry names a changed file and the
20
+ * graph did not select. Adding a test is always safe, so a stale map costs time, never a miss. Replacing
21
+ * a full-suite fallback with what the map says (phase B) waits until a replay shows it loses no catches.
22
+ * Only node:test is supported: Vitest and Jest run many files in one worker, so reads cannot be told apart.
23
+ */
24
+ export const COVERAGE_MAP_SCHEMA = "diffci.coverage-map.v1";
25
+ const PROBE = `"use strict";
26
+ if (process.env.NODE_TEST_CONTEXT && process.argv[1] && process.env.DIFFCI_COVERAGE_LOG) {
27
+ const fs = require("node:fs");
28
+ const { fileURLToPath } = require("node:url");
29
+ const file = process.argv[1];
30
+ const reads = new Set();
31
+ const listed = new Set();
32
+ const note = (set, target) => {
33
+ try { set.add(typeof target === "string" ? target : target instanceof URL ? fileURLToPath(target) : Buffer.isBuffer(target) ? target.toString() : ""); } catch {}
34
+ };
35
+ const wrap = (owner, name, set) => {
36
+ const original = owner[name];
37
+ if (typeof original !== "function") return;
38
+ owner[name] = function (target, ...rest) { note(set, target); return original.call(this, target, ...rest); };
39
+ };
40
+ for (const name of ["readFileSync", "readFile", "createReadStream", "existsSync"]) wrap(fs, name, reads);
41
+ for (const name of ["readdirSync", "readdir", "opendirSync", "opendir"]) wrap(fs, name, listed);
42
+ wrap(fs.promises, "readFile", reads);
43
+ wrap(fs.promises, "readdir", listed);
44
+ wrap(fs.promises, "opendir", listed);
45
+ try { require("node:module").syncBuiltinESMExports(); } catch {}
46
+ process.on("exit", () => {
47
+ try { fs.appendFileSync(process.env.DIFFCI_COVERAGE_LOG, JSON.stringify({ file, pid: process.pid, reads: [...reads], listed: [...listed] }) + "\\n"); } catch {}
48
+ });
49
+ }
50
+ `;
51
+ export function coverageMapPath(repoPath) {
52
+ const log = outcomeLogPath(repoPath);
53
+ return log ? join(log, "..", "coverage-map.json") : undefined;
54
+ }
55
+ export function readCoverageMap(repoPath) {
56
+ const path = coverageMapPath(repoPath);
57
+ if (!path || !existsSync(path))
58
+ return undefined;
59
+ try {
60
+ const map = JSON.parse(readFileSync(path, "utf8"));
61
+ return map.schema === COVERAGE_MAP_SCHEMA && map.tests && typeof map.tests === "object" ? map : undefined;
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ }
67
+ /** Runs `command` under the probe and V8 coverage, and writes the map. */
68
+ export function buildCoverageMap(repoPath, command, options) {
69
+ const dir = mkdtempSync(join(tmpdir(), "diffci-coverage-"));
70
+ try {
71
+ const probe = join(dir, "probe.cjs");
72
+ const log = join(dir, "reads.jsonl");
73
+ const v8 = join(dir, "v8");
74
+ mkdirSync(v8);
75
+ writeFileSync(probe, PROBE);
76
+ const nodeOptions = options.nodeOptions ?? process.env.NODE_OPTIONS;
77
+ const required = `--require "${probe.split(sep).join("/")}"`;
78
+ const execution = measureCommand(command, {
79
+ cwd: repoPath,
80
+ timeoutMs: options.timeoutMs,
81
+ tailBytes: options.tailBytes ?? 4000,
82
+ env: { NODE_OPTIONS: nodeOptions?.trim() ? `${nodeOptions} ${required}` : required, DIFFCI_COVERAGE_LOG: log, NODE_V8_COVERAGE: v8 },
83
+ });
84
+ let records = [];
85
+ try {
86
+ records = readFileSync(log, "utf8").split("\n").filter(Boolean).flatMap((line) => { try {
87
+ return [JSON.parse(line)];
88
+ }
89
+ catch {
90
+ return [];
91
+ } });
92
+ }
93
+ catch { }
94
+ if (records.length === 0) {
95
+ return { execution, error: "no node --test process reported to the probe; the coverage map needs node:test, which runs each test file in its own process" };
96
+ }
97
+ const root = realpath(repoPath);
98
+ const inRepo = (absolute) => {
99
+ if (!absolute || !isAbsolute(absolute))
100
+ return undefined;
101
+ const path = relative(root, realpath(absolute)).split(sep).join("/");
102
+ if (!path || path.startsWith("..") || isAbsolute(path))
103
+ return undefined;
104
+ if (path.split("/").some((part) => part === "node_modules" || part === ".git"))
105
+ return undefined;
106
+ return path;
107
+ };
108
+ const loaded = loadedModulesByPid(v8);
109
+ const tests = {};
110
+ for (const record of records) {
111
+ const test = inRepo(record.file);
112
+ if (!test)
113
+ continue;
114
+ const entry = tests[test] ??= new Set();
115
+ for (const read of [...record.reads, ...(loaded.get(record.pid) ?? [])]) {
116
+ const path = inRepo(read);
117
+ if (path && path !== test && isFile(join(root, path)))
118
+ entry.add(path);
119
+ }
120
+ for (const listed of record.listed) {
121
+ const path = inRepo(listed);
122
+ if (path && isDirectory(join(root, path)))
123
+ entry.add(`${path}/`);
124
+ }
125
+ }
126
+ const map = {
127
+ schema: COVERAGE_MAP_SCHEMA,
128
+ produced_at: new Date().toISOString(),
129
+ command,
130
+ tests: Object.fromEntries(Object.entries(tests).sort(([a], [b]) => a.localeCompare(b)).map(([test, paths]) => [test, [...paths].sort()])),
131
+ };
132
+ const path = coverageMapPath(repoPath);
133
+ if (path) {
134
+ mkdirSync(join(path, ".."), { recursive: true });
135
+ writeFileSync(path, `${JSON.stringify(map)}\n`, "utf8");
136
+ }
137
+ return { map, ...(path ? { path } : {}), execution };
138
+ }
139
+ finally {
140
+ rmSync(dir, { recursive: true, force: true });
141
+ }
142
+ }
143
+ /** Script URLs in each process's V8 coverage file (`coverage-<pid>-<time>-<n>.json`), by pid. */
144
+ function loadedModulesByPid(dir) {
145
+ const byPid = new Map();
146
+ for (const name of readdirSync(dir)) {
147
+ const pid = Number(/^coverage-(\d+)-/.exec(name)?.[1]);
148
+ if (!Number.isFinite(pid))
149
+ continue;
150
+ try {
151
+ const { result } = JSON.parse(readFileSync(join(dir, name), "utf8"));
152
+ const files = result.flatMap(({ url }) => { try {
153
+ return url.startsWith("file:") ? [fileURLToPath(url)] : isAbsolute(url) ? [url] : [];
154
+ }
155
+ catch {
156
+ return [];
157
+ } });
158
+ byPid.set(pid, [...(byPid.get(pid) ?? []), ...files]);
159
+ }
160
+ catch { }
161
+ }
162
+ return byPid;
163
+ }
164
+ function realpath(path) {
165
+ try {
166
+ return realpathSync.native(path);
167
+ }
168
+ catch {
169
+ return path;
170
+ }
171
+ }
172
+ function isFile(path) {
173
+ try {
174
+ return statSync(path).isFile();
175
+ }
176
+ catch {
177
+ return false;
178
+ }
179
+ }
180
+ function isDirectory(path) {
181
+ try {
182
+ return statSync(path).isDirectory();
183
+ }
184
+ catch {
185
+ return false;
186
+ }
187
+ }
188
+ /** Tests whose map entry names one of `changed` (or lists a directory holding one), that `selected` lacks. */
189
+ export function coverageAdditions(map, changed, selected) {
190
+ const have = new Set(selected);
191
+ const additions = [];
192
+ for (const [test, paths] of Object.entries(map.tests)) {
193
+ if (have.has(test))
194
+ continue;
195
+ const hit = changed.find((file) => paths.some((path) => path === file || (path.endsWith("/") && file.startsWith(path))));
196
+ if (hit)
197
+ additions.push({ test, changed_file: hit });
198
+ }
199
+ return additions;
200
+ }
201
+ export function formatCoverageRun(run) {
202
+ if (!run.map)
203
+ return `diffci coverage: ${run.error ?? "no map was built"}`;
204
+ const tests = Object.keys(run.map.tests).length;
205
+ const files = new Set(Object.values(run.map.tests).flat()).size;
206
+ const lines = [`DiffCI coverage map: ${tests} test file(s), ${files} file(s) and directories they load, read or list`];
207
+ if (run.path)
208
+ lines.push(` written to ${run.path} (inside .git, never committed or sent)`);
209
+ if (run.execution.exitCode !== 0)
210
+ lines.push(` the test command exited ${String(run.execution.exitCode)}; the map still records what each test touched`);
211
+ lines.push(" verify now adds tests this map connects to a changed file when the dependency graph did not select them");
212
+ return lines.join("\n");
213
+ }
@@ -250,6 +250,8 @@ export async function observe(options) {
250
250
  const outsideSuite = [...(impact.testsOutsideFullSuite ?? []).map((test) => test.path), ...planOutside].sort();
251
251
  const outsidePlan = outsideSuite.length ? planSelectiveTestCommands(profile, outsideSuite) : undefined;
252
252
  markPhase("impactAndCommands");
253
+ // Newer than some bundled engines, which never return it.
254
+ const fallbackDetails = impact.fallbackDetails;
253
255
  return finish("OBSERVED", "complete", {
254
256
  result: {
255
257
  mode: impact.fallbackRequired ? "FULL" : "SELECTIVE",
@@ -265,6 +267,7 @@ export async function observe(options) {
265
267
  outsideSuiteCommands: outsidePlan?.refusalReason ? [] : (outsidePlan?.commands ?? []).map(commandSpecToString),
266
268
  } : {}),
267
269
  fallbackReasons: impact.fallbackReasons,
270
+ ...(fallbackDetails ? { fallbackDetails } : {}),
268
271
  proposedCommands: (commandPlan?.commands ?? []).map(commandSpecToString),
269
272
  ...(impact.testPhases?.length ? { testPhases: [...impact.testPhases] } : {}),
270
273
  workspaceCommands: Boolean(profile.workspaceTestPackages?.length),
@@ -192,6 +192,9 @@ export interface ObservationResult {
192
192
  * are commands and are not redacted. */
193
193
  testPhases?: string[];
194
194
  fallbackReasons: string[];
195
+ /** For each changed file whose readers could not be resolved, every blocker with the readers leading to it.
196
+ * Like `fallbackReasons`, these name repository paths. Present only on a fallback. */
197
+ fallbackDetails?: Record<string, string[]>;
195
198
  /** The command DiffCI would have run. Present even in observe mode - it is the claim being tested. */
196
199
  proposedCommands: string[];
197
200
  /** Workspace execution can widen affected files to whole state-sharing suites. */
@@ -86,6 +86,8 @@ export interface VerificationReport {
86
86
  total: number;
87
87
  timings: "file" | "equal";
88
88
  };
89
+ /** Tests the coverage map added to the selection (coverage-map.ts), when it added any. */
90
+ coverage_added?: string[];
89
91
  }
90
92
  interface VerifyOptions {
91
93
  repoPath: string;
@@ -108,6 +110,8 @@ interface VerifyOptions {
108
110
  /** Run only this job's share of the selection (`--shard i/N`), balanced by `timings` when given. */
109
111
  shard?: ShardSpec;
110
112
  timings?: TimingsFile;
113
+ /** False ignores the coverage map (`--no-coverage`). */
114
+ coverage?: boolean;
111
115
  }
112
116
  export interface VerifyChangedOptions extends VerifyOptions {
113
117
  }
@@ -1,7 +1,8 @@
1
1
  import { mkdtempSync, rmSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
- import { batchCommand, measureCommands, orderCommand, splitCommand, subsetCommand } from "./command-batches.js";
4
+ import { appendToCommand, batchCommand, measureCommands, orderCommand, splitCommand, subsetCommand } from "./command-batches.js";
5
+ import { coverageAdditions, readCoverageMap } from "./coverage-map.js";
5
6
  import { checkAtBaseline, compareWithBaseline } from "./failure-baseline.js";
6
7
  import { collectEnforcementContext, evaluateEnforcement } from "./enforce-policy.js";
7
8
  import { inferFullCommand, inferSelectedCommand, inferSelectedCommands } from "./full-command.js";
@@ -110,6 +111,29 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
110
111
  report.snapshot.after_tree_sha = afterAnalysis.treeSha;
111
112
  return report;
112
113
  }
114
+ // Coverage edges, phase A (coverage-map.ts, 2026-11-06): tests the coverage map connects to a changed
115
+ // file and the graph did not select are added. Only ever adds; a selected command that cannot take them
116
+ // runs the full suite instead. Never under enforce or path redaction.
117
+ const coverageAdded = [];
118
+ if (result && result.mode === "SELECTIVE" && !enforcement && !options.redactPaths && options.coverage !== false) {
119
+ const map = readCoverageMap(options.repoPath);
120
+ const additions = map ? coverageAdditions(map, result.changedFiles, result.selectedTests) : [];
121
+ if (additions.length) {
122
+ const tests = additions.map((addition) => addition.test);
123
+ const extended = result.proposedCommands.length === 1 ? appendToCommand(result.proposedCommands[0], result.selectedTests, tests) : undefined;
124
+ coverageAdded.push(...tests);
125
+ result = extended
126
+ ? {
127
+ ...result,
128
+ selectedTests: [...result.selectedTests, ...tests],
129
+ proposedCommands: [extended],
130
+ selectionReasons: { ...result.selectionReasons, ...Object.fromEntries(additions.map((addition) => [addition.test, { reason: "COVERAGE", changed_file: addition.changed_file }])) },
131
+ }
132
+ : { ...result, mode: "FULL", fallbackReasons: [...result.fallbackReasons, `the coverage map adds ${tests.length} test file(s) the selected command cannot include, such as ${tests[0]}`] };
133
+ counts.testsSelected = result.selectedTests.length;
134
+ analysis.fallback_reasons = result.fallbackReasons;
135
+ }
136
+ }
113
137
  // --shard i/N (test-shards.ts): this job's share of the selection, split the same way in every job.
114
138
  const shard = options.shard;
115
139
  const shardTests = shard && result && !enforcedFull && result.mode === "SELECTIVE"
@@ -118,7 +142,11 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
118
142
  const executable = enforcedFull || !result
119
143
  ? fullSelection(options.repoPath, `enforce fallback (${enforcement?.fired_fallback}): ${enforcement?.detail}`)
120
144
  : executableSelection(options.repoPath, result, rankedOrdering(options, result), shard && shardTests ? { tests: new Set(shardTests), first: shard.index === 1 } : undefined);
121
- const { selection, command, commands, reason, outsideSuite } = executable;
145
+ const { selection, command, commands, outsideSuite } = executable;
146
+ const reason = coverageAdded.length && selection === "selected"
147
+ ? `${executable.reason}; the coverage map added ${coverageAdded.length} test file(s) the dependency graph did not select (${coverageAdded.slice(0, 3).join(", ")})`
148
+ : executable.reason;
149
+ const coverageField = coverageAdded.length && selection === "selected" ? { coverage_added: coverageAdded } : {};
122
150
  const unshardable = "unshardable" in executable && executable.unshardable;
123
151
  const shardField = shard ? { shard: { index: shard.index, total: shard.total, timings: options.timings ? "file" : "equal" } } : {};
124
152
  if (shard) {
@@ -184,6 +212,7 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
184
212
  required_actions: [],
185
213
  reused_from,
186
214
  ...shardField,
215
+ ...coverageField,
187
216
  };
188
217
  }
189
218
  const checkBaseline = options.baselineOnFailure && checkBase && checkHead
@@ -312,6 +341,7 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
312
341
  required_actions: verification === "passed" ? [] : [finalReason + baselineNote],
313
342
  ...(failureBaseline ? { failure_baseline: failureBaseline } : {}),
314
343
  ...shardField,
344
+ ...coverageField,
315
345
  };
316
346
  }
317
347
  function stamped(report, version) {
@@ -284,6 +284,7 @@ export function testListEdit(oldBody, newBody) {
284
284
  return { added, removed };
285
285
  }
286
286
  const DEPENDENCY_FIELDS = new Set(["dependencies", "devDependencies", "optionalDependencies"]);
287
+ const PACKAGE_LOCKFILES = ["package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml", "bun.lock", "bun.lockb"];
287
288
  /** Exact root requests for the supported Classic layout. Unlike scriptRecord, never discard an
288
289
  * invalid dependency value: an omitted root would make the lockfile attribution incomplete. */
289
290
  function yarnDirectDependencies(content) {
@@ -716,6 +717,64 @@ export async function analyzeGitDelta(options = {}) {
716
717
  }
717
718
  }
718
719
  }
720
+ // 2026-11-05: without a committed lockfile every install resolves each request afresh, so an edit
721
+ // limited to dependency requests reaches only the packages whose request changed and what they
722
+ // install; importers of those packages are selected like a lockfile-attributed change. LobeHub ignores
723
+ // pnpm-lock.yaml, and each of its workspace dependency bumps ran the full suite. A lockfile that governs
724
+ // any changed manifest, a local (`workspace:`, `link:`, `file:`) request, a scripts edit, any other
725
+ // behavioral field, or a package-manager configuration change keeps the global signal.
726
+ const manifests = filesWithBinary.filter((f) => f.changeType === "modified" && posix.basename(f.path) === "package.json" && !f.path.split("/").includes("node_modules"));
727
+ const managerConfiguration = allPaths.some((path) => posix.basename(path) !== "package.json"
728
+ && (LOCKFILE.test(posix.basename(path)) || /^(?:\.npmrc|\.yarnrc(?:\.yml)?|pnpm-workspace\.yaml|\.pnpmfile\.cjs|bunfig\.toml)$/.test(posix.basename(path))));
729
+ if (manifests.length > 0 && !manifests.some((f) => narrowed.has(f)) && !analysis.lockfileChanged && !managerConfiguration) {
730
+ const lockfileGoverns = (path) => {
731
+ for (let dir = posix.dirname(path);; dir = posix.dirname(dir)) {
732
+ const prefix = dir === "." ? "" : `${dir}/`;
733
+ if (PACKAGE_LOCKFILES.some((name) => [baseSha, headSha].some((sha) => readFileAtSha(sha, prefix + name, repoPath) !== undefined)))
734
+ return true;
735
+ if (dir === ".")
736
+ return false;
737
+ }
738
+ };
739
+ const edits = manifests.map((file) => {
740
+ const before = readFileAtSha(baseSha, file.path, repoPath);
741
+ const after = readFileAtSha(headSha, file.path, repoPath);
742
+ const change = packageJsonChange(before, after);
743
+ const localChanged = change.changedDependencies.some((name) => [before, after].some((content) => {
744
+ try {
745
+ const json = JSON.parse(content ?? "");
746
+ return [...DEPENDENCY_FIELDS].some((field) => /^(?:workspace|link|file|portal):/.test(scriptRecord(json[field])?.[name] ?? ""));
747
+ }
748
+ catch {
749
+ return true;
750
+ }
751
+ }));
752
+ const eligible = change.kind !== "behavioral" && !localChanged
753
+ && JSON.stringify(parsePackageScripts(before)) === JSON.stringify(parsePackageScripts(after));
754
+ return { file, change, eligible };
755
+ });
756
+ if (edits.some((edit) => edit.change.kind === "dependencies") && edits.every((edit) => edit.eligible) && !manifests.some((f) => lockfileGoverns(f.path))) {
757
+ const names = new Set(analysis.changedDependencies ?? []);
758
+ const specifiersOnly = [];
759
+ for (const { file, change } of edits) {
760
+ for (const name of change.changedDependencies)
761
+ names.add(name);
762
+ narrowed.add(file);
763
+ if (change.kind !== "metadata" && !referenceResolvedPaths.includes(file.path))
764
+ referenceResolvedPaths.push(file.path);
765
+ if (change.kind === "dependencies" && change.specifiersOnly)
766
+ specifiersOnly.push(file.path);
767
+ if (file.path === "package.json" && change.testScriptAddedPaths.length > 0)
768
+ analysis.testScriptAddedPaths = change.testScriptAddedPaths;
769
+ }
770
+ analysis.dependencyManifestChanged = false;
771
+ analysis.changedDependencies = [...names].sort();
772
+ if (specifiersOnly.includes("package.json"))
773
+ analysis.packageJsonSpecifiersOnly = true;
774
+ if (specifiersOnly.length > 0)
775
+ analysis.specifiersOnlyManifests = specifiersOnly.sort();
776
+ }
777
+ }
719
778
  // 2026-11-03: a workspace package's package.json used to be an unknown file and a full run. One whose
720
779
  // edit is limited to metadata and data fields (a release bumping `version`) cannot change how tests
721
780
  // run, so its readers are resolved like the root's. A script edit stays unknown: the root's test