@diffci.com/diffci 0.3.29 → 0.3.30

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 (93) hide show
  1. package/dist-client/src/client/cli.js +53 -5
  2. package/dist-client/src/client/command-batches.d.ts +17 -0
  3. package/dist-client/src/client/command-batches.js +73 -9
  4. package/dist-client/src/client/failure-baseline.js +0 -0
  5. package/dist-client/src/client/outcome-log.d.ts +40 -0
  6. package/dist-client/src/client/outcome-log.js +38 -1
  7. package/dist-client/src/client/selected-coverage.d.ts +3 -0
  8. package/dist-client/src/client/selected-coverage.js +35 -5
  9. package/dist-client/src/client/test-ranking.d.ts +39 -0
  10. package/dist-client/src/client/test-ranking.js +127 -0
  11. package/dist-client/src/client/test-results.d.ts +27 -0
  12. package/dist-client/src/client/test-results.js +54 -0
  13. package/dist-client/src/client/test-shards.d.ts +36 -0
  14. package/dist-client/src/client/test-shards.js +68 -0
  15. package/dist-client/src/client/verify-savings.d.ts +6 -0
  16. package/dist-client/src/client/verify-savings.js +4 -0
  17. package/dist-client/src/client/verify.d.ts +32 -1
  18. package/dist-client/src/client/verify.js +141 -13
  19. package/node_modules/@babel/helper-string-parser/lib/index.js +5 -5
  20. package/node_modules/@babel/helper-string-parser/lib/index.js.map +1 -1
  21. package/node_modules/@babel/helper-string-parser/package.json +1 -1
  22. package/node_modules/@babel/parser/lib/index.js +6306 -6143
  23. package/node_modules/@babel/parser/lib/index.js.map +1 -1
  24. package/node_modules/@babel/parser/package.json +3 -3
  25. package/node_modules/@babel/types/lib/definitions/typescript.js +2 -1
  26. package/node_modules/@babel/types/lib/definitions/typescript.js.map +1 -1
  27. package/node_modules/@babel/types/package.json +3 -3
  28. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  29. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +2 -1
  30. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  31. package/node_modules/@diffci.com/core/dist/repo/file-references.js +39 -2
  32. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  33. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +1 -1
  34. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +13 -0
  35. package/node_modules/@diffci.com/core/dist/repo/impact.js +104 -9
  36. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/repo/repo-config.d.ts +11 -0
  38. package/node_modules/@diffci.com/core/dist/repo/repo-config.js +11 -1
  39. package/node_modules/@diffci.com/core/dist/repo/repo-config.js.map +1 -1
  40. package/node_modules/@diffci.com/core/dist/repo/route-visits.d.ts +34 -0
  41. package/node_modules/@diffci.com/core/dist/repo/route-visits.js +93 -0
  42. package/node_modules/@diffci.com/core/dist/repo/route-visits.js.map +1 -0
  43. package/node_modules/@diffci.com/core/package.json +3 -3
  44. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +2 -1
  45. package/node_modules/@diffci.com/core/src/repo/file-references.ts +32 -2
  46. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +2 -0
  47. package/node_modules/@diffci.com/core/src/repo/impact.ts +95 -9
  48. package/node_modules/@diffci.com/core/src/repo/repo-config.ts +23 -1
  49. package/node_modules/@diffci.com/core/src/repo/route-visits.ts +88 -0
  50. package/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js +4 -3
  51. package/node_modules/@vue/compiler-core/dist/compiler-core.cjs.prod.js +4 -3
  52. package/node_modules/@vue/compiler-core/dist/compiler-core.esm-bundler.js +4 -3
  53. package/node_modules/@vue/compiler-core/package.json +4 -4
  54. package/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.js +9 -6
  55. package/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.prod.js +41 -4
  56. package/node_modules/@vue/compiler-dom/dist/compiler-dom.esm-browser.js +10 -7
  57. package/node_modules/@vue/compiler-dom/dist/compiler-dom.esm-browser.prod.js +12 -11
  58. package/node_modules/@vue/compiler-dom/dist/compiler-dom.esm-bundler.js +5 -3
  59. package/node_modules/@vue/compiler-dom/dist/compiler-dom.global.js +10 -7
  60. package/node_modules/@vue/compiler-dom/dist/compiler-dom.global.prod.js +12 -11
  61. package/node_modules/@vue/compiler-dom/package.json +3 -3
  62. package/node_modules/@vue/compiler-sfc/dist/compiler-sfc.cjs.js +155 -20
  63. package/node_modules/@vue/compiler-sfc/dist/compiler-sfc.esm-browser.js +431 -98
  64. package/node_modules/@vue/compiler-sfc/package.json +10 -10
  65. package/node_modules/@vue/compiler-ssr/dist/compiler-ssr.cjs.js +1 -1
  66. package/node_modules/@vue/compiler-ssr/package.json +3 -3
  67. package/node_modules/@vue/shared/dist/shared.cjs.js +51 -32
  68. package/node_modules/@vue/shared/dist/shared.cjs.prod.js +51 -32
  69. package/node_modules/@vue/shared/dist/shared.d.ts +2 -1
  70. package/node_modules/@vue/shared/dist/shared.esm-bundler.js +51 -32
  71. package/node_modules/@vue/shared/package.json +1 -1
  72. package/node_modules/nanoid/async/index.d.cts +56 -0
  73. package/node_modules/nanoid/index.cjs +12 -7
  74. package/node_modules/nanoid/index.js +1 -1
  75. package/node_modules/nanoid/package.json +3 -3
  76. package/node_modules/postcss/lib/input.js +1 -1
  77. package/node_modules/postcss/lib/lazy-result.js +1 -1
  78. package/node_modules/postcss/lib/list.js +19 -1
  79. package/node_modules/postcss/lib/map-generator.js +9 -3
  80. package/node_modules/postcss/lib/no-work-result.js +1 -1
  81. package/node_modules/postcss/lib/node.js +2 -2
  82. package/node_modules/postcss/lib/parser.js +6 -1
  83. package/node_modules/postcss/lib/processor.js +1 -1
  84. package/node_modules/postcss/lib/stringifier.js +16 -28
  85. package/node_modules/postcss/lib/stringify.js +84 -2
  86. package/node_modules/postcss/lib/warning.js +1 -0
  87. package/node_modules/postcss/package.json +3 -3
  88. package/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +19 -18
  89. package/node_modules/yaml/browser/dist/nodes/Alias.js +25 -23
  90. package/node_modules/yaml/dist/compose/resolve-flow-scalar.js +19 -18
  91. package/node_modules/yaml/dist/nodes/Alias.js +25 -23
  92. package/node_modules/yaml/package.json +1 -1
  93. package/package.json +2 -2
@@ -54,6 +54,8 @@ 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 { confidenceCurve, formatConfidenceCurve } from "./test-ranking.js";
58
+ import { parseShard, readTimings, timingsFromOutcomes } from "./test-shards.js";
57
59
  import { findReceipt, findWindowStart, inferRerunArgs, mergedPullRequests, MISS_REPORT_FILE, rerunFailingFiles, spawnRunner, } from "./enforce-misses-collect.js";
58
60
  function parseArgs(argv) {
59
61
  const args = argv.slice(2);
@@ -354,6 +356,27 @@ async function runVerifyCommand(flags, env) {
354
356
  console.error(`Refusing to write the verification receipt inside the repository: ${reportPath}. Use --out with a path outside the checkout.`);
355
357
  return 2;
356
358
  }
359
+ const shardFlag = stringFlag(flags, "shard");
360
+ const shard = shardFlag === undefined ? undefined : parseShard(shardFlag);
361
+ if (shardFlag !== undefined && !shard) {
362
+ console.error(`diffci verify --shard takes i/N with 1 <= i <= N, got ${JSON.stringify(shardFlag)}`);
363
+ return 2;
364
+ }
365
+ const timingsFlag = stringFlag(flags, "timings");
366
+ let timings;
367
+ if (timingsFlag !== undefined) {
368
+ if (!shard) {
369
+ console.error("diffci verify --timings balances --shard; pass both");
370
+ return 2;
371
+ }
372
+ try {
373
+ timings = readTimings(resolve(timingsFlag));
374
+ }
375
+ catch (error) {
376
+ console.error(error instanceof Error ? error.message : String(error));
377
+ return 2;
378
+ }
379
+ }
357
380
  const identity = observerIdentity();
358
381
  const common = {
359
382
  repoPath,
@@ -366,6 +389,11 @@ async function runVerifyCommand(flags, env) {
366
389
  baselineOnFailure: flags["baseline-on-failure"] === true || env.DIFFCI_BASELINE_ON_FAILURE === "1",
367
390
  // Gate checks are for before push; in CI the repository's own check jobs already run them.
368
391
  skipChecks: flags["no-checks"] === true || env.DIFFCI_CHECKS === "0" || (Boolean(env.CI) && env.CI !== "false" && flags.checks !== true),
392
+ reuse: flags["no-reuse"] !== true && env.DIFFCI_REUSE !== "0",
393
+ rank: flags["no-rank"] !== true && env.DIFFCI_RANK !== "0",
394
+ failFast: flags["fail-fast"] === true,
395
+ ...(shard ? { shard } : {}),
396
+ ...(timings ? { timings } : {}),
369
397
  };
370
398
  const report = changed
371
399
  ? await verifyChanged(common)
@@ -398,7 +426,17 @@ function runOutcomesCommand(flags, env) {
398
426
  console.error(`Not a Git repository: ${repoPath}`);
399
427
  return 2;
400
428
  }
401
- const summary = summarizeOutcomes(readOutcomes(path));
429
+ const records = readOutcomes(path);
430
+ if (flags.timings === true) {
431
+ console.log(JSON.stringify(timingsFromOutcomes(records), null, 2));
432
+ return 0;
433
+ }
434
+ if (flags.curve === true) {
435
+ const curve = confidenceCurve(records);
436
+ console.log(flags.json === true ? JSON.stringify({ log: path, ...curve }, null, 2) : formatConfidenceCurve(curve));
437
+ return 0;
438
+ }
439
+ const summary = summarizeOutcomes(records);
402
440
  console.log(flags.json === true ? JSON.stringify({ log: path, ...summary }, null, 2) : formatOutcomeSummary(summary, path));
403
441
  return 0;
404
442
  }
@@ -1101,7 +1139,8 @@ Usage:
1101
1139
  diffci mcp
1102
1140
  diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
1103
1141
  [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--no-checks | --checks]
1104
- [--share-usage] [--no-send] [--no-log]
1142
+ [--share-usage] [--no-send] [--no-log] [--no-reuse] [--no-rank] [--fail-fast]
1143
+ [--shard <i/N> [--timings <file>]]
1105
1144
  diffci telemetry [--mode off|anonymous|installations] [--internal-usage]
1106
1145
  diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
1107
1146
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
@@ -1126,7 +1165,7 @@ Usage:
1126
1165
  diffci gate --plan-out <file> [--base <sha> --head <sha>] [--script <name,...>] [--repo <path>]
1127
1166
  diffci enforce-misses --junit <file> --out-dir <dir> [--repository <owner/name>] [--repo <path>]
1128
1167
  [--head <sha>] [--rerun-junit <file>] [--open-issue]
1129
- diffci outcomes [--repo <path>] [--json]
1168
+ diffci outcomes [--repo <path>] [--curve | --timings] [--json]
1130
1169
  diffci version
1131
1170
 
1132
1171
  init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json. It also
@@ -1166,10 +1205,19 @@ and writes DiffCI's decisions, for a gate that runs without git history; --plan
1166
1205
  analysing, and --expect-head ignores a plan made for another commit. It sends nothing.
1167
1206
  enforce-misses classifies a full run's failures on main against the enforce dry-run receipts of the pull
1168
1207
  requests merged since the last recorded run, and exits 1 on a miss. It never edits configuration.
1169
- verify appends each run (plan, selection reasons, checks, results, durations, failing tests) to
1208
+ verify appends each run (plan, selection reasons, checks, results, per-file durations, failing tests) to
1170
1209
  .git/diffci/outcomes.jsonl, which is never committed and never sent; --no-log or DIFFCI_OUTCOME_LOG=0 skips it.
1210
+ When an earlier run in that log passed on the exact same tree and covered the same tests and checks, verify
1211
+ reuses it and runs nothing; --no-reuse or DIFFCI_REUSE=0 runs everything again. Selected tests that have
1212
+ failed before in that log, or that the change edited, run first (--no-rank keeps the selection's order);
1213
+ --fail-fast runs them as a first batch and stops there if one fails. --shard i/N runs job i's share of the
1214
+ selection in an N-job CI matrix; every job splits it the same way, balanced by --timings (a file from
1215
+ diffci outcomes --timings that every job reads) or else by file count. The full suite, test-script phases
1216
+ and a selection that cannot be split run in shard 1.
1171
1217
  outcomes summarises that log: results, selected and full runs, top full-run reasons, agents, and possible
1172
- misses (a selected run that passed and a later full run of the same tree that failed).
1218
+ misses (a selected run that passed and a later full run of the same tree that failed). --curve replays the
1219
+ failing runs to show how soon the first failure is seen, ranked by history against path order. --timings
1220
+ prints each test file's typical duration as JSON, for verify --shard --timings.
1173
1221
  Failures are re-run with the package.json tsx --test runner, or read from --rerun-junit for other runners.
1174
1222
 
1175
1223
  The report is sent only when both --api-url and --api-token are given (or DIFFCI_API_URL and
@@ -13,15 +13,32 @@ import { type CommandMeasurement } from "./verify-savings.js";
13
13
  * whole, because rewriting a command that is not understood could change what it runs.
14
14
  */
15
15
  export declare const COMMAND_LINE_LIMIT: number;
16
+ /**
17
+ * `command` with its selected paths in `order` (test-ranking.ts, 2026-11-06), or unchanged when it does not
18
+ * end in exactly the selected paths. Paths missing from `order` keep their place after the ordered ones.
19
+ */
20
+ export declare function orderCommand(command: string, order: readonly string[]): string;
21
+ /**
22
+ * `command` as two invocations of the same runner, the `first` paths and then the rest, for `--fail-fast`;
23
+ * `[command]` when it cannot be split safely or one side would be empty.
24
+ */
25
+ export declare function splitCommand(command: string, paths: readonly string[], first: readonly string[]): string[];
26
+ /**
27
+ * `command` keeping only the `keep` paths (`verify --shard`, test-shards.ts), `null` when it keeps none,
28
+ * or undefined when `command` does not end in exactly selected paths and so cannot be cut safely.
29
+ */
30
+ export declare function subsetCommand(command: string, paths: readonly string[], keep: ReadonlySet<string>): string | null | undefined;
16
31
  /** `command` split so each part fits `limit`, or `[command]` when it fits or cannot be split safely. */
17
32
  export declare function batchCommand(command: string, paths: readonly string[], limit?: number): string[];
18
33
  /**
19
34
  * Runs `commands` in order as one verification. Every part runs, so one receipt carries every failing
20
35
  * test; the first non-zero exit is the result, and the remaining time budget is shared between parts.
36
+ * With `stopOnFailure` (`--fail-fast`, 2026-11-06) the parts after the first failing one do not run.
21
37
  */
22
38
  export declare function measureCommands(commands: readonly string[], options: {
23
39
  cwd: string;
24
40
  timeoutMs: number;
25
41
  tailBytes: number;
26
42
  env?: Record<string, string>;
43
+ stopOnFailure?: boolean;
27
44
  }): CommandMeasurement;
@@ -1,4 +1,5 @@
1
1
  import { commandArguments } from "./selected-coverage.js";
2
+ import { mergeTestFileResults } from "./test-results.js";
2
3
  import { measureCommand } from "./verify-savings.js";
3
4
  /**
4
5
  * Selected-test commands too long for the shell (2026-10-21).
@@ -14,23 +15,77 @@ import { measureCommand } from "./verify-savings.js";
14
15
  * whole, because rewriting a command that is not understood could change what it runs.
15
16
  */
16
17
  export const COMMAND_LINE_LIMIT = process.platform === "win32" ? 8000 : 100_000;
17
- /** `command` split so each part fits `limit`, or `[command]` when it fits or cannot be split safely. */
18
- export function batchCommand(command, paths, limit = COMMAND_LINE_LIMIT) {
19
- if (command.length <= limit || paths.length === 0)
20
- return [command];
18
+ /**
19
+ * The runner prefix and the selected paths `command` ends with, one token each, or undefined when it does
20
+ * not end in exactly selected paths. Every rewrite here (batching, reordering, splitting) needs this shape.
21
+ */
22
+ function selectedTail(command, paths) {
21
23
  const tokens = command.split(" ");
22
24
  const selected = new Set(paths);
23
25
  // A `node --test` path with brackets arrives quoted and class-escaped: "src/app/@([[])id@([]])/x.test.ts"
24
26
  // (Core before 2026-11-02 emitted the bare class, "src/app/[[]id[]]/x.test.ts").
25
- const isSelected = (token) => selected.has(token)
26
- || selected.has((commandArguments(token)[0] ?? "").replace(/@\(\[(.)\]\)|\[(.)\]/g, (_, wrapped, bare) => wrapped ?? bare ?? ""));
27
+ const pathOf = (token) => {
28
+ if (selected.has(token))
29
+ return token;
30
+ const decoded = (commandArguments(token)[0] ?? "").replace(/@\(\[(.)\]\)|\[(.)\]/g, (_, wrapped, bare) => wrapped ?? bare ?? "");
31
+ return selected.has(decoded) ? decoded : undefined;
32
+ };
27
33
  let start = tokens.length;
28
- while (start > 0 && isSelected(tokens[start - 1]))
34
+ while (start > 0 && pathOf(tokens[start - 1]) !== undefined)
29
35
  start--;
30
36
  const trailing = tokens.slice(start);
31
37
  if (trailing.length === 0 || new Set(trailing).size !== trailing.length)
38
+ return undefined;
39
+ return { prefix: tokens.slice(0, start).join(" "), tokens: trailing.map((token) => ({ token, path: pathOf(token) })) };
40
+ }
41
+ /**
42
+ * `command` with its selected paths in `order` (test-ranking.ts, 2026-11-06), or unchanged when it does not
43
+ * end in exactly the selected paths. Paths missing from `order` keep their place after the ordered ones.
44
+ */
45
+ export function orderCommand(command, order) {
46
+ const tail = selectedTail(command, order);
47
+ if (!tail)
48
+ return command;
49
+ const rank = new Map(order.map((path, index) => [path, index]));
50
+ const sorted = tail.tokens.map((entry, index) => ({ ...entry, index }))
51
+ .sort((a, b) => (rank.get(a.path) ?? order.length + a.index) - (rank.get(b.path) ?? order.length + b.index));
52
+ return `${tail.prefix} ${sorted.map((entry) => entry.token).join(" ")}`;
53
+ }
54
+ /**
55
+ * `command` as two invocations of the same runner, the `first` paths and then the rest, for `--fail-fast`;
56
+ * `[command]` when it cannot be split safely or one side would be empty.
57
+ */
58
+ export function splitCommand(command, paths, first) {
59
+ const tail = selectedTail(command, paths);
60
+ if (!tail)
32
61
  return [command];
33
- const prefix = tokens.slice(0, start).join(" ");
62
+ const head = new Set(first);
63
+ const early = tail.tokens.filter((entry) => head.has(entry.path));
64
+ const late = tail.tokens.filter((entry) => !head.has(entry.path));
65
+ if (early.length === 0 || late.length === 0)
66
+ return [command];
67
+ return [early, late].map((part) => `${tail.prefix} ${part.map((entry) => entry.token).join(" ")}`);
68
+ }
69
+ /**
70
+ * `command` keeping only the `keep` paths (`verify --shard`, test-shards.ts), `null` when it keeps none,
71
+ * or undefined when `command` does not end in exactly selected paths and so cannot be cut safely.
72
+ */
73
+ export function subsetCommand(command, paths, keep) {
74
+ const tail = selectedTail(command, paths);
75
+ if (!tail)
76
+ return undefined;
77
+ const kept = tail.tokens.filter((entry) => keep.has(entry.path));
78
+ return kept.length ? `${tail.prefix} ${kept.map((entry) => entry.token).join(" ")}` : null;
79
+ }
80
+ /** `command` split so each part fits `limit`, or `[command]` when it fits or cannot be split safely. */
81
+ export function batchCommand(command, paths, limit = COMMAND_LINE_LIMIT) {
82
+ if (command.length <= limit || paths.length === 0)
83
+ return [command];
84
+ const tail = selectedTail(command, paths);
85
+ if (!tail)
86
+ return [command];
87
+ const { prefix } = tail;
88
+ const trailing = tail.tokens.map((entry) => entry.token);
34
89
  if (prefix.length + 1 + Math.max(...trailing.map((t) => t.length)) > limit)
35
90
  return [command];
36
91
  const batches = [[]];
@@ -51,12 +106,14 @@ export function batchCommand(command, paths, limit = COMMAND_LINE_LIMIT) {
51
106
  /**
52
107
  * Runs `commands` in order as one verification. Every part runs, so one receipt carries every failing
53
108
  * test; the first non-zero exit is the result, and the remaining time budget is shared between parts.
109
+ * With `stopOnFailure` (`--fail-fast`, 2026-11-06) the parts after the first failing one do not run.
54
110
  */
55
111
  export function measureCommands(commands, options) {
56
112
  if (commands.length === 1)
57
113
  return measureCommand(commands[0], options);
58
114
  const started = Date.now();
59
115
  const parts = [];
116
+ let stopped = false;
60
117
  for (const command of commands) {
61
118
  const remaining = options.timeoutMs - (Date.now() - started);
62
119
  if (remaining <= 0)
@@ -65,17 +122,22 @@ export function measureCommands(commands, options) {
65
122
  parts.push(part);
66
123
  if (part.timedOut)
67
124
  break;
125
+ if (options.stopOnFailure && (part.exitCode !== 0 || part.signal !== null) && parts.length < commands.length) {
126
+ stopped = true;
127
+ break;
128
+ }
68
129
  }
69
130
  const failed = parts.find((part) => part.exitCode !== 0 || part.signal !== null || part.timedOut);
70
131
  const ranAll = parts.length === commands.length;
71
132
  const failingTests = [...new Set(parts.flatMap((part) => part.failingTests ?? []))].sort();
72
133
  const counted = ranAll && parts.every((part) => part.runnerTestCount !== undefined);
134
+ const testResults = mergeTestFileResults(...parts.map((part) => part.testResults));
73
135
  const tail = (key) => parts.map((part) => part[key]).join("").slice(-Math.max(options.tailBytes, 0) || undefined);
74
136
  return {
75
137
  command: commands.join(" && "),
76
138
  exitCode: failed ? failed.exitCode : ranAll ? 0 : null,
77
139
  signal: failed?.signal ?? null,
78
- timedOut: parts.some((part) => part.timedOut) || !ranAll,
140
+ timedOut: parts.some((part) => part.timedOut) || (!ranAll && !stopped),
79
141
  startedAt: parts[0]?.startedAt ?? new Date(started).toISOString(),
80
142
  finishedAt: parts[parts.length - 1]?.finishedAt ?? new Date().toISOString(),
81
143
  wallMs: Date.now() - started,
@@ -83,5 +145,7 @@ export function measureCommands(commands, options) {
83
145
  stderrTail: options.tailBytes > 0 ? tail("stderrTail") : "",
84
146
  ...(failingTests.length ? { failingTests } : {}),
85
147
  ...(counted ? { runnerTestCount: parts.reduce((sum, part) => sum + part.runnerTestCount, 0) } : {}),
148
+ ...(testResults.length ? { testResults } : {}),
149
+ ...(stopped ? { partsNotRun: commands.length - parts.length } : {}),
86
150
  };
87
151
  }
@@ -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 {
@@ -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
+ }