@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
@@ -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) {
@@ -2,6 +2,7 @@ import { type FailureBaseline } from "./failure-baseline.js";
2
2
  import { type EnforcementDecision } from "./enforce-policy.js";
3
3
  import { type CheckResult } from "./gate-checks.js";
4
4
  import type { ObservationCommitRange, ObservationReport, SelectionReason } from "./report.js";
5
+ import { type ShardSpec, type TimingsFile } from "./test-shards.js";
5
6
  import type { CommandMeasurement } from "./verify-savings.js";
6
7
  import { type SnapshotChange } from "./working-tree.js";
7
8
  export declare const VERIFICATION_SCHEMA: "diffci.verification.v1";
@@ -73,6 +74,18 @@ export interface VerificationReport {
73
74
  enforcement?: EnforcementDecision & {
74
75
  applied: boolean;
75
76
  };
77
+ /** Present when nothing ran because an earlier pass of this exact tree covered it (outcome-log.ts, reusablePass). */
78
+ reused_from?: {
79
+ produced_at: string;
80
+ selection: "selected" | "full";
81
+ command?: string;
82
+ };
83
+ /** Present under `--shard i/N`: this job's share of the selection (test-shards.ts). */
84
+ shard?: {
85
+ index: number;
86
+ total: number;
87
+ timings: "file" | "equal";
88
+ };
76
89
  }
77
90
  interface VerifyOptions {
78
91
  repoPath: string;
@@ -86,6 +99,15 @@ interface VerifyOptions {
86
99
  baselineOnFailure?: boolean;
87
100
  /** Run only the tests, not the gate's other checks (`--no-checks`). */
88
101
  skipChecks?: boolean;
102
+ /** False runs everything even when an earlier pass of the same tree covers it (`--no-reuse`). */
103
+ reuse?: boolean;
104
+ /** False keeps the selection's own order instead of likeliest failures first (`--no-rank`). */
105
+ rank?: boolean;
106
+ /** Run the likeliest failures first and stop there if one fails (`--fail-fast`). */
107
+ failFast?: boolean;
108
+ /** Run only this job's share of the selection (`--shard i/N`), balanced by `timings` when given. */
109
+ shard?: ShardSpec;
110
+ timings?: TimingsFile;
89
111
  }
90
112
  export interface VerifyChangedOptions extends VerifyOptions {
91
113
  }
@@ -101,13 +123,22 @@ export declare function verifyChanged(options: VerifyChangedOptions): Promise<Ve
101
123
  export declare function verifyRange(options: VerifyRangeOptions): Promise<VerificationReport>;
102
124
  export declare function verificationExitCode(report: VerificationReport): number;
103
125
  export declare function formatVerificationSummary(report: VerificationReport): string;
126
+ /** The order to run selected tests in, and under --fail-fast the ones to run first (test-ranking.ts). */
127
+ export interface SelectedOrdering {
128
+ order: readonly string[];
129
+ first?: readonly string[];
130
+ }
104
131
  /** Shared executable plan for read-only agent selection and verification. */
105
- export declare function executableSelection(repoPath: string, result: NonNullable<ObservationReport["result"]>): {
132
+ export declare function executableSelection(repoPath: string, result: NonNullable<ObservationReport["result"]>, ordering?: SelectedOrdering, shard?: {
133
+ tests: ReadonlySet<string>;
134
+ first: boolean;
135
+ }): {
106
136
  selection: "full" | "selected";
107
137
  command: string | undefined;
108
138
  commands: string[];
109
139
  reason: string;
110
140
  outsideSuite: number;
141
+ unshardable: boolean;
111
142
  };
112
143
  /** A test-script phase as a standalone command. `npm test` puts `node_modules/.bin` on PATH; outside
113
144
  * it a repository-local runner such as tsx is reached the way selected TypeScript tests are. */
@@ -1,13 +1,17 @@
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 } from "./command-batches.js";
4
+ import { batchCommand, measureCommands, orderCommand, splitCommand, subsetCommand } from "./command-batches.js";
5
5
  import { checkAtBaseline, compareWithBaseline } from "./failure-baseline.js";
6
6
  import { collectEnforcementContext, evaluateEnforcement } from "./enforce-policy.js";
7
7
  import { inferFullCommand, inferSelectedCommand, inferSelectedCommands } from "./full-command.js";
8
8
  import { plannedChecks, runChecks } from "./gate-checks.js";
9
9
  import { makeGitRunner, observe } from "./observe.js";
10
10
  import { selectedNodeTests, traceNodeTestFiles, unmatchedNodeTests, unstartedNodeTests } from "./selected-coverage.js";
11
+ import { outcomeLogPath, readOutcomes, reusablePass } from "./outcome-log.js";
12
+ import { likelyFailures, rankTests, testHistory } from "./test-ranking.js";
13
+ import { assignShards } from "./test-shards.js";
14
+ import { mergeTestFileResults } from "./test-results.js";
11
15
  import { captureWorkingTreeSnapshot, snapshotChanges } from "./working-tree.js";
12
16
  export const VERIFICATION_SCHEMA = "diffci.verification.v1";
13
17
  function receiptRange(range) {
@@ -64,7 +68,8 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
64
68
  // Under enforce, a fired fallback runs the full suite even where plain verify would block: an
65
69
  // unusable analysis is a reason to run everything, never a reason to pass with nothing run.
66
70
  const enforcedFull = enforcement !== undefined && enforcement.fired_fallback !== null;
67
- const result = observation.result;
71
+ // Under --shard, narrowed to this job's share once the commands are built.
72
+ let result = observation.result;
68
73
  const range = observation.commitRange;
69
74
  const boundRange = scope === "commit-range" ? range : undefined;
70
75
  const counts = {
@@ -105,9 +110,45 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
105
110
  report.snapshot.after_tree_sha = afterAnalysis.treeSha;
106
111
  return report;
107
112
  }
108
- const { selection, command, commands, reason, outsideSuite } = enforcedFull || !result
113
+ // --shard i/N (test-shards.ts): this job's share of the selection, split the same way in every job.
114
+ const shard = options.shard;
115
+ const shardTests = shard && result && !enforcedFull && result.mode === "SELECTIVE"
116
+ ? assignShards(result.selectedTests, shard.total, options.timings)[shard.index - 1]
117
+ : undefined;
118
+ const executable = enforcedFull || !result
109
119
  ? fullSelection(options.repoPath, `enforce fallback (${enforcement?.fired_fallback}): ${enforcement?.detail}`)
110
- : executableSelection(options.repoPath, result);
120
+ : 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;
122
+ const unshardable = "unshardable" in executable && executable.unshardable;
123
+ const shardField = shard ? { shard: { index: shard.index, total: shard.total, timings: options.timings ? "file" : "equal" } } : {};
124
+ if (shard) {
125
+ const label = `${shard.index}/${shard.total}`;
126
+ const elsewhere = selection === "full" ? `the full suite runs in shard 1/${shard.total}`
127
+ : unshardable ? `the selected command cannot be split, so the whole selection runs in shard 1/${shard.total}`
128
+ : undefined;
129
+ if ((elsewhere && shard.index !== 1) || commands.length === 0) {
130
+ const why = elsewhere && shard.index !== 1 ? elsewhere : `shard ${label} has no selected test files`;
131
+ return {
132
+ ...baseReport(before, scope, boundRange),
133
+ verification: "passed",
134
+ safe_to_continue: true,
135
+ reason: `nothing to run in shard ${label}: ${why}`,
136
+ changed_files: counts.changedFiles,
137
+ tests_available: counts.testsAvailable,
138
+ tests_selected: 0,
139
+ selection: "none",
140
+ snapshot: { ...baseReport(before, scope, boundRange).snapshot, after_base_sha: before.baseSha, after_tree_sha: before.treeSha, unchanged: true },
141
+ analysis,
142
+ required_actions: [],
143
+ ...shardField,
144
+ };
145
+ }
146
+ if (selection === "selected" && !unshardable && shardTests && result) {
147
+ const reasons = result.selectionReasons;
148
+ result = { ...result, selectedTests: shardTests, ...(reasons ? { selectionReasons: Object.fromEntries(shardTests.flatMap((test) => reasons[test] ? [[test, reasons[test]]] : [])) } : {}) };
149
+ counts.testsSelected = shardTests.length;
150
+ }
151
+ }
111
152
  if (!command) {
112
153
  const inferred = inferFullCommand(options.repoPath);
113
154
  return blocked(before, scope, `no executable verification command is available: ${inferred.reason}`, analysis, counts, boundRange);
@@ -117,6 +158,34 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
117
158
  const checkBase = scope === "commit-range" ? range?.baseSha : before.baseSha;
118
159
  const checkHead = scope === "commit-range" ? range?.headSha : before.commitSha;
119
160
  const planned = options.skipChecks ? [] : plannedChecks(options.repoPath, checkBase && checkHead ? { baseSha: checkBase, headSha: checkHead } : undefined);
161
+ // An earlier pass of this exact tree that covers these tests and checks ends the run here (2026-11-06).
162
+ // Never under enforce, whose receipt must show the decision it applied, nor for tests outside the full
163
+ // suite, which a full run does not cover.
164
+ const reusable = options.reuse !== false && !enforcement && !outsideSuite
165
+ ? findReusablePass(options, before.treeSha, selection, result?.selectedTests ?? [], commands.join(" && "), planned)
166
+ : undefined;
167
+ if (reusable) {
168
+ const reused_from = { produced_at: reusable.produced_at, selection: reusable.selection, ...(reusable.command ? { command: reusable.command } : {}) };
169
+ return {
170
+ ...baseReport(before, scope, boundRange),
171
+ verification: "passed",
172
+ safe_to_continue: true,
173
+ reason: `reused the passing ${reused_from.selection} run of this exact tree from ${reused_from.produced_at}; nothing was run again (--no-reuse runs it)`,
174
+ changed_files: counts.changedFiles,
175
+ tests_available: counts.testsAvailable,
176
+ tests_selected: selection === "full" ? counts.testsAvailable : counts.testsSelected,
177
+ selection,
178
+ ...(selection === "selected" && result ? { selected_tests: result.selectedTests } : {}),
179
+ ...(selection === "selected" && result?.selectionReasons ? { selection_reasons: result.selectionReasons } : {}),
180
+ command,
181
+ ...(commands.length > 1 ? { commands } : {}),
182
+ snapshot: { ...baseReport(before, scope, boundRange).snapshot, after_base_sha: before.baseSha, after_tree_sha: before.treeSha, unchanged: true },
183
+ analysis,
184
+ required_actions: [],
185
+ reused_from,
186
+ ...shardField,
187
+ };
188
+ }
120
189
  const checkBaseline = options.baselineOnFailure && checkBase && checkHead
121
190
  ? (check, remainingMs) => checkAtBaseline({ repoPath: options.repoPath, baseSha: checkBase, headSha: checkHead, command: check.command, timeoutMs: Math.max(remainingMs, 0) })
122
191
  : undefined;
@@ -126,23 +195,31 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
126
195
  // Checks that also fail at the base: still a failed verdict (required CI fails either way), but they
127
196
  // no longer stop the run before the change's own failures.
128
197
  const preexistingChecks = checkRun?.preexisting ?? [];
129
- const preexistingNote = preexistingChecks.length
198
+ const checksNote = preexistingChecks.length
130
199
  ? `; gate check(s) ${preexistingChecks.map((check) => check.id).join(", ")} also fail at the base commit (already broken before this change)`
131
200
  : "";
132
- // Selected `node --test` files run under a probe that records which of them actually started.
201
+ // Every test run goes under a probe that records which `node --test` files started (selected ones must)
202
+ // and each one's duration and result for the outcome log (2026-11-06). Outside node:test it does nothing.
133
203
  const expectedNodeTests = selection === "selected" && result ? selectedNodeTests(command, result.selectedTests) : [];
134
- const trace = expectedNodeTests.length && !checkRun?.failure ? traceNodeTestFiles(options.repoPath) : undefined;
204
+ const trace = !checkRun?.failure ? traceNodeTestFiles(options.repoPath) : undefined;
135
205
  let startedNodeTests;
136
206
  let execution;
137
207
  try {
138
208
  execution = checkRun?.failure
139
209
  ? checkRun.failure.measurement
140
- : measureCommands(commands, { cwd: options.repoPath, timeoutMs: Math.max(options.timeoutMs - (checkRun?.wallMs ?? 0), 0), tailBytes: options.tailBytes, env: trace?.env });
210
+ : measureCommands(commands, { cwd: options.repoPath, timeoutMs: Math.max(options.timeoutMs - (checkRun?.wallMs ?? 0), 0), tailBytes: options.tailBytes, env: trace?.env, stopOnFailure: options.failFast });
141
211
  startedNodeTests = trace?.read();
212
+ const nodeResults = trace?.results() ?? [];
213
+ if (nodeResults.length)
214
+ execution = { ...execution, testResults: mergeTestFileResults(execution.testResults, nodeResults) };
142
215
  }
143
216
  finally {
144
217
  trace?.dispose();
145
218
  }
219
+ const failFastNote = execution.partsNotRun
220
+ ? `; --fail-fast stopped at the first failing part, so ${execution.partsNotRun} later part(s) of the selection did not run`
221
+ : "";
222
+ const preexistingNote = checksNote + failFastNote;
146
223
  let after;
147
224
  try {
148
225
  after = captureWorkingTreeSnapshot(options.repoPath);
@@ -234,6 +311,7 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
234
311
  analysis,
235
312
  required_actions: verification === "passed" ? [] : [finalReason + baselineNote],
236
313
  ...(failureBaseline ? { failure_baseline: failureBaseline } : {}),
314
+ ...shardField,
237
315
  };
238
316
  }
239
317
  function stamped(report, version) {
@@ -383,8 +461,38 @@ function fullSelection(repoPath, reason) {
383
461
  const command = inferFullCommand(repoPath).command;
384
462
  return { selection: "full", command, commands: command ? [command] : [], reason, outsideSuite: 0 };
385
463
  }
464
+ /** Ranks the selected tests by the outcome log's history, or undefined when nothing in it says any is
465
+ * likelier to fail than another, so a repository without history runs its selection exactly as before. */
466
+ function rankedOrdering(options, result) {
467
+ if (options.rank === false || result.mode !== "SELECTIVE")
468
+ return undefined;
469
+ const path = outcomeLogPath(options.repoPath);
470
+ const history = testHistory(path ? readOutcomes(path) : []);
471
+ const reasons = result.selectionReasons ?? {};
472
+ const likely = likelyFailures(result.selectedTests, history, reasons);
473
+ if (likely.length === 0)
474
+ return undefined;
475
+ const order = rankTests(result.selectedTests, history, reasons);
476
+ return { order, ...(options.failFast ? { first: order.filter((test) => likely.includes(test)) } : {}) };
477
+ }
478
+ /** The earlier pass in this repository's outcome log that covers this run, if any (reusablePass). */
479
+ function findReusablePass(options, treeSha, selection, selectedTests, command, planned) {
480
+ const path = outcomeLogPath(options.repoPath);
481
+ if (!path)
482
+ return undefined;
483
+ return reusablePass(readOutcomes(path), {
484
+ tree_sha: treeSha,
485
+ diffci_version: options.version,
486
+ node_version: process.versions.node,
487
+ selection,
488
+ selected_tests: selectedTests,
489
+ command,
490
+ full_command: selection === "full" ? command : fullSelection(options.repoPath, "").command,
491
+ checks: planned.filter((check) => check.decision !== "SKIP").map(({ id, command: checkCommand }) => ({ id, command: checkCommand })),
492
+ });
493
+ }
386
494
  /** Shared executable plan for read-only agent selection and verification. */
387
- export function executableSelection(repoPath, result) {
495
+ export function executableSelection(repoPath, result, ordering, shard) {
388
496
  let selection;
389
497
  let command;
390
498
  let reason;
@@ -458,13 +566,33 @@ export function executableSelection(repoPath, result) {
458
566
  reason = `${reason}; ${outside.length} affected test file(s) outside the full test command were not run (${auxiliary?.reason ?? "no single command covers them"})`;
459
567
  }
460
568
  }
569
+ // Under --shard each selected command keeps only the shard's files, and the test-script phases and the
570
+ // outside-suite command run in shard 1 (test-shards.ts, 2026-11-06). A command that cannot be cut
571
+ // safely leaves the whole selection to shard 1.
572
+ let shardParts;
573
+ let unshardable = false;
574
+ if (shard && selection === "selected" && command) {
575
+ const cut = (selectedParts ?? [primary ?? command]).map((part) => subsetCommand(part, result.selectedTests, shard.tests));
576
+ if (cut.some((part) => part === undefined))
577
+ unshardable = true;
578
+ else
579
+ shardParts = cut.filter((part) => typeof part === "string");
580
+ }
581
+ // A single selected command runs its files likeliest failures first, and under --fail-fast as two
582
+ // invocations, the likely ones and then the rest (test-ranking.ts, 2026-11-06).
583
+ const singleSource = shardParts ? (shardParts.length === 1 ? shardParts[0] : undefined) : primary ?? command;
584
+ const single = selection === "selected" && !selectedParts && ordering ? singleSource : undefined;
585
+ const ordered = single ? orderCommand(single, ordering.order) : undefined;
586
+ const primaryParts = ordered
587
+ ? (ordering.first?.length ? splitCommand(ordered, result.selectedTests, ordering.first) : [ordered]).flatMap((part) => batchCommand(part, result.selectedTests))
588
+ : undefined;
589
+ const extras = !shard || shard.first || unshardable ? [...primaryPhases, ...(auxiliaryCommand ? batchCommand(auxiliaryCommand, outside) : [])] : [];
461
590
  // Each part stays within the shell's command-line limit (cmd.exe stops at 8,191 characters).
462
591
  const commands = command ? [
463
- ...(selectedParts ?? batchCommand(primary ?? command, selection === "selected" ? result.selectedTests : [])),
464
- ...primaryPhases,
465
- ...(auxiliaryCommand ? batchCommand(auxiliaryCommand, outside) : []),
592
+ ...(primaryParts ?? shardParts?.flatMap((part) => batchCommand(part, result.selectedTests)) ?? selectedParts ?? batchCommand(primary ?? command, selection === "selected" ? result.selectedTests : [])),
593
+ ...extras,
466
594
  ] : [];
467
- return { selection, command: commands.length ? commands.join(" && ") : command, commands, reason, outsideSuite };
595
+ return { selection, command: commands.length ? commands.join(" && ") : shard ? undefined : command, commands, reason, outsideSuite, unshardable };
468
596
  }
469
597
  /** A test-script phase as a standalone command. `npm test` puts `node_modules/.bin` on PATH; outside
470
598
  * it a repository-local runner such as tsx is reached the way selected TypeScript tests are. */
@@ -10,7 +10,7 @@ var _isDigit = function isDigit(code) {
10
10
  return code >= 48 && code <= 57;
11
11
  };
12
12
  const forbiddenNumericSeparatorSiblings = {
13
- decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]),
13
+ decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111, 43, 45]),
14
14
  hex: new Set([46, 88, 95, 120])
15
15
  };
16
16
  const isAllowedNumericSeparatorSibling = {
@@ -212,7 +212,7 @@ function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumS
212
212
  pos
213
213
  };
214
214
  errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);
215
- } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) {
215
+ } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev)) {
216
216
  if (bailOnError) return {
217
217
  n: null,
218
218
  pos
@@ -232,12 +232,12 @@ function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumS
232
232
  val = Infinity;
233
233
  }
234
234
  if (val >= radix) {
235
- if (val <= 9 && bailOnError) {
236
- return {
235
+ if (val <= 9) {
236
+ if (bailOnError) return {
237
237
  n: null,
238
238
  pos
239
239
  };
240
- } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) {
240
+ errors.invalidDigit(pos, lineStart, curLine, radix);
241
241
  val = 0;
242
242
  } else if (forceLen) {
243
243
  val = 0;