@diffci.com/diffci 0.3.12 → 0.3.14

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 (65) hide show
  1. package/dist-client/src/client/agent-selection.js +4 -1
  2. package/dist-client/src/client/cli.js +4 -49
  3. package/dist-client/src/client/command-batches.js +80 -0
  4. package/dist-client/src/client/failure-baseline.js +99 -0
  5. package/dist-client/src/client/observe.js +11 -3
  6. package/dist-client/src/client/pilot-packet.js +0 -31
  7. package/dist-client/src/client/verify-savings.js +12 -1
  8. package/dist-client/src/client/verify.js +53 -5
  9. package/dist-client/src/client/workflow-templates.js +80 -0
  10. package/node_modules/@diffci.com/core/README.md +13 -7
  11. package/node_modules/@diffci.com/core/dist/analyze.js +2 -1
  12. package/node_modules/@diffci.com/core/dist/analyze.js.map +1 -1
  13. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  14. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +1 -1
  15. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +9 -0
  16. package/node_modules/@diffci.com/core/dist/git/git-diff.js +122 -19
  17. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  18. package/node_modules/@diffci.com/core/dist/git/types.d.ts +9 -0
  19. package/node_modules/@diffci.com/core/dist/planner/test-command.js +16 -3
  20. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  21. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js +99 -42
  22. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.d.ts +16 -0
  24. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js +101 -0
  25. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js.map +1 -0
  26. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +68 -0
  27. package/node_modules/@diffci.com/core/dist/repo/file-references.js +278 -0
  28. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -0
  29. package/node_modules/@diffci.com/core/dist/repo/graph.d.ts +4 -2
  30. package/node_modules/@diffci.com/core/dist/repo/graph.js +107 -31
  31. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  32. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +7 -1
  33. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +32 -0
  34. package/node_modules/@diffci.com/core/dist/repo/impact.js +241 -20
  35. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  36. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js +9 -3
  37. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js.map +1 -1
  38. package/node_modules/@diffci.com/core/dist/repo/script-universe.d.ts +16 -0
  39. package/node_modules/@diffci.com/core/dist/repo/script-universe.js +173 -0
  40. package/node_modules/@diffci.com/core/dist/repo/script-universe.js.map +1 -0
  41. package/node_modules/@diffci.com/core/dist/repo/test-discovery.d.ts +12 -0
  42. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +54 -7
  43. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  44. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +8 -0
  45. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.d.ts +15 -0
  46. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +157 -0
  47. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -0
  48. package/node_modules/@diffci.com/core/package.json +5 -0
  49. package/node_modules/@diffci.com/core/src/analyze.ts +2 -1
  50. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +1 -1
  51. package/node_modules/@diffci.com/core/src/git/git-diff.ts +106 -20
  52. package/node_modules/@diffci.com/core/src/git/types.ts +9 -0
  53. package/node_modules/@diffci.com/core/src/planner/test-command.ts +17 -3
  54. package/node_modules/@diffci.com/core/src/repo/adapters/maven.ts +120 -30
  55. package/node_modules/@diffci.com/core/src/repo/compiled-projects.ts +108 -0
  56. package/node_modules/@diffci.com/core/src/repo/file-references.ts +275 -0
  57. package/node_modules/@diffci.com/core/src/repo/graph.ts +104 -31
  58. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +10 -0
  59. package/node_modules/@diffci.com/core/src/repo/impact.ts +243 -18
  60. package/node_modules/@diffci.com/core/src/repo/runner-universe.ts +6 -3
  61. package/node_modules/@diffci.com/core/src/repo/script-universe.ts +158 -0
  62. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +62 -7
  63. package/node_modules/@diffci.com/core/src/repo/types.ts +5 -0
  64. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +117 -0
  65. package/package.json +2 -2
@@ -36,12 +36,13 @@ export async function agentSelection(repoInput) {
36
36
  const after = captureWorkingTreeSnapshot(repoPath);
37
37
  const unchanged = before.baseSha === after.baseSha && before.treeSha === after.treeSha;
38
38
  let command;
39
+ let commands = [];
39
40
  let selection = "none";
40
41
  let reason = "no uncommitted changes; use diffci_verify for a committed range";
41
42
  if (before.changed) {
42
43
  reason = observation?.reason ?? "analysis did not produce a runnable plan";
43
44
  if (observation?.status === "OBSERVED" && result) {
44
- ({ command, selection, reason } = executableSelection(repoPath, result));
45
+ ({ command, commands, selection, reason } = executableSelection(repoPath, result));
45
46
  if (!command)
46
47
  reason = `no executable verification command is available: ${reason}`;
47
48
  }
@@ -56,6 +57,8 @@ export async function agentSelection(repoInput) {
56
57
  tests_available: result?.totalTestCount ?? 0,
57
58
  tests_selected: selection === "full" ? result?.totalTestCount ?? 0 : selection === "selected" ? result?.selectedTests.length ?? 0 : 0,
58
59
  command: ready ? command : undefined,
60
+ // Run these one after another when present: the joined command exceeds the shell's limit.
61
+ ...(ready && commands.length > 1 ? { commands } : {}),
59
62
  reason: unchanged ? reason : "working tree changed during analysis; reanalyze",
60
63
  fallback_reasons: result?.fallbackReasons ?? [],
61
64
  analysis_status: observation?.status ?? "not_needed",
@@ -40,8 +40,9 @@ import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conf
40
40
  import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
41
41
  import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
42
42
  import { auditWorkflows, isNonInterfering } from "./workflow-guard.js";
43
- import { buildPilotWorkflow, renderPilotPacket } from "./pilot-packet.js";
43
+ import { renderPilotPacket } from "./pilot-packet.js";
44
44
  import { observerIdentity } from "./package-identity.js";
45
+ import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js";
45
46
  function parseArgs(argv) {
46
47
  const args = argv.slice(2);
47
48
  const flags = {};
@@ -139,53 +140,6 @@ const MANAGED_INSTRUCTIONS_END = "<!-- diffci:managed:end -->";
139
140
  function managedInstructions(content) {
140
141
  return `${MANAGED_INSTRUCTIONS_BEGIN}\n${content.trim()}\n${MANAGED_INSTRUCTIONS_END}\n`;
141
142
  }
142
- function diffciWorkflow(version) {
143
- return `name: DiffCI observation
144
- on: [push, pull_request]
145
- permissions:
146
- contents: read
147
- jobs:
148
- diffci:
149
- runs-on: ubuntu-24.04
150
- continue-on-error: true
151
- steps:
152
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # immutable checkout pin
153
- with:
154
- fetch-depth: 0
155
- - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # immutable setup-node pin
156
- with:
157
- node-version: 22
158
- - run: npx "@diffci.com/diffci@${version}" observe --no-send
159
- `;
160
- }
161
- function diffciVerificationWorkflow(version) {
162
- return `name: DiffCI verification
163
- on: [push, pull_request]
164
- permissions:
165
- contents: read
166
- jobs:
167
- diffci-verify:
168
- name: DiffCI verification
169
- runs-on: ubuntu-24.04
170
- steps:
171
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # immutable checkout pin
172
- with:
173
- fetch-depth: 0
174
- ref: \${{ github.event.pull_request.head.sha || github.sha }}
175
- - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # immutable setup-node pin
176
- with:
177
- node-version: 22
178
- - name: Verify changed code
179
- run: npx "@diffci.com/diffci@${version}" verify --json --out "$RUNNER_TEMP/diffci-verification.json"
180
- - name: Upload verification receipt
181
- if: always()
182
- uses: actions/upload-artifact@v4
183
- with:
184
- name: diffci-verification-\${{ github.run_id }}-\${{ github.run_attempt }}
185
- path: \${{ runner.temp }}/diffci-verification.json
186
- if-no-files-found: warn
187
- `;
188
- }
189
143
  function writeInitFile(repoPath, relativePath, content, force) {
190
144
  const absolutePath = join(repoPath, relativePath);
191
145
  const existed = existsSync(absolutePath);
@@ -359,6 +313,7 @@ async function runVerifyCommand(flags, env) {
359
313
  timeoutMs: numberFlag(flags, "timeout-ms") ?? 30 * 60 * 1000,
360
314
  tailBytes: numberFlag(flags, "tail-bytes") ?? 12_000,
361
315
  redactPaths: flags["redact-paths"] === true,
316
+ baselineOnFailure: flags["baseline-on-failure"] === true || env.DIFFCI_BASELINE_ON_FAILURE === "1",
362
317
  };
363
318
  const report = changed
364
319
  ? await verifyChanged(common)
@@ -857,7 +812,7 @@ Usage:
857
812
  diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--force]
858
813
  diffci mcp
859
814
  diffci verify [--changed | --base <sha> --head <sha>] [--repo <path>] [--out <file>] [--json]
860
- [--redact-paths] [--timeout-ms <ms>]
815
+ [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure]
861
816
  diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
862
817
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
863
818
  diffci pilot --full <command> [--selected <command>] [--repo <path>] [--out-dir <dir>] [--label <name>]
@@ -0,0 +1,80 @@
1
+ import { measureCommand } from "./verify-savings.js";
2
+ /**
3
+ * Selected-test commands too long for the shell (2026-10-21).
4
+ *
5
+ * WHY. A selection is one runner invocation listing every selected test file. Windows runs it through
6
+ * cmd.exe, whose command line stops at 8,191 characters: replaying a dogfood repository, every
7
+ * selection of 191 files failed in under a second with exit 255 before any test ran, which a receipt
8
+ * would report as a failed verification. Linux shells allow far more, so CI never saw it.
9
+ *
10
+ * WHAT. A command over the limit is split into several invocations of the same runner prefix, each
11
+ * listing a share of the files, run one after another and reported as one verification. Splitting only
12
+ * happens when the command ends in exactly the selected paths as plain tokens; anything else is left
13
+ * whole, because rewriting a command that is not understood could change what it runs.
14
+ */
15
+ export const COMMAND_LINE_LIMIT = process.platform === "win32" ? 8000 : 100_000;
16
+ /** `command` split so each part fits `limit`, or `[command]` when it fits or cannot be split safely. */
17
+ export function batchCommand(command, paths, limit = COMMAND_LINE_LIMIT) {
18
+ if (command.length <= limit || paths.length === 0)
19
+ return [command];
20
+ const tokens = command.split(" ");
21
+ const selected = new Set(paths);
22
+ let start = tokens.length;
23
+ while (start > 0 && selected.has(tokens[start - 1]))
24
+ start--;
25
+ const trailing = tokens.slice(start);
26
+ if (trailing.length === 0 || new Set(trailing).size !== trailing.length)
27
+ return [command];
28
+ const prefix = tokens.slice(0, start).join(" ");
29
+ if (prefix.length + 1 + Math.max(...trailing.map((t) => t.length)) > limit)
30
+ return [command];
31
+ const batches = [[]];
32
+ let length = prefix.length;
33
+ for (const token of trailing) {
34
+ const batch = batches[batches.length - 1];
35
+ if (batch.length > 0 && length + 1 + token.length > limit) {
36
+ batches.push([token]);
37
+ length = prefix.length + 1 + token.length;
38
+ }
39
+ else {
40
+ batch.push(token);
41
+ length += 1 + token.length;
42
+ }
43
+ }
44
+ return batches.map((batch) => `${prefix} ${batch.join(" ")}`);
45
+ }
46
+ /**
47
+ * Runs `commands` in order as one verification. Every part runs, so one receipt carries every failing
48
+ * test; the first non-zero exit is the result, and the remaining time budget is shared between parts.
49
+ */
50
+ export function measureCommands(commands, options) {
51
+ if (commands.length === 1)
52
+ return measureCommand(commands[0], options);
53
+ const started = Date.now();
54
+ const parts = [];
55
+ for (const command of commands) {
56
+ const remaining = options.timeoutMs - (Date.now() - started);
57
+ if (remaining <= 0)
58
+ break;
59
+ const part = measureCommand(command, { ...options, timeoutMs: remaining });
60
+ parts.push(part);
61
+ if (part.timedOut)
62
+ break;
63
+ }
64
+ const failed = parts.find((part) => part.exitCode !== 0 || part.signal !== null || part.timedOut);
65
+ const ranAll = parts.length === commands.length;
66
+ const failingTests = [...new Set(parts.flatMap((part) => part.failingTests ?? []))].sort();
67
+ const tail = (key) => parts.map((part) => part[key]).join("").slice(-Math.max(options.tailBytes, 0) || undefined);
68
+ return {
69
+ command: commands.join(" && "),
70
+ exitCode: failed ? failed.exitCode : ranAll ? 0 : null,
71
+ signal: failed?.signal ?? null,
72
+ timedOut: parts.some((part) => part.timedOut) || !ranAll,
73
+ startedAt: parts[0]?.startedAt ?? new Date(started).toISOString(),
74
+ finishedAt: parts[parts.length - 1]?.finishedAt ?? new Date().toISOString(),
75
+ wallMs: Date.now() - started,
76
+ stdoutTail: options.tailBytes > 0 ? tail("stdoutTail") : "",
77
+ stderrTail: options.tailBytes > 0 ? tail("stderrTail") : "",
78
+ ...(failingTests.length ? { failingTests } : {}),
79
+ };
80
+ }
@@ -0,0 +1,99 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, lstatSync, mkdtempSync, readFileSync, rmdirSync, rmSync, symlinkSync, unlinkSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { measureCommands } from "./command-batches.js";
6
+ const DEPENDENCY_FILES = ["package.json", "package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"];
7
+ /** Test names a runner reported as failing: node:test spec and TAP, Vitest and Jest. */
8
+ export function failingTestNames(output) {
9
+ const names = new Set();
10
+ for (const raw of output.split(/\r?\n/)) {
11
+ const line = raw.replace(/\x1b\[[0-9;]*m/g, "");
12
+ const spec = /^\s*✖\s+(.+?)\s+\(\d+(?:\.\d+)?m?s\)\s*$/.exec(line);
13
+ const tap = /^\s*not ok \d+ - (.+?)\s*(?:#.*)?$/.exec(line);
14
+ const vitest = /^\s*(?:FAIL|×)\s+(.+?)(?:\s+\d+(?:\.\d+)?m?s)?\s*$/.exec(line);
15
+ const jest = /^\s*●\s+(.+›.+?)\s*$/.exec(line);
16
+ const name = (spec ?? tap ?? vitest ?? jest)?.[1]?.trim();
17
+ if (name && !/^failing tests:?$/i.test(name))
18
+ names.add(name);
19
+ }
20
+ return [...names].sort();
21
+ }
22
+ function declaresDependencies(repoPath) {
23
+ try {
24
+ const pkg = JSON.parse(readFileSync(join(repoPath, "package.json"), "utf8"));
25
+ return ["dependencies", "devDependencies", "optionalDependencies"].some((field) => Object.keys(pkg[field] ?? {}).length > 0);
26
+ }
27
+ catch {
28
+ return existsSync(join(repoPath, "package.json"));
29
+ }
30
+ }
31
+ function git(repoPath, args) {
32
+ return spawnSync("git", args, { cwd: repoPath, encoding: "buffer", maxBuffer: 1024 * 1024 * 1024 });
33
+ }
34
+ export function compareWithBaseline(input) {
35
+ const report = (status, reason, extra = {}) => ({
36
+ status, base_sha: input.baseSha, reason, failing_at_head: input.headFailures.length, preexisting: [], introduced: [], ...extra,
37
+ });
38
+ if (input.headFailures.length === 0)
39
+ return report("unknown", "no failing test names could be identified in the verification output");
40
+ const changedDependencies = git(input.repoPath, ["diff", "--quiet", input.baseSha, input.headSha, "--", ...DEPENDENCY_FILES]);
41
+ if (changedDependencies.status !== 0)
42
+ return report("unknown", "dependency manifests or lockfiles differ between base and head");
43
+ const modules = join(input.repoPath, "node_modules");
44
+ if (declaresDependencies(input.repoPath) && !existsSync(modules)) {
45
+ return report("unknown", "no installed node_modules to run the base commit with");
46
+ }
47
+ const directory = mkdtempSync(join(tmpdir(), "diffci-baseline-"));
48
+ const link = join(directory, "node_modules");
49
+ try {
50
+ const archive = git(input.repoPath, ["archive", "--format=tar", input.baseSha]);
51
+ if (archive.status !== 0)
52
+ return report("unknown", "the base commit could not be exported");
53
+ const extract = spawnSync("tar", ["-x", "-f", "-", "-C", directory], { input: archive.stdout, maxBuffer: 64 * 1024 * 1024 });
54
+ if (extract.status !== 0)
55
+ return report("unknown", "the base commit could not be extracted");
56
+ if (existsSync(modules))
57
+ symlinkSync(modules, link, process.platform === "win32" ? "junction" : "dir");
58
+ const execution = measureCommands(input.commands, { cwd: directory, timeoutMs: input.timeoutMs, tailBytes: 0 });
59
+ const baseExecution = { exit_code: execution.exitCode, wall_ms: execution.wallMs, timed_out: execution.timedOut };
60
+ if (execution.timedOut)
61
+ return report("unknown", "the base run timed out", { base_execution: baseExecution });
62
+ const atBase = new Set(execution.failingTests ?? []);
63
+ if (execution.exitCode === 0) {
64
+ return report("introduced", "the same command passes at the base commit", { failing_at_base: 0, introduced: input.headFailures.slice(0, 20), base_execution: baseExecution });
65
+ }
66
+ const preexisting = input.headFailures.filter((name) => atBase.has(name));
67
+ const introduced = input.headFailures.filter((name) => !atBase.has(name));
68
+ const status = introduced.length === 0 ? "preexisting" : preexisting.length === 0 ? "introduced" : "mixed";
69
+ const reason = status === "preexisting"
70
+ ? `all ${preexisting.length} failing test(s) also fail at the base commit`
71
+ : status === "introduced"
72
+ ? `none of the ${introduced.length} failing test(s) fail at the base commit`
73
+ : `${introduced.length} failing test(s) are new; ${preexisting.length} also fail at the base commit`;
74
+ return report(status, reason, { failing_at_base: atBase.size, preexisting: preexisting.slice(0, 20), introduced: introduced.slice(0, 20), base_execution: baseExecution });
75
+ }
76
+ catch (error) {
77
+ return report("unknown", `the base run could not be prepared: ${error instanceof Error ? error.message : String(error)}`);
78
+ }
79
+ finally {
80
+ // Remove the dependency link itself first, so cleanup can never descend into the real node_modules.
81
+ let linked = false;
82
+ try {
83
+ if (lstatSync(link, { throwIfNoEntry: false })) {
84
+ try {
85
+ unlinkSync(link);
86
+ }
87
+ catch {
88
+ rmdirSync(link);
89
+ }
90
+ }
91
+ }
92
+ catch {
93
+ linked = true;
94
+ }
95
+ // If the link could not be removed, leave the temporary directory rather than risk the real one.
96
+ if (!linked)
97
+ rmSync(directory, { recursive: true, force: true });
98
+ }
99
+ }
@@ -163,8 +163,8 @@ export async function observe(options) {
163
163
  if (economics.decision === "BYPASS_FULL")
164
164
  return finish("REFUSED", "eligibility", { reason: `ECONOMICS_FULL_BYPASS: ${economics.reason}. No selective command is authorized.` });
165
165
  }
166
- const [{ analyzeGitDelta }, { classifyRepositoryProject, buildDependencyGraph }, { ImpactAnalyzer }, { runPathBaseline }, { commandSpecToString, planSelectiveTestCommands }] = await Promise.all([
167
- import("@diffci.com/core/git/git-diff"), import("@diffci.com/core/repo/graph"), import("@diffci.com/core/repo/impact"), import("@diffci.com/core/planner/path-baseline"), import("@diffci.com/core/planner/test-command"),
166
+ const [{ analyzeGitDelta }, { classifyRepositoryProject, buildDependencyGraph }, { ImpactAnalyzer }, { runPathBaseline }, { commandSpecToString, planSelectiveTestCommands }, { repositoryFileReader }] = await Promise.all([
167
+ import("@diffci.com/core/git/git-diff"), import("@diffci.com/core/repo/graph"), import("@diffci.com/core/repo/impact"), import("@diffci.com/core/planner/path-baseline"), import("@diffci.com/core/planner/test-command"), import("@diffci.com/core/repo/file-references"),
168
168
  ]);
169
169
  markPhase("engineLoad");
170
170
  // The eligibility gate is asked of the graph builder itself (classifyRepositoryProject), not of a
@@ -193,6 +193,7 @@ export async function observe(options) {
193
193
  const profile = graphResult.profile;
194
194
  const impact = new ImpactAnalyzer().analyze(delta, graphResult, profile, {
195
195
  repositoryFiles: deltaResult.inventory?.files,
196
+ readRepositoryFile: repositoryFileReader(repoPath),
196
197
  });
197
198
  const baseline = runPathBaseline(profile.testFilePaths, delta.files, profile);
198
199
  const selectedTests = impact.affectedTests.map((test) => test.path).sort();
@@ -202,6 +203,8 @@ export async function observe(options) {
202
203
  const commandPlan = impact.fallbackRequired
203
204
  ? undefined
204
205
  : planSelectiveTestCommands(profile, selectedTests);
206
+ const outsideSuite = (impact.testsOutsideFullSuite ?? []).map((test) => test.path).sort();
207
+ const outsidePlan = outsideSuite.length ? planSelectiveTestCommands(profile, outsideSuite) : undefined;
205
208
  markPhase("impactAndCommands");
206
209
  return finish("OBSERVED", "complete", {
207
210
  result: {
@@ -210,7 +213,12 @@ export async function observe(options) {
210
213
  changedFiles: delta.files.map((file) => hashPath(file.path)),
211
214
  affectedSourceFileCount: impact.affectedSourceFiles.length,
212
215
  selectedTests: selectedTests.map(hashPath),
213
- totalTestCount: profile.testFilePaths.length,
216
+ totalTestCount: impact.fullSuiteTestCount ?? profile.testFilePaths.length,
217
+ discoveredTestCount: profile.testFilePaths.length,
218
+ ...(outsideSuite.length ? {
219
+ testsOutsideFullSuite: outsideSuite.map(hashPath),
220
+ outsideSuiteCommands: outsidePlan?.refusalReason ? [] : (outsidePlan?.commands ?? []).map(commandSpecToString),
221
+ } : {}),
214
222
  fallbackReasons: impact.fallbackReasons,
215
223
  proposedCommands: (commandPlan?.commands ?? []).map(commandSpecToString),
216
224
  workspaceCommands: Boolean(profile.workspaceTestPackages?.length),
@@ -1,40 +1,9 @@
1
- const CHECKOUT_SHA = "3d3c42e5aac5ba805825da76410c181273ba90b1";
2
- const SETUP_NODE_SHA = "820762786026740c76f36085b0efc47a31fe5020";
3
- const UPLOAD_ARTIFACT_SHA = "043fb46d1a93c77aae656e7c1c64a875d1fc6a0a";
4
1
  function text(value) {
5
2
  return value?.trim() || "not reported";
6
3
  }
7
4
  function bullets(values, empty) {
8
5
  return values.length > 0 ? values.map((value) => `- ${value}`).join("\n") : `- ${empty}`;
9
6
  }
10
- export function buildPilotWorkflow(version) {
11
- return `name: DiffCI pilot observation
12
- on: [pull_request]
13
- permissions:
14
- contents: read
15
- jobs:
16
- diffci-pilot:
17
- name: DiffCI pilot (non-blocking)
18
- runs-on: ubuntu-24.04
19
- continue-on-error: true
20
- steps:
21
- - uses: actions/checkout@${CHECKOUT_SHA} # immutable checkout pin
22
- with:
23
- fetch-depth: 0
24
- - uses: actions/setup-node@${SETUP_NODE_SHA} # immutable setup-node pin
25
- with:
26
- node-version: 22
27
- - name: Observe only
28
- run: npx "@diffci.com/diffci@${version}" observe --no-send --out "$RUNNER_TEMP/diffci-observe.json"
29
- - name: Upload local observation
30
- if: always()
31
- uses: actions/upload-artifact@${UPLOAD_ARTIFACT_SHA} # immutable upload-artifact v7 pin
32
- with:
33
- name: diffci-observation-\${{ github.run_id }}-\${{ github.run_attempt }}
34
- path: \${{ runner.temp }}/diffci-observe.json
35
- if-no-files-found: warn
36
- `;
37
- }
38
7
  export function renderPilotPacket(report, options) {
39
8
  const result = report.result;
40
9
  const range = report.commitRange;
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
3
3
  import { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { arch, cpus, platform, release, totalmem } from "node:os";
5
5
  import { basename, dirname, resolve } from "node:path";
6
+ import { failingTestNames } from "./failure-baseline.js";
6
7
  import { classifyFailureFromEvidence, computeFailureFingerprint } from "../preflight/fingerprint.js";
7
8
  function tail(value, bytes) {
8
9
  if (Buffer.byteLength(value, "utf8") <= bytes)
@@ -237,6 +238,13 @@ function assessFailures(trials) {
237
238
  }
238
239
  return { kind: "inconclusive", confidence: "low", explanation: "The failures were not stable enough to classify conservatively.", evidence };
239
240
  }
241
+ /** A `node --test` started while NODE_TEST_CONTEXT is set reports to that parent runner instead of
242
+ * running as its own suite, and exits 0 without executing anything. DiffCI launched from inside a test
243
+ * process (an agent's harness, DiffCI's own tests) must still measure the real suite (2026-10-21). */
244
+ function withoutTestRunnerContext(env) {
245
+ const { NODE_TEST_CONTEXT: _context, ...rest } = env;
246
+ return rest;
247
+ }
240
248
  export function measureCommand(command, options) {
241
249
  const startedAt = new Date().toISOString();
242
250
  const started = Date.now();
@@ -252,7 +260,7 @@ export function measureCommand(command, options) {
252
260
  shell: false,
253
261
  windowsVerbatimArguments: process.platform === "win32",
254
262
  env: {
255
- ...process.env,
263
+ ...withoutTestRunnerContext(process.env),
256
264
  CI: "1",
257
265
  FORCE_COLOR: "0",
258
266
  COREPACK_ENABLE_DOWNLOAD_PROMPT: "0",
@@ -260,6 +268,8 @@ export function measureCommand(command, options) {
260
268
  },
261
269
  });
262
270
  const finishedAt = new Date().toISOString();
271
+ const failingTests = result.status === 0 ? [] : failingTestNames(`${result.stdout ?? ""}
272
+ ${result.stderr ?? ""}`);
263
273
  return {
264
274
  command,
265
275
  exitCode: result.status,
@@ -270,6 +280,7 @@ export function measureCommand(command, options) {
270
280
  wallMs: Date.now() - started,
271
281
  stdoutTail: tail(result.stdout ?? "", options.tailBytes),
272
282
  stderrTail: tail(result.stderr ?? "", options.tailBytes),
283
+ ...(failingTests.length ? { failingTests } : {}),
273
284
  };
274
285
  }
275
286
  export function buildVerifySavingsReport(input) {
@@ -1,9 +1,10 @@
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";
5
+ import { compareWithBaseline } from "./failure-baseline.js";
4
6
  import { inferFullCommand, inferSelectedCommand } from "./full-command.js";
5
7
  import { observe } from "./observe.js";
6
- import { measureCommand } from "./verify-savings.js";
7
8
  import { captureWorkingTreeSnapshot } from "./working-tree.js";
8
9
  export const VERIFICATION_SCHEMA = "diffci.verification.v1";
9
10
  function receiptRange(range) {
@@ -62,6 +63,8 @@ async function executeObservation(options, scope, before, observation) {
62
63
  mode: result?.mode,
63
64
  fallback_reasons: result?.fallbackReasons ?? [],
64
65
  error: observation.reason,
66
+ ...(observation.timings?.totalMs !== undefined ? { duration_ms: observation.timings.totalMs } : {}),
67
+ ...(result?.graph ? { graph_confidence: result.graph.confidence, effective_graph_confidence: result.graph.effectiveConfidence } : {}),
65
68
  };
66
69
  if (observation.status !== "OBSERVED" || !result) {
67
70
  return blocked(before, scope, observation.reason ?? "DiffCI analysis did not produce a verification plan", analysis, counts, boundRange);
@@ -87,12 +90,12 @@ async function executeObservation(options, scope, before, observation) {
87
90
  report.snapshot.after_tree_sha = afterAnalysis.treeSha;
88
91
  return report;
89
92
  }
90
- const { selection, command, reason } = executableSelection(options.repoPath, result);
93
+ const { selection, command, commands, reason, outsideSuite } = executableSelection(options.repoPath, result);
91
94
  if (!command) {
92
95
  const inferred = inferFullCommand(options.repoPath);
93
96
  return blocked(before, scope, `no executable verification command is available: ${inferred.reason}`, analysis, counts, boundRange);
94
97
  }
95
- const execution = measureCommand(command, { cwd: options.repoPath, timeoutMs: options.timeoutMs, tailBytes: options.tailBytes });
98
+ const execution = measureCommands(commands, { cwd: options.repoPath, timeoutMs: options.timeoutMs, tailBytes: options.tailBytes });
96
99
  let after;
97
100
  try {
98
101
  after = captureWorkingTreeSnapshot(options.repoPath);
@@ -103,6 +106,7 @@ async function executeObservation(options, scope, before, observation) {
103
106
  ...blocked(before, scope, `could not confirm the post-verification snapshot: ${message}`, analysis, counts, boundRange),
104
107
  selection,
105
108
  command,
109
+ ...(commands.length > 1 ? { commands } : {}),
106
110
  execution,
107
111
  };
108
112
  }
@@ -116,6 +120,13 @@ async function executeObservation(options, scope, before, observation) {
116
120
  : execution.timedOut
117
121
  ? `verification timed out after ${options.timeoutMs}ms`
118
122
  : `verification command failed with exit code ${String(execution.exitCode)}`;
123
+ const baselineSha = scope === "commit-range" ? range?.baseSha : before.baseSha;
124
+ const failureBaseline = verification === "failed" && !execution.timedOut && options.baselineOnFailure && baselineSha
125
+ ? compareWithBaseline({ repoPath: options.repoPath, baseSha: baselineSha, headSha: scope === "commit-range" ? before.baseSha : before.commitSha, commands, headFailures: execution.failingTests ?? [], timeoutMs: options.timeoutMs })
126
+ : undefined;
127
+ const baselineNote = failureBaseline && failureBaseline.status !== "unknown"
128
+ ? `; ${failureBaseline.reason} (${failureBaseline.base_sha.slice(0, 12)})`
129
+ : "";
119
130
  return {
120
131
  ...baseReport(before, scope, boundRange),
121
132
  verification,
@@ -124,8 +135,10 @@ async function executeObservation(options, scope, before, observation) {
124
135
  changed_files: counts.changedFiles,
125
136
  tests_available: counts.testsAvailable,
126
137
  tests_selected: selection === "full" ? counts.testsAvailable : counts.testsSelected,
138
+ ...(outsideSuite ? { tests_outside_full_suite: outsideSuite } : {}),
127
139
  selection,
128
140
  command,
141
+ ...(commands.length > 1 ? { commands } : {}),
129
142
  execution,
130
143
  snapshot: {
131
144
  ...baseReport(before, scope, boundRange).snapshot,
@@ -134,11 +147,19 @@ async function executeObservation(options, scope, before, observation) {
134
147
  unchanged,
135
148
  },
136
149
  analysis,
137
- required_actions: verification === "passed" ? [] : [finalReason],
150
+ required_actions: verification === "passed" ? [] : [finalReason + baselineNote],
151
+ ...(failureBaseline ? { failure_baseline: failureBaseline } : {}),
138
152
  };
139
153
  }
154
+ function stamped(report, version) {
155
+ const { schema, schema_version, produced_at, ...rest } = report;
156
+ return { schema, schema_version, produced_at, diffci_version: version, ...rest };
157
+ }
140
158
  /** Verify exactly the staged, unstaged, and non-ignored untracked content currently on disk. */
141
159
  export async function verifyChanged(options) {
160
+ return stamped(await verifyChangedSnapshot(options), options.version);
161
+ }
162
+ async function verifyChangedSnapshot(options) {
142
163
  const repoPath = resolve(options.repoPath);
143
164
  let before;
144
165
  try {
@@ -188,6 +209,9 @@ export async function verifyChanged(options) {
188
209
  }
189
210
  /** Verify a real commit range and bind the receipt to the clean commit that was actually executed. */
190
211
  export async function verifyRange(options) {
212
+ return stamped(await verifyCommitRange(options), options.version);
213
+ }
214
+ async function verifyCommitRange(options) {
191
215
  const repoPath = resolve(options.repoPath);
192
216
  let before;
193
217
  try {
@@ -266,5 +290,29 @@ export function executableSelection(repoPath, result) {
266
290
  const fallback = result.fallbackReasons[0] ?? result.commandRefusalReason;
267
291
  reason = fallback ? `full verification required: ${fallback}` : "full verification required";
268
292
  }
269
- return { selection, command, reason };
293
+ // Affected tests the full command never runs are still affected: run them after the selection
294
+ // rather than counting them in it (2026-10-21).
295
+ const outside = result.testsOutsideFullSuite ?? [];
296
+ let outsideSuite = 0;
297
+ let primary;
298
+ let auxiliaryCommand;
299
+ if (command && outside.length) {
300
+ const auxiliary = result.outsideSuiteCommands?.length === 1 ? inferSelectedCommand(repoPath, result.outsideSuiteCommands[0], outside) : undefined;
301
+ if (auxiliary?.command) {
302
+ primary = command;
303
+ auxiliaryCommand = auxiliary.command;
304
+ command = `${command} && ${auxiliary.command}`;
305
+ outsideSuite = outside.length;
306
+ reason = `${reason}; also ran ${outside.length} affected test file(s) the full test command does not run`;
307
+ }
308
+ else {
309
+ reason = `${reason}; ${outside.length} affected test file(s) outside the full test command were not run (${auxiliary?.reason ?? "no single command covers them"})`;
310
+ }
311
+ }
312
+ // Each part stays within the shell's command-line limit (cmd.exe stops at 8,191 characters).
313
+ const commands = command ? [
314
+ ...batchCommand(primary ?? command, selection === "selected" ? result.selectedTests : []),
315
+ ...(auxiliaryCommand ? batchCommand(auxiliaryCommand, outside) : []),
316
+ ] : [];
317
+ return { selection, command: commands.length ? commands.join(" && ") : command, commands, reason, outsideSuite };
270
318
  }
@@ -0,0 +1,80 @@
1
+ /** GitHub-hosted runner and Node 24 action pins shared by every workflow the CLI generates. */
2
+ export const RUNNER = "ubuntu-26.04";
3
+ export const CHECKOUT_SHA = "3d3c42e5aac5ba805825da76410c181273ba90b1"; // actions/checkout v7.0.1
4
+ export const SETUP_NODE_SHA = "820762786026740c76f36085b0efc47a31fe5020"; // actions/setup-node v7.0.0
5
+ export const UPLOAD_ARTIFACT_SHA = "043fb46d1a93c77aae656e7c1c64a875d1fc6a0a"; // actions/upload-artifact v7.0.1
6
+ export function diffciWorkflow(version) {
7
+ return `name: DiffCI observation
8
+ on: [push, pull_request]
9
+ permissions:
10
+ contents: read
11
+ jobs:
12
+ diffci:
13
+ runs-on: ${RUNNER}
14
+ continue-on-error: true
15
+ steps:
16
+ - uses: actions/checkout@${CHECKOUT_SHA} # immutable checkout pin
17
+ with:
18
+ fetch-depth: 0
19
+ - uses: actions/setup-node@${SETUP_NODE_SHA} # immutable setup-node pin
20
+ with:
21
+ node-version: 22
22
+ - run: npx "@diffci.com/diffci@${version}" observe --no-send
23
+ `;
24
+ }
25
+ export function diffciVerificationWorkflow(version) {
26
+ return `name: DiffCI verification
27
+ on: [push, pull_request]
28
+ permissions:
29
+ contents: read
30
+ jobs:
31
+ diffci-verify:
32
+ name: DiffCI verification
33
+ runs-on: ${RUNNER}
34
+ steps:
35
+ - uses: actions/checkout@${CHECKOUT_SHA} # immutable checkout pin
36
+ with:
37
+ fetch-depth: 0
38
+ ref: \${{ github.event.pull_request.head.sha || github.sha }}
39
+ - uses: actions/setup-node@${SETUP_NODE_SHA} # immutable setup-node pin
40
+ with:
41
+ node-version: 22
42
+ - name: Verify changed code
43
+ run: npx "@diffci.com/diffci@${version}" verify --json --out "$RUNNER_TEMP/diffci-verification.json"
44
+ - name: Upload verification receipt
45
+ if: always()
46
+ uses: actions/upload-artifact@${UPLOAD_ARTIFACT_SHA} # immutable upload-artifact v7 pin
47
+ with:
48
+ name: diffci-verification-\${{ github.run_id }}-\${{ github.run_attempt }}
49
+ path: \${{ runner.temp }}/diffci-verification.json
50
+ if-no-files-found: warn
51
+ `;
52
+ }
53
+ export function buildPilotWorkflow(version) {
54
+ return `name: DiffCI pilot observation
55
+ on: [pull_request]
56
+ permissions:
57
+ contents: read
58
+ jobs:
59
+ diffci-pilot:
60
+ name: DiffCI pilot (non-blocking)
61
+ runs-on: ${RUNNER}
62
+ continue-on-error: true
63
+ steps:
64
+ - uses: actions/checkout@${CHECKOUT_SHA} # immutable checkout pin
65
+ with:
66
+ fetch-depth: 0
67
+ - uses: actions/setup-node@${SETUP_NODE_SHA} # immutable setup-node pin
68
+ with:
69
+ node-version: 22
70
+ - name: Observe only
71
+ run: npx "@diffci.com/diffci@${version}" observe --no-send --out "$RUNNER_TEMP/diffci-observe.json"
72
+ - name: Upload local observation
73
+ if: always()
74
+ uses: actions/upload-artifact@${UPLOAD_ARTIFACT_SHA} # immutable upload-artifact v7 pin
75
+ with:
76
+ name: diffci-observation-\${{ github.run_id }}-\${{ github.run_attempt }}
77
+ path: \${{ runner.temp }}/diffci-observe.json
78
+ if-no-files-found: warn
79
+ `;
80
+ }