@diffci.com/diffci 0.3.29 → 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 (111) hide show
  1. package/dist-client/src/client/cli.js +78 -5
  2. package/dist-client/src/client/command-batches.d.ts +22 -0
  3. package/dist-client/src/client/command-batches.js +82 -9
  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/outcome-log.d.ts +40 -0
  9. package/dist-client/src/client/outcome-log.js +38 -1
  10. package/dist-client/src/client/report.d.ts +3 -0
  11. package/dist-client/src/client/selected-coverage.d.ts +3 -0
  12. package/dist-client/src/client/selected-coverage.js +35 -5
  13. package/dist-client/src/client/test-ranking.d.ts +39 -0
  14. package/dist-client/src/client/test-ranking.js +127 -0
  15. package/dist-client/src/client/test-results.d.ts +27 -0
  16. package/dist-client/src/client/test-results.js +54 -0
  17. package/dist-client/src/client/test-shards.d.ts +36 -0
  18. package/dist-client/src/client/test-shards.js +68 -0
  19. package/dist-client/src/client/verify-savings.d.ts +6 -0
  20. package/dist-client/src/client/verify-savings.js +4 -0
  21. package/dist-client/src/client/verify.d.ts +36 -1
  22. package/dist-client/src/client/verify.js +171 -13
  23. package/node_modules/@babel/helper-string-parser/lib/index.js +5 -5
  24. package/node_modules/@babel/helper-string-parser/lib/index.js.map +1 -1
  25. package/node_modules/@babel/helper-string-parser/package.json +1 -1
  26. package/node_modules/@babel/parser/lib/index.js +6306 -6143
  27. package/node_modules/@babel/parser/lib/index.js.map +1 -1
  28. package/node_modules/@babel/parser/package.json +3 -3
  29. package/node_modules/@babel/types/lib/definitions/typescript.js +2 -1
  30. package/node_modules/@babel/types/lib/definitions/typescript.js.map +1 -1
  31. package/node_modules/@babel/types/package.json +3 -3
  32. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  33. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +2 -1
  34. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  35. package/node_modules/@diffci.com/core/dist/git/git-diff.js +59 -0
  36. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/git/types.d.ts +4 -0
  38. package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +11 -0
  39. package/node_modules/@diffci.com/core/dist/planner/test-command.js +65 -9
  40. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  41. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +10 -1
  42. package/node_modules/@diffci.com/core/dist/repo/file-references.js +96 -18
  43. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  44. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +4 -1
  45. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +20 -0
  46. package/node_modules/@diffci.com/core/dist/repo/impact.js +147 -25
  47. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  48. package/node_modules/@diffci.com/core/dist/repo/repo-config.d.ts +11 -0
  49. package/node_modules/@diffci.com/core/dist/repo/repo-config.js +11 -1
  50. package/node_modules/@diffci.com/core/dist/repo/repo-config.js.map +1 -1
  51. package/node_modules/@diffci.com/core/dist/repo/route-visits.d.ts +34 -0
  52. package/node_modules/@diffci.com/core/dist/repo/route-visits.js +93 -0
  53. package/node_modules/@diffci.com/core/dist/repo/route-visits.js.map +1 -0
  54. package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.d.ts +1 -1
  55. package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.js +48 -5
  56. package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.js.map +1 -1
  57. package/node_modules/@diffci.com/core/package.json +3 -3
  58. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +2 -1
  59. package/node_modules/@diffci.com/core/src/git/git-diff.ts +48 -0
  60. package/node_modules/@diffci.com/core/src/git/types.ts +4 -0
  61. package/node_modules/@diffci.com/core/src/planner/test-command.ts +54 -9
  62. package/node_modules/@diffci.com/core/src/repo/file-references.ts +92 -20
  63. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +5 -0
  64. package/node_modules/@diffci.com/core/src/repo/impact.ts +134 -25
  65. package/node_modules/@diffci.com/core/src/repo/repo-config.ts +23 -1
  66. package/node_modules/@diffci.com/core/src/repo/route-visits.ts +88 -0
  67. package/node_modules/@diffci.com/core/src/repo/test-fixture-ownership.ts +39 -5
  68. package/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js +4 -3
  69. package/node_modules/@vue/compiler-core/dist/compiler-core.cjs.prod.js +4 -3
  70. package/node_modules/@vue/compiler-core/dist/compiler-core.esm-bundler.js +4 -3
  71. package/node_modules/@vue/compiler-core/package.json +4 -4
  72. package/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.js +9 -6
  73. package/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.prod.js +41 -4
  74. package/node_modules/@vue/compiler-dom/dist/compiler-dom.esm-browser.js +10 -7
  75. package/node_modules/@vue/compiler-dom/dist/compiler-dom.esm-browser.prod.js +12 -11
  76. package/node_modules/@vue/compiler-dom/dist/compiler-dom.esm-bundler.js +5 -3
  77. package/node_modules/@vue/compiler-dom/dist/compiler-dom.global.js +10 -7
  78. package/node_modules/@vue/compiler-dom/dist/compiler-dom.global.prod.js +12 -11
  79. package/node_modules/@vue/compiler-dom/package.json +3 -3
  80. package/node_modules/@vue/compiler-sfc/dist/compiler-sfc.cjs.js +155 -20
  81. package/node_modules/@vue/compiler-sfc/dist/compiler-sfc.esm-browser.js +431 -98
  82. package/node_modules/@vue/compiler-sfc/package.json +10 -10
  83. package/node_modules/@vue/compiler-ssr/dist/compiler-ssr.cjs.js +1 -1
  84. package/node_modules/@vue/compiler-ssr/package.json +3 -3
  85. package/node_modules/@vue/shared/dist/shared.cjs.js +51 -32
  86. package/node_modules/@vue/shared/dist/shared.cjs.prod.js +51 -32
  87. package/node_modules/@vue/shared/dist/shared.d.ts +2 -1
  88. package/node_modules/@vue/shared/dist/shared.esm-bundler.js +51 -32
  89. package/node_modules/@vue/shared/package.json +1 -1
  90. package/node_modules/nanoid/async/index.d.cts +56 -0
  91. package/node_modules/nanoid/index.cjs +12 -7
  92. package/node_modules/nanoid/index.js +1 -1
  93. package/node_modules/nanoid/package.json +3 -3
  94. package/node_modules/postcss/lib/input.js +1 -1
  95. package/node_modules/postcss/lib/lazy-result.js +1 -1
  96. package/node_modules/postcss/lib/list.js +19 -1
  97. package/node_modules/postcss/lib/map-generator.js +9 -3
  98. package/node_modules/postcss/lib/no-work-result.js +1 -1
  99. package/node_modules/postcss/lib/node.js +2 -2
  100. package/node_modules/postcss/lib/parser.js +6 -1
  101. package/node_modules/postcss/lib/processor.js +1 -1
  102. package/node_modules/postcss/lib/stringifier.js +16 -28
  103. package/node_modules/postcss/lib/stringify.js +84 -2
  104. package/node_modules/postcss/lib/warning.js +1 -0
  105. package/node_modules/postcss/package.json +3 -3
  106. package/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +19 -18
  107. package/node_modules/yaml/browser/dist/nodes/Alias.js +25 -23
  108. package/node_modules/yaml/dist/compose/resolve-flow-scalar.js +19 -18
  109. package/node_modules/yaml/dist/nodes/Alias.js +25 -23
  110. package/node_modules/yaml/package.json +1 -1
  111. package/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import type { SelectionReason } from "./report.js";
2
+ import type { TestFileResult } from "./test-results.js";
2
3
  import type { VerificationReport } from "./verify.js";
3
4
  /**
4
5
  * The local outcome log (2026-11-05).
@@ -39,9 +40,48 @@ export interface OutcomeRecord {
39
40
  decision: string;
40
41
  status: string;
41
42
  wall_ms?: number;
43
+ command?: string;
42
44
  }>;
45
+ /** The test command as run, and the Node version it ran under (2026-11-06). */
46
+ command?: string;
47
+ node_version?: string;
48
+ /** Each test file's result and duration, where the runner showed them (test-results.ts, 2026-11-06). */
49
+ test_results?: TestFileResult[];
50
+ /** When this run ran nothing and reused an earlier pass: that run's `produced_at` (reusablePass). */
51
+ reused_from?: string;
43
52
  }
44
53
  export declare function outcomeRecord(report: VerificationReport, env?: Record<string, string | undefined>): OutcomeRecord;
54
+ /** What a verify run is about to execute, for reusablePass. */
55
+ export interface ReuseQuery {
56
+ tree_sha: string;
57
+ diffci_version: string;
58
+ node_version: string;
59
+ selection: "selected" | "full";
60
+ selected_tests: readonly string[];
61
+ /** The command this run would execute, and the repository's full test command. */
62
+ command: string;
63
+ full_command?: string;
64
+ /** The gate checks this run would execute (decision RUN or NARROWED), with their exact commands. */
65
+ checks: ReadonlyArray<{
66
+ id: string;
67
+ command: string;
68
+ }>;
69
+ }
70
+ /**
71
+ * Result reuse by tree (2026-11-06), the idea of Turborepo's and Bazel's caches applied to a verify run.
72
+ *
73
+ * WHY. Agents re-run verify on a tree that has not changed since the last pass: after a commit, after a
74
+ * rebase that changed nothing, from a second worktree. Running the same tests on the same bytes again
75
+ * learns nothing.
76
+ *
77
+ * WHAT. The newest earlier run that passed on the same tree, under the same DiffCI and Node versions, and
78
+ * that covers what this run would execute: a full run of the same full command, or a selected run whose
79
+ * tests include every test selected now. Every gate check this run would execute must have passed in it
80
+ * with the identical command, so a check narrowed to other files does not count. Only passes are reused;
81
+ * a reused run is never itself a source. The tree covers the lockfile but not node_modules, so a changed
82
+ * install with an unchanged lockfile is the one thing reuse cannot see; `--no-reuse` runs everything.
83
+ */
84
+ export declare function reusablePass(records: readonly OutcomeRecord[], query: ReuseQuery): OutcomeRecord | undefined;
45
85
  /** `<git common dir>/diffci/outcomes.jsonl`, or undefined outside a Git repository. */
46
86
  export declare function outcomeLogPath(repoPath: string): string | undefined;
47
87
  /** Appends the run to the log. Best effort: a log that cannot be written never fails verification. */
@@ -36,9 +36,46 @@ export function outcomeRecord(report, env = {}) {
36
36
  ...(report.analysis.duration_ms !== undefined ? { analysis_ms: report.analysis.duration_ms } : {}),
37
37
  ...(report.execution ? { tests_ms: report.execution.wallMs, exit_code: report.execution.exitCode } : {}),
38
38
  ...(report.execution?.failingTests?.length ? { failing_tests: report.execution.failingTests } : {}),
39
- ...(report.checks ? { checks: report.checks.map((check) => ({ id: check.id, decision: check.decision, status: check.status, ...(check.wall_ms !== undefined ? { wall_ms: check.wall_ms } : {}) })) } : {}),
39
+ ...(report.checks ? { checks: report.checks.map((check) => ({ id: check.id, decision: check.decision, status: check.status, ...(check.wall_ms !== undefined ? { wall_ms: check.wall_ms } : {}), command: check.command })) } : {}),
40
+ ...(report.command ? { command: report.commands?.join(" && ") ?? report.command } : {}),
41
+ node_version: process.versions.node,
42
+ ...(report.execution?.testResults?.length ? { test_results: report.execution.testResults } : {}),
43
+ ...(report.reused_from ? { reused_from: report.reused_from.produced_at } : {}),
40
44
  };
41
45
  }
46
+ /**
47
+ * Result reuse by tree (2026-11-06), the idea of Turborepo's and Bazel's caches applied to a verify run.
48
+ *
49
+ * WHY. Agents re-run verify on a tree that has not changed since the last pass: after a commit, after a
50
+ * rebase that changed nothing, from a second worktree. Running the same tests on the same bytes again
51
+ * learns nothing.
52
+ *
53
+ * WHAT. The newest earlier run that passed on the same tree, under the same DiffCI and Node versions, and
54
+ * that covers what this run would execute: a full run of the same full command, or a selected run whose
55
+ * tests include every test selected now. Every gate check this run would execute must have passed in it
56
+ * with the identical command, so a check narrowed to other files does not count. Only passes are reused;
57
+ * a reused run is never itself a source. The tree covers the lockfile but not node_modules, so a changed
58
+ * install with an unchanged lockfile is the one thing reuse cannot see; `--no-reuse` runs everything.
59
+ */
60
+ export function reusablePass(records, query) {
61
+ for (let index = records.length - 1; index >= 0; index -= 1) {
62
+ const run = records[index];
63
+ if (run.reused_from || run.verification !== "passed" || run.tree_sha !== query.tree_sha)
64
+ continue;
65
+ if (run.diffci_version !== query.diffci_version || run.node_version !== query.node_version)
66
+ continue;
67
+ const tests = run.selection === "full"
68
+ ? run.command !== undefined && run.command === (query.selection === "full" ? query.command : query.full_command)
69
+ : run.selection === "selected" && query.selection === "selected" && run.selected_tests !== undefined
70
+ && query.selected_tests.every((test) => run.selected_tests.includes(test));
71
+ if (!tests)
72
+ continue;
73
+ const passedChecks = new Set((run.checks ?? []).filter((check) => check.status === "passed" && check.command).map((check) => `${check.id}\n${check.command}`));
74
+ if (query.checks.every((check) => passedChecks.has(`${check.id}\n${check.command}`)))
75
+ return run;
76
+ }
77
+ return undefined;
78
+ }
42
79
  /** `<git common dir>/diffci/outcomes.jsonl`, or undefined outside a Git repository. */
43
80
  export function outcomeLogPath(repoPath) {
44
81
  try {
@@ -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. */
@@ -1,3 +1,4 @@
1
+ import { type TestFileResult } from "./test-results.js";
1
2
  /**
2
3
  * Selected tests the runner would never execute (2026-11-01).
3
4
  *
@@ -30,6 +31,8 @@ export interface NodeTestTrace {
30
31
  env: Record<string, string>;
31
32
  /** Repository-relative paths of the files that started, or undefined when none did. */
32
33
  read(): string[] | undefined;
34
+ /** Each test process that exited: its file, duration and whether it passed. */
35
+ results(): TestFileResult[];
33
36
  dispose(): void;
34
37
  }
35
38
  export declare function traceNodeTestFiles(cwd: string, nodeOptions?: string | undefined): NodeTestTrace;
@@ -1,6 +1,7 @@
1
1
  import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, matchesGlob, relative, sep } from "node:path";
4
+ import { mergeTestFileResults } from "./test-results.js";
4
5
  /**
5
6
  * Selected tests the runner would never execute (2026-11-01).
6
7
  *
@@ -100,16 +101,27 @@ export function selectedNodeTests(command, selectedTests, windows = process.plat
100
101
  }
101
102
  /** Records the file each node:test process starts for. node --test runs every file in a child process
102
103
  * with NODE_TEST_CONTEXT set and the file as argv[1]; NODE_OPTIONS reaches it through npx and tsx.
103
- * Under `--test-isolation=none` no child starts and the trace stays empty, which proves nothing. */
104
+ * Under `--test-isolation=none` no child starts and the trace stays empty, which proves nothing.
105
+ * Since 2026-11-06 the process also records, on exit, its file, its duration and its exit code: the
106
+ * per-file results test-results.ts cannot read from node:test's output. */
104
107
  const PROBE = `"use strict";
105
108
  if (process.env.NODE_TEST_CONTEXT && process.argv[1] && process.env.DIFFCI_NODE_TEST_TRACE) {
106
- try { require("node:fs").appendFileSync(process.env.DIFFCI_NODE_TEST_TRACE, process.argv[1] + "\\n"); } catch {}
109
+ const fs = require("node:fs");
110
+ const file = process.argv[1];
111
+ const started = Date.now();
112
+ try { fs.appendFileSync(process.env.DIFFCI_NODE_TEST_TRACE, file + "\\n"); } catch {}
113
+ if (process.env.DIFFCI_NODE_TEST_RESULTS) {
114
+ process.on("exit", (code) => {
115
+ try { fs.appendFileSync(process.env.DIFFCI_NODE_TEST_RESULTS, JSON.stringify({ file, ms: Date.now() - started, code }) + "\\n"); } catch {}
116
+ });
117
+ }
107
118
  }
108
119
  `;
109
120
  export function traceNodeTestFiles(cwd, nodeOptions = process.env.NODE_OPTIONS) {
110
121
  const dir = mkdtempSync(join(tmpdir(), "diffci-node-test-trace-"));
111
122
  const probe = join(dir, "probe.cjs");
112
123
  const log = join(dir, "started.txt");
124
+ const resultsLog = join(dir, "results.jsonl");
113
125
  writeFileSync(probe, PROBE);
114
126
  // NODE_OPTIONS reads a backslash inside double quotes as an escape; forward slashes work on Windows.
115
127
  const required = `--require "${probe.split(sep).join("/")}"`;
@@ -119,8 +131,9 @@ export function traceNodeTestFiles(cwd, nodeOptions = process.env.NODE_OPTIONS)
119
131
  catch {
120
132
  return path;
121
133
  } };
134
+ const repoRelative = (file) => relative(real(cwd), real(file)).split(sep).join("/");
122
135
  return {
123
- env: { NODE_OPTIONS: nodeOptions?.trim() ? `${nodeOptions} ${required}` : required, DIFFCI_NODE_TEST_TRACE: log },
136
+ env: { NODE_OPTIONS: nodeOptions?.trim() ? `${nodeOptions} ${required}` : required, DIFFCI_NODE_TEST_TRACE: log, DIFFCI_NODE_TEST_RESULTS: resultsLog },
124
137
  read() {
125
138
  let lines;
126
139
  try {
@@ -129,10 +142,27 @@ export function traceNodeTestFiles(cwd, nodeOptions = process.env.NODE_OPTIONS)
129
142
  catch {
130
143
  return undefined;
131
144
  }
132
- const root = real(cwd);
133
- const files = lines.map((file) => relative(root, real(file)).split(sep).join("/"));
145
+ const files = lines.map(repoRelative);
134
146
  return files.length ? [...new Set(files)].sort() : undefined;
135
147
  },
148
+ results() {
149
+ let lines;
150
+ try {
151
+ lines = readFileSync(resultsLog, "utf8").split("\n").filter(Boolean);
152
+ }
153
+ catch {
154
+ return [];
155
+ }
156
+ return mergeTestFileResults(lines.flatMap((line) => {
157
+ try {
158
+ const { file, ms, code } = JSON.parse(line);
159
+ return [{ file: repoRelative(file), status: code === 0 ? "passed" : "failed", ms }];
160
+ }
161
+ catch {
162
+ return [];
163
+ }
164
+ }));
165
+ },
136
166
  dispose() { rmSync(dir, { recursive: true, force: true }); },
137
167
  };
138
168
  }
@@ -0,0 +1,39 @@
1
+ import type { OutcomeRecord } from "./outcome-log.js";
2
+ import type { SelectionReason } from "./report.js";
3
+ export interface TestHistory {
4
+ /** Recency-weighted failures and runs per test file. */
5
+ failures: Map<string, number>;
6
+ runs: Map<string, number>;
7
+ /** The latest known duration per test file. */
8
+ ms: Map<string, number>;
9
+ }
10
+ export declare function testHistory(records: readonly OutcomeRecord[]): TestHistory;
11
+ /** How likely `test` is to fail, from 0 to 1: its weighted failure rate, smoothed toward 0 for few runs,
12
+ * or 1 for a test the change edited or added. */
13
+ export declare function failureScore(test: string, history: TestHistory, reason?: SelectionReason): number;
14
+ /** `tests` with the likeliest failures first; ties go to the faster test, then keep their given order. */
15
+ export declare function rankTests(tests: readonly string[], history: TestHistory, reasons?: Record<string, SelectionReason>): string[];
16
+ /** The ranked tests worth running first under `--fail-fast`: those with any failure history, or edited. */
17
+ export declare function likelyFailures(tests: readonly string[], history: TestHistory, reasons?: Record<string, SelectionReason>): string[];
18
+ /** One point of the confidence curve: within `time_share` of the test time, `detected_share` of failing runs. */
19
+ export interface CurvePoint {
20
+ time_share: number;
21
+ detected_share: number;
22
+ }
23
+ export interface ConfidenceCurve {
24
+ /** Failing runs with per-file durations that the curve replays. */
25
+ failing_runs: number;
26
+ /** Ranked by the history before each run, against the runner's file order (by path). */
27
+ ranked: CurvePoint[];
28
+ by_path: CurvePoint[];
29
+ /** Median share of the run's test time spent before the first failure. */
30
+ median_ranked?: number;
31
+ median_by_path?: number;
32
+ }
33
+ /**
34
+ * The confidence curve: replays every failing run that recorded per-file durations, ranking its files by
35
+ * the history of the runs BEFORE it (never its own result), and reports how much of the test time passes
36
+ * before the first failure. Compared with the files in path order, roughly how the runners schedule them.
37
+ */
38
+ export declare function confidenceCurve(records: readonly OutcomeRecord[], steps?: number): ConfidenceCurve;
39
+ export declare function formatConfidenceCurve(curve: ConfidenceCurve): string;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Ranking selected tests by failure history (2026-11-06), the idea of Launchable (CloudBees Smart Tests)
3
+ * applied to the local outcome log.
4
+ *
5
+ * WHY. The selection decides what runs; the order decides how soon a failure is seen. An agent that sees
6
+ * the failing test first fixes it sooner, and `--fail-fast` can stop before the rest.
7
+ *
8
+ * WHAT. A heuristic, not a model: each test file's failures in the outcome log, each run weighted by how
9
+ * recent it is (a run HALF_LIFE runs ago counts half), over the runs it took part in. A test the change
10
+ * itself edited or added ranks with the most likely. Ties go to the faster test, then to the given order.
11
+ * Ranking only reorders: every selected test still runs. A learned model across repositories belongs to
12
+ * DiffCI Cloud, once there is outside data to learn from (docs/strategy.md, Predict).
13
+ */
14
+ const HALF_LIFE = 20;
15
+ const CHANGED_TEST_REASONS = new Set(["DIRECT_TEST_CHANGE", "NEW_TEST_FILE"]);
16
+ export function testHistory(records) {
17
+ const history = { failures: new Map(), runs: new Map(), ms: new Map() };
18
+ const withResults = records.filter((record) => record.test_results?.length);
19
+ withResults.forEach((record, index) => {
20
+ const weight = 0.5 ** ((withResults.length - 1 - index) / HALF_LIFE);
21
+ for (const result of record.test_results) {
22
+ history.runs.set(result.file, (history.runs.get(result.file) ?? 0) + weight);
23
+ if (result.status === "failed")
24
+ history.failures.set(result.file, (history.failures.get(result.file) ?? 0) + weight);
25
+ if (result.ms !== undefined)
26
+ history.ms.set(result.file, result.ms);
27
+ }
28
+ });
29
+ return history;
30
+ }
31
+ /** How likely `test` is to fail, from 0 to 1: its weighted failure rate, smoothed toward 0 for few runs,
32
+ * or 1 for a test the change edited or added. */
33
+ export function failureScore(test, history, reason) {
34
+ if (reason && CHANGED_TEST_REASONS.has(reason.reason))
35
+ return 1;
36
+ const failures = history.failures.get(test) ?? 0;
37
+ return failures / ((history.runs.get(test) ?? 0) + 1);
38
+ }
39
+ /** `tests` with the likeliest failures first; ties go to the faster test, then keep their given order. */
40
+ export function rankTests(tests, history, reasons = {}) {
41
+ return tests
42
+ .map((test, index) => ({ test, index, score: failureScore(test, history, reasons[test]), ms: history.ms.get(test) ?? Number.POSITIVE_INFINITY }))
43
+ .sort((a, b) => b.score - a.score || a.ms - b.ms || a.index - b.index)
44
+ .map(({ test }) => test);
45
+ }
46
+ /** The ranked tests worth running first under `--fail-fast`: those with any failure history, or edited. */
47
+ export function likelyFailures(tests, history, reasons = {}) {
48
+ return tests.filter((test) => failureScore(test, history, reasons[test]) > 0);
49
+ }
50
+ /** Share of the run's test time spent before the first failing file starts, with files run in `order`. */
51
+ function timeToFirstFailure(order, record) {
52
+ const results = new Map(record.test_results.map((result) => [result.file, result]));
53
+ const total = record.test_results.reduce((sum, result) => sum + (result.ms ?? 0), 0);
54
+ if (total <= 0)
55
+ return undefined;
56
+ let elapsed = 0;
57
+ for (const file of order) {
58
+ const result = results.get(file);
59
+ if (result.status === "failed")
60
+ return elapsed / total;
61
+ elapsed += result.ms ?? 0;
62
+ }
63
+ return undefined;
64
+ }
65
+ function median(values) {
66
+ if (values.length === 0)
67
+ return undefined;
68
+ const sorted = [...values].sort((a, b) => a - b);
69
+ const middle = Math.floor(sorted.length / 2);
70
+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
71
+ }
72
+ /**
73
+ * The confidence curve: replays every failing run that recorded per-file durations, ranking its files by
74
+ * the history of the runs BEFORE it (never its own result), and reports how much of the test time passes
75
+ * before the first failure. Compared with the files in path order, roughly how the runners schedule them.
76
+ */
77
+ export function confidenceCurve(records, steps = 10) {
78
+ const ranked = [];
79
+ const byPath = [];
80
+ records.forEach((record, index) => {
81
+ if (!record.test_results?.some((result) => result.status === "failed"))
82
+ return;
83
+ if (!record.test_results.every((result) => result.ms !== undefined))
84
+ return;
85
+ // Path order is both the baseline and the ranking's tie-break, so ranking can only move files from it.
86
+ const files = record.test_results.map((result) => result.file).sort();
87
+ const history = testHistory(records.slice(0, index));
88
+ const rankedShare = timeToFirstFailure(rankTests(files, history, record.selection_reasons), record);
89
+ const pathShare = timeToFirstFailure(files, record);
90
+ if (rankedShare === undefined || pathShare === undefined)
91
+ return;
92
+ ranked.push(rankedShare);
93
+ byPath.push(pathShare);
94
+ });
95
+ const curve = (shares) => Array.from({ length: steps }, (_, step) => {
96
+ const time_share = (step + 1) / steps;
97
+ return { time_share, detected_share: shares.length ? shares.filter((share) => share < time_share).length / shares.length : 0 };
98
+ });
99
+ const medianRanked = median(ranked);
100
+ const medianByPath = median(byPath);
101
+ return {
102
+ failing_runs: ranked.length,
103
+ ranked: curve(ranked),
104
+ by_path: curve(byPath),
105
+ ...(medianRanked !== undefined ? { median_ranked: medianRanked } : {}),
106
+ ...(medianByPath !== undefined ? { median_by_path: medianByPath } : {}),
107
+ };
108
+ }
109
+ export function formatConfidenceCurve(curve) {
110
+ if (curve.failing_runs === 0) {
111
+ return "Confidence curve: no failing run with per-file durations in the outcome log yet; it fills as verify runs fail.";
112
+ }
113
+ const percent = (value) => `${Math.round(value * 100)}%`;
114
+ const lines = [
115
+ `Confidence curve over ${curve.failing_runs} failing run(s): share of failing runs whose first failure is seen within each share of test time`,
116
+ " test time ranked by history by path",
117
+ ];
118
+ curve.ranked.forEach((point, index) => {
119
+ lines.push(` ${percent(point.time_share).padStart(9)} ${percent(point.detected_share).padStart(17)} ${percent(curve.by_path[index].detected_share).padStart(7)}`);
120
+ });
121
+ if (curve.median_ranked !== undefined && curve.median_by_path !== undefined) {
122
+ lines.push(` median test time before the first failure: ${percent(curve.median_ranked)} ranked, ${percent(curve.median_by_path)} by path`);
123
+ }
124
+ if (curve.failing_runs < 10)
125
+ lines.push(" fewer than 10 failing runs: read this as an early signal, not a measurement");
126
+ return lines.join("\n");
127
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Per-test-file results (2026-11-06).
3
+ *
4
+ * WHY. The outcome log recorded one wall time and the failing test names per run. Ranking tests by
5
+ * failure history, the confidence curve and splitting a selection into shards of equal time all need
6
+ * each test file's own result and duration, from every run, starting now.
7
+ *
8
+ * WHAT. Vitest and Jest print one line per test file with its status and, usually, its duration; those
9
+ * lines are read from the complete output. `node --test` prints test names, not files, so its files come
10
+ * from the probe in selected-coverage.ts, which records each test process's file, duration and exit code.
11
+ * Nothing changes how the command runs: no reporter is added, so a runner whose output is not recognised
12
+ * simply yields no results.
13
+ */
14
+ export interface TestFileResult {
15
+ /** As the runner names it, usually relative to its root directory. */
16
+ file: string;
17
+ status: "passed" | "failed";
18
+ ms?: number;
19
+ }
20
+ /**
21
+ * Vitest: `✓ src/a.test.ts (3 tests) 12ms`, `❯ src/a.test.ts (3 tests | 1 failed) 1.2s`, optionally
22
+ * with a `|project|` label. Only file lines carry the `(N test` count, which tells them from test lines.
23
+ * Jest: `PASS src/a.test.ts`, `FAIL web src/a.test.ts (5.1 s)` (a project name may precede the path).
24
+ */
25
+ export declare function parseTestFileResults(output: string): TestFileResult[];
26
+ /** One result per file; a later run of the same file (another command part) replaces an earlier one. */
27
+ export declare function mergeTestFileResults(...lists: ReadonlyArray<readonly TestFileResult[] | undefined>): TestFileResult[];
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Per-test-file results (2026-11-06).
3
+ *
4
+ * WHY. The outcome log recorded one wall time and the failing test names per run. Ranking tests by
5
+ * failure history, the confidence curve and splitting a selection into shards of equal time all need
6
+ * each test file's own result and duration, from every run, starting now.
7
+ *
8
+ * WHAT. Vitest and Jest print one line per test file with its status and, usually, its duration; those
9
+ * lines are read from the complete output. `node --test` prints test names, not files, so its files come
10
+ * from the probe in selected-coverage.ts, which records each test process's file, duration and exit code.
11
+ * Nothing changes how the command runs: no reporter is added, so a runner whose output is not recognised
12
+ * simply yields no results.
13
+ */
14
+ const ANSI = /\x1b\[[0-9;]*m/g;
15
+ function duration(value, unit) {
16
+ if (value === undefined)
17
+ return undefined;
18
+ const amount = Number(value);
19
+ if (!Number.isFinite(amount))
20
+ return undefined;
21
+ return Math.round(unit === "s" ? amount * 1000 : amount);
22
+ }
23
+ /**
24
+ * Vitest: `✓ src/a.test.ts (3 tests) 12ms`, `❯ src/a.test.ts (3 tests | 1 failed) 1.2s`, optionally
25
+ * with a `|project|` label. Only file lines carry the `(N test` count, which tells them from test lines.
26
+ * Jest: `PASS src/a.test.ts`, `FAIL web src/a.test.ts (5.1 s)` (a project name may precede the path).
27
+ */
28
+ export function parseTestFileResults(output) {
29
+ const results = new Map();
30
+ for (const raw of output.split(/\r?\n/)) {
31
+ const line = raw.replace(ANSI, "");
32
+ const vitest = /^\s*(✓|√|❯|×|✗)\s+(?:\|[^|]+\|\s+)?(\S+)\s+\((\d+) tests?(?:\s*\|[^)]*)?\)(?:\s+(\d+(?:\.\d+)?)(ms|s))?\s*$/.exec(line);
33
+ if (vitest) {
34
+ const failed = vitest[1] !== "✓" && vitest[1] !== "√" || /\|\s*\d+ failed/.test(line);
35
+ const ms = duration(vitest[4], vitest[5]);
36
+ results.set(vitest[2], { file: vitest[2], status: failed ? "failed" : "passed", ...(ms !== undefined ? { ms } : {}) });
37
+ continue;
38
+ }
39
+ const jest = /^\s*(PASS|FAIL)\s+(?:\S+\s+)?(\S+\.[cm]?[jt]sx?)(?:\s+\((\d+(?:\.\d+)?) s\))?\s*$/.exec(line);
40
+ if (jest) {
41
+ const ms = duration(jest[3], "s");
42
+ results.set(jest[2], { file: jest[2], status: jest[1] === "FAIL" ? "failed" : "passed", ...(ms !== undefined ? { ms } : {}) });
43
+ }
44
+ }
45
+ return [...results.values()].sort((a, b) => a.file.localeCompare(b.file));
46
+ }
47
+ /** One result per file; a later run of the same file (another command part) replaces an earlier one. */
48
+ export function mergeTestFileResults(...lists) {
49
+ const merged = new Map();
50
+ for (const list of lists)
51
+ for (const result of list ?? [])
52
+ merged.set(result.file, result);
53
+ return [...merged.values()].sort((a, b) => a.file.localeCompare(b.file));
54
+ }
@@ -0,0 +1,36 @@
1
+ import type { OutcomeRecord } from "./outcome-log.js";
2
+ /**
3
+ * Splitting a selection across CI jobs (2026-11-06), the idea of Vitest's `--shard` and Knapsack Pro.
4
+ *
5
+ * WHY. A selection that still takes minutes runs faster split across a CI matrix, and the split is only
6
+ * as good as its balance: shards of equal file count can differ in time by a factor of ten.
7
+ *
8
+ * WHAT. `verify --shard i/N` keeps shard i's share of the selected files. Every job of the matrix must
9
+ * compute the same split without talking to the others, so the split depends only on the selection, which
10
+ * is the same for the same commits, and on an explicit timings file (`--timings`, written by `diffci
11
+ * outcomes --timings`) that every job reads the same copy of. The local outcome log is deliberately not
12
+ * read: each CI job has its own, so jobs would disagree, and a file could run twice or never. Without a
13
+ * timings file every file weighs the same. Files are assigned longest first to the shard with the least
14
+ * time so far (ties to the lower shard), files of equal time in path order: deterministic everywhere.
15
+ */
16
+ export interface ShardSpec {
17
+ /** 1-based. */
18
+ index: number;
19
+ total: number;
20
+ }
21
+ export declare function parseShard(value: string): ShardSpec | undefined;
22
+ export declare const TIMINGS_SCHEMA: "diffci.timings.v1";
23
+ export interface TimingsFile {
24
+ schema: typeof TIMINGS_SCHEMA;
25
+ /** Typical duration per test file, in milliseconds. */
26
+ files: Record<string, number>;
27
+ }
28
+ /** The median of each file's last five recorded durations in the outcome log. */
29
+ export declare function timingsFromOutcomes(records: readonly OutcomeRecord[]): TimingsFile;
30
+ /** Reads a timings file, or throws with a message fit for the command line. */
31
+ export declare function readTimings(path: string): TimingsFile;
32
+ /**
33
+ * `tests` split into `total` shards of similar time. A file without a timing weighs the median known
34
+ * timing, or 1 when none is known. Returns each shard's files in their given order.
35
+ */
36
+ export declare function assignShards(tests: readonly string[], total: number, timings?: TimingsFile): string[][];
@@ -0,0 +1,68 @@
1
+ import { readFileSync } from "node:fs";
2
+ export function parseShard(value) {
3
+ const match = /^(\d+)\/(\d+)$/.exec(value.trim());
4
+ if (!match)
5
+ return undefined;
6
+ const index = Number(match[1]);
7
+ const total = Number(match[2]);
8
+ return index >= 1 && total >= 1 && index <= total && total <= 1000 ? { index, total } : undefined;
9
+ }
10
+ export const TIMINGS_SCHEMA = "diffci.timings.v1";
11
+ /** The median of each file's last five recorded durations in the outcome log. */
12
+ export function timingsFromOutcomes(records) {
13
+ const recent = new Map();
14
+ for (const record of records) {
15
+ for (const result of record.test_results ?? []) {
16
+ if (result.ms === undefined)
17
+ continue;
18
+ const list = recent.get(result.file) ?? [];
19
+ list.push(result.ms);
20
+ if (list.length > 5)
21
+ list.shift();
22
+ recent.set(result.file, list);
23
+ }
24
+ }
25
+ const files = {};
26
+ for (const [file, list] of [...recent].sort(([a], [b]) => a.localeCompare(b))) {
27
+ const sorted = [...list].sort((a, b) => a - b);
28
+ files[file] = sorted[Math.floor(sorted.length / 2)];
29
+ }
30
+ return { schema: TIMINGS_SCHEMA, files };
31
+ }
32
+ /** Reads a timings file, or throws with a message fit for the command line. */
33
+ export function readTimings(path) {
34
+ let parsed;
35
+ try {
36
+ parsed = JSON.parse(readFileSync(path, "utf8"));
37
+ }
38
+ catch (error) {
39
+ throw new Error(`could not read timings file ${path}: ${error instanceof Error ? error.message : String(error)}`);
40
+ }
41
+ const record = parsed;
42
+ if (!record || record.schema !== TIMINGS_SCHEMA || !record.files || typeof record.files !== "object"
43
+ || !Object.values(record.files).every((ms) => typeof ms === "number" && Number.isFinite(ms) && ms >= 0)) {
44
+ throw new Error(`timings file ${path} is not a ${TIMINGS_SCHEMA} file (write one with diffci outcomes --timings)`);
45
+ }
46
+ return record;
47
+ }
48
+ /**
49
+ * `tests` split into `total` shards of similar time. A file without a timing weighs the median known
50
+ * timing, or 1 when none is known. Returns each shard's files in their given order.
51
+ */
52
+ export function assignShards(tests, total, timings) {
53
+ const known = tests.map((test) => timings?.files[test]).filter((ms) => ms !== undefined).sort((a, b) => a - b);
54
+ const fallback = known.length ? known[Math.floor(known.length / 2)] : 1;
55
+ const weighted = [...new Set(tests)].map((test) => ({ test, ms: timings?.files[test] ?? fallback }))
56
+ .sort((a, b) => b.ms - a.ms || a.test.localeCompare(b.test));
57
+ const loads = Array.from({ length: total }, () => 0);
58
+ const members = Array.from({ length: total }, () => new Set());
59
+ for (const { test, ms } of weighted) {
60
+ let target = 0;
61
+ for (let shard = 1; shard < total; shard += 1)
62
+ if (loads[shard] < loads[target])
63
+ target = shard;
64
+ loads[target] += ms;
65
+ members[target].add(test);
66
+ }
67
+ return members.map((set) => tests.filter((test) => set.has(test)));
68
+ }
@@ -1,3 +1,4 @@
1
+ import { type TestFileResult } from "./test-results.js";
1
2
  import type { FailureClass } from "../preflight/taxonomy.js";
2
3
  export type CacheState = "cold" | "warm" | "unknown" | "potentially-warmed";
3
4
  export type FailureAssessmentKind = "none" | "selection_miss" | "likely_flaky" | "pre_existing" | "infrastructure" | "inconclusive";
@@ -16,6 +17,11 @@ export interface CommandMeasurement {
16
17
  /** node:test's reported test count, or vitest's or jest's test-file total, from the complete output.
17
18
  * Each file contributes at least one, so fewer than the selected files means some never ran. */
18
19
  runnerTestCount?: number;
20
+ /** Each test file's result and duration, where the runner's output or the node:test probe shows them
21
+ * (test-results.ts). */
22
+ testResults?: TestFileResult[];
23
+ /** Parts left unrun because an earlier one failed under `--fail-fast` (command-batches.ts). */
24
+ partsNotRun?: number;
19
25
  }
20
26
  export interface VerifySavingsReport {
21
27
  schema: "diffci.verifySavings.v3";
@@ -5,6 +5,7 @@ import { arch, cpus, platform, release, totalmem } from "node:os";
5
5
  import { basename, dirname, resolve } from "node:path";
6
6
  import { failingTestNames } from "./failure-baseline.js";
7
7
  import { runnerTestCount } from "./selected-coverage.js";
8
+ import { parseTestFileResults } from "./test-results.js";
8
9
  import { classifyFailureFromEvidence, computeFailureFingerprint } from "../preflight/fingerprint.js";
9
10
  function tail(value, bytes) {
10
11
  if (Buffer.byteLength(value, "utf8") <= bytes)
@@ -273,6 +274,8 @@ export function measureCommand(command, options) {
273
274
  const failingTests = result.status === 0 ? [] : failingTestNames(`${result.stdout ?? ""}
274
275
  ${result.stderr ?? ""}`);
275
276
  const testCount = runnerTestCount(result.stdout ?? "");
277
+ const testResults = parseTestFileResults(`${result.stdout ?? ""}
278
+ ${result.stderr ?? ""}`);
276
279
  return {
277
280
  command,
278
281
  exitCode: result.status,
@@ -285,6 +288,7 @@ ${result.stderr ?? ""}`);
285
288
  stderrTail: tail(result.stderr ?? "", options.tailBytes),
286
289
  ...(failingTests.length ? { failingTests } : {}),
287
290
  ...(testCount !== undefined ? { runnerTestCount: testCount } : {}),
291
+ ...(testResults.length ? { testResults } : {}),
288
292
  };
289
293
  }
290
294
  export function buildVerifySavingsReport(input) {