@diffci.com/diffci 0.3.20 → 0.3.21

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.
@@ -12,6 +12,7 @@
12
12
  * init seed a repository with AI-agent instructions for using DiffCI
13
13
  * mcp run the stdio MCP server
14
14
  * verify fail-closed verification of a working-tree snapshot or commit range
15
+ * gate run a build's whole gate and record what DiffCI would have skipped (observe)
15
16
  * check analysis plus automatic paired runtime measurement
16
17
  * observe analyse the checkout and write an observation report
17
18
  * verify-savings run a paired full-versus-selected timing check
@@ -41,6 +42,7 @@ import { configureTelemetry, readTelemetryPreference, recordUsage } from "./tele
41
42
  import { formatFeedbackPrompt, markFeedbackPromptShown, shouldShowFeedbackPrompt } from "./feedback-prompt.js";
42
43
  import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conflicts.js";
43
44
  import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
45
+ import { formatGateSummary, gateExitCode, planGate, runGate } from "./gate.js";
44
46
  import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
45
47
  import { auditWorkflows, isNonInterfering } from "./workflow-guard.js";
46
48
  import { renderPilotPacket } from "./pilot-packet.js";
@@ -367,6 +369,84 @@ async function runVerifyCommand(flags, env) {
367
369
  }
368
370
  return verificationExitCode(report);
369
371
  }
372
+ async function runGateCommand(flags, env) {
373
+ const mode = stringFlag(flags, "mode") ?? "observe";
374
+ if (mode !== "observe") {
375
+ console.error(`diffci gate supports only --mode observe for now, got ${JSON.stringify(mode)}`);
376
+ return 2;
377
+ }
378
+ const only = stringFlag(flags, "only");
379
+ if (only !== undefined && only !== "checks" && only !== "tests") {
380
+ console.error(`diffci gate --only accepts "checks" or "tests", got ${JSON.stringify(only)}`);
381
+ return 2;
382
+ }
383
+ const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
384
+ const out = stringFlag(flags, "out");
385
+ const reportPath = out ? resolve(out) : undefined;
386
+ if (reportPath && (reportPath === repoPath || isInsideRepository(repoPath, reportPath))) {
387
+ console.error(`Refusing to write the gate report inside the repository: ${reportPath}. Use --out with a path outside the checkout.`);
388
+ return 2;
389
+ }
390
+ const identity = observerIdentity();
391
+ const scripts = stringFlag(flags, "script")?.split(",").map((name) => name.trim()).filter(Boolean);
392
+ const common = {
393
+ repoPath,
394
+ env: env,
395
+ version: identity.version,
396
+ engineSha: identity.sha,
397
+ baseOverride: stringFlag(flags, "base"),
398
+ headOverride: stringFlag(flags, "head"),
399
+ scripts,
400
+ };
401
+ // Plan only: where the checkout has history, for a gate that runs where it does not. Never fails, so a
402
+ // build that plans first is not stopped by DiffCI; an unusable plan makes the gate run unplanned.
403
+ const planOut = stringFlag(flags, "plan-out");
404
+ if (planOut) {
405
+ const planPath = resolve(planOut);
406
+ if (planPath === repoPath || isInsideRepository(repoPath, planPath)) {
407
+ console.error(`Refusing to write the gate plan inside the repository: ${planPath}. Use a path outside the checkout.`);
408
+ return 2;
409
+ }
410
+ const plan = await planGate(common);
411
+ mkdirSync(dirname(planPath), { recursive: true });
412
+ writeFileSync(planPath, `${JSON.stringify(plan, null, 2)}\n`, "utf8");
413
+ console.log(`DiffCI gate plan: ${plan.analysis.status}${plan.range ? ` ${plan.range.base_sha.slice(0, 12)}..${plan.range.head_sha.slice(0, 12)}` : ""}${plan.analysis.reason ? ` - ${plan.analysis.reason}` : ""}`);
414
+ console.log(` ${plan.checks.filter((check) => check.decision === "SKIP").length} of ${plan.checks.length} checks would be skipped; tests: ${plan.tests.selection} (${plan.tests.tests_selected}/${plan.tests.tests_available})`);
415
+ console.log(` plan: ${planPath}`);
416
+ return 0;
417
+ }
418
+ const planFile = stringFlag(flags, "plan");
419
+ let plan;
420
+ if (planFile) {
421
+ try {
422
+ plan = JSON.parse(readFileSync(resolve(planFile), "utf8"));
423
+ }
424
+ catch {
425
+ plan = null;
426
+ }
427
+ }
428
+ const report = await runGate({
429
+ ...common,
430
+ tests: stringFlag(flags, "tests"),
431
+ measureSelected: flags["measure-selected"] === true,
432
+ only: only,
433
+ ...(planFile ? { plan, expectHead: stringFlag(flags, "expect-head") } : {}),
434
+ timeoutMs: numberFlag(flags, "timeout-ms") ?? 60 * 60 * 1000,
435
+ tailBytes: numberFlag(flags, "tail-bytes") ?? 12_000,
436
+ });
437
+ if (reportPath) {
438
+ mkdirSync(dirname(reportPath), { recursive: true });
439
+ writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
440
+ }
441
+ if (flags.json === true)
442
+ console.log(JSON.stringify(report, null, 2));
443
+ else {
444
+ console.log(formatGateSummary(report));
445
+ if (reportPath)
446
+ console.log(` report: ${reportPath}`);
447
+ }
448
+ return gateExitCode(report);
449
+ }
370
450
  function formatFinding(finding) {
371
451
  const where = finding.job ? `${finding.workflow}#${finding.job}` : finding.workflow;
372
452
  return ` [${finding.severity}] ${finding.code} (${where})\n ${finding.message}`;
@@ -945,6 +1025,10 @@ Usage:
945
1025
  [--cache-prepare <command>] [--fixed-order]
946
1026
  diffci validate-specs --file <json> [--json]
947
1027
  diffci verify-workflow [--repo <path>]
1028
+ diffci gate [--base <sha> --head <sha>] [--tests <command>] [--script <name,...>] [--measure-selected]
1029
+ [--only checks|tests] [--plan <file> [--expect-head <sha>]] [--repo <path>] [--out <file>]
1030
+ [--json] [--timeout-ms <ms>]
1031
+ diffci gate --plan-out <file> [--base <sha> --head <sha>] [--script <name,...>] [--repo <path>]
948
1032
  diffci enforce-misses --junit <file> --out-dir <dir> [--repository <owner/name>] [--repo <path>]
949
1033
  [--head <sha>] [--rerun-junit <file>] [--open-issue]
950
1034
  diffci version
@@ -971,6 +1055,15 @@ observe analyses the checkout and writes one JSON report. It runs nothing and ch
971
1055
  verify-savings runs both commands and reports measured paired runtime; it is an opt-in pilot command.
972
1056
  validate-specs checks an explicit list of specification IDs and logical targets and blocks duplicates.
973
1057
  verify-workflow checks that the job running DiffCI cannot affect any other job, and exits 1 if it can.
1058
+ gate replaces a build's gate script (for example "npm run check && npm test"). In observe mode, the only
1059
+ mode so far, it runs every gate check and the full test command (--tests, default the repository's test
1060
+ script) exactly as the build would and exits with their result. It records what DiffCI would have run,
1061
+ narrowed or skipped for the range, the time that would have saved, and any miss: a failing step DiffCI
1062
+ would have skipped. Narrowed checks and selected tests run again only when their full step failed, unless
1063
+ --measure-selected. --script adds gate scripts beyond check (comma-separated). --only checks or --only tests
1064
+ runs one half, for builds that run checks and tests as separate stages. --plan-out only analyses the range
1065
+ and writes DiffCI's decisions, for a gate that runs without git history; --plan uses that file instead of
1066
+ analysing, and --expect-head ignores a plan made for another commit. It sends nothing.
974
1067
  enforce-misses classifies a full run's failures on main against the enforce dry-run receipts of the pull
975
1068
  requests merged since the last recorded run, and exits 1 on a miss. It never edits configuration.
976
1069
  Failures are re-run with the package.json tsx --test runner, or read from --rerun-junit for other runners.
@@ -1041,6 +1134,9 @@ async function main() {
1041
1134
  case "verify-workflow":
1042
1135
  process.exitCode = runVerifyWorkflow(flags, env);
1043
1136
  return;
1137
+ case "gate":
1138
+ process.exitCode = await runGateCommand(flags, env);
1139
+ return;
1044
1140
  case "enforce-misses":
1045
1141
  process.exitCode = runEnforceMisses(flags, env);
1046
1142
  return;
@@ -55,9 +55,10 @@ function readRepositoryFile(repoPath, path) {
55
55
  * Agents ran the tests DiffCI selected and then failed `npm run check` after push; these are the rest of
56
56
  * the gate. With a change, per-file lint and format checks are narrowed to its files or skipped
57
57
  * (check-narrowing.ts); if the change cannot be read, every check runs. No package.json, or one that
58
- * cannot be read, has none.
58
+ * cannot be read, has none. `extraRoots` replaces the scripts CI workflows add to the gate, for a caller
59
+ * that knows exactly which scripts its build runs (`diffci gate --script`).
59
60
  */
60
- export function plannedChecks(repoPath, change) {
61
+ export function plannedChecks(repoPath, change, options = {}) {
61
62
  const path = join(repoPath, "package.json");
62
63
  if (!existsSync(path))
63
64
  return [];
@@ -73,7 +74,8 @@ export function plannedChecks(repoPath, change) {
73
74
  const scripts = Object.fromEntries(Object.entries(pkg.scripts).filter((entry) => typeof entry[1] === "string"));
74
75
  const manager = packageManager(repoPath, pkg.packageManager);
75
76
  const lifecycleHooks = manager !== "pnpm";
76
- let { checks } = discoverGateChecks(scripts, { lifecycleHooks, workflowScripts: workflowGateScripts(workflowTexts(repoPath), scripts) });
77
+ const workflowScripts = options.extraRoots ?? workflowGateScripts(workflowTexts(repoPath), scripts);
78
+ let { checks } = discoverGateChecks(scripts, { lifecycleHooks, workflowScripts });
77
79
  if (change) {
78
80
  try {
79
81
  const changes = changedPaths(repoPath, change);
@@ -0,0 +1,221 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { inferFullCommand } from "./full-command.js";
5
+ import { plannedChecks } from "./gate-checks.js";
6
+ import { observe } from "./observe.js";
7
+ import { executableSelection } from "./verify.js";
8
+ import { measureCommand } from "./verify-savings.js";
9
+ /**
10
+ * `diffci gate` in observe mode (2026-10-30, docs/design/pipeline-impact.md, phase 2).
11
+ *
12
+ * WHY. Builds that run a script instead of workflow jobs (DentalPresence's Cloudflare Sandbox build runs
13
+ * `npm run check` and its whole test suite on every staging build, about 19 of 44 build-hours) cannot use
14
+ * per-job `if:` conditions. `diffci gate` replaces that script. Before anything is skipped in a build, the
15
+ * miss rate has to be measured on real builds, so this mode changes nothing about what runs.
16
+ *
17
+ * WHAT IT DOES. Runs every leaf of the gate and the full test command, exactly as the build would, and
18
+ * exits with their result. Alongside, it records what DiffCI would have done for the same commit range:
19
+ * each check's RUN/NARROWED/SKIP decision and the test selection. A miss is a step DiffCI would have
20
+ * skipped or narrowed that failed in full while DiffCI's version passed; those are only rerun when the full
21
+ * step failed, so a passing build pays for nothing but the analysis. `--measure-selected` also runs the
22
+ * narrowed checks and selected tests on passing builds, to measure rather than estimate the saving.
23
+ *
24
+ * DiffCI never decides the build's outcome here: an analysis that fails still runs and reports the full gate.
25
+ */
26
+ export const GATE_SCHEMA = "diffci.gate.v1";
27
+ function stepRun(measurement) {
28
+ const status = measurement.timedOut ? "timed_out" : measurement.exitCode === 0 && measurement.signal === null ? "passed" : "failed";
29
+ return { status, wall_ms: measurement.wallMs, exit_code: measurement.exitCode };
30
+ }
31
+ export const GATE_PLAN_SCHEMA = "diffci.gate-plan.v1";
32
+ export async function planGate(options) {
33
+ const repoPath = resolve(options.repoPath);
34
+ const temporary = mkdtempSync(join(tmpdir(), "diffci-gate-"));
35
+ let observation;
36
+ let analysisError;
37
+ try {
38
+ observation = await (options.analyse ?? observe)({
39
+ repoPath, env: options.env, version: options.version, engineSha: options.engineSha,
40
+ baseOverride: options.baseOverride, headOverride: options.headOverride,
41
+ reportPath: join(temporary, "observation.json"), selectTestPhases: true,
42
+ });
43
+ }
44
+ catch (error) {
45
+ analysisError = error instanceof Error ? error.message : String(error);
46
+ }
47
+ finally {
48
+ rmSync(temporary, { recursive: true, force: true });
49
+ }
50
+ const range = observation?.commitRange;
51
+ const result = observation?.status === "OBSERVED" ? observation.result : undefined;
52
+ const unanalysed = analysisError ?? observation?.reason ?? "the change could not be analysed";
53
+ const checks = range ? plannedChecks(repoPath, { baseSha: range.baseSha, headSha: range.headSha }, { extraRoots: options.scripts ?? [] }) : [];
54
+ const selected = result ? executableSelection(repoPath, result) : undefined;
55
+ const selection = !selected || !selected.command ? "unavailable" : selected.selection;
56
+ return {
57
+ schema: GATE_PLAN_SCHEMA,
58
+ diffci_version: options.version,
59
+ ...(range ? { range: { base_sha: range.baseSha, head_sha: range.headSha, source: range.source } } : {}),
60
+ analysis: {
61
+ status: analysisError ? "ERROR" : observation?.status ?? "ERROR",
62
+ ...(analysisError ?? observation?.reason ? { reason: unanalysed } : {}),
63
+ ...(result?.mode ? { mode: result.mode } : {}),
64
+ fallback_reasons: result?.fallbackReasons ?? [],
65
+ ...(observation?.timings?.totalMs !== undefined ? { duration_ms: observation.timings.totalMs } : {}),
66
+ },
67
+ checks,
68
+ tests: {
69
+ selection,
70
+ reason: selected?.reason ?? unanalysed,
71
+ tests_selected: selection === "selected" ? result?.selectedTests.length ?? 0 : result?.totalTestCount ?? 0,
72
+ tests_available: result?.totalTestCount ?? 0,
73
+ ...(selection === "selected" ? { selected_commands: selected.commands } : {}),
74
+ },
75
+ };
76
+ }
77
+ /** A plan that is not this version's, or not for the commit being gated, is not used. */
78
+ function usablePlan(plan, expectHead) {
79
+ const candidate = plan;
80
+ if (!candidate || candidate.schema !== GATE_PLAN_SCHEMA || !Array.isArray(candidate.checks) || !candidate.tests || !candidate.analysis) {
81
+ return { reason: "the gate plan is missing or not a diffci.gate-plan.v1 document" };
82
+ }
83
+ if (expectHead && candidate.range?.head_sha !== expectHead) {
84
+ return { reason: `the gate plan is for ${candidate.range?.head_sha ?? "no commit"}, not ${expectHead}` };
85
+ }
86
+ return { plan: candidate };
87
+ }
88
+ export async function runGate(options) {
89
+ const repoPath = resolve(options.repoPath);
90
+ const run = options.run ?? measureCommand;
91
+ const started = Date.now();
92
+ const remaining = () => Math.max(options.timeoutMs - (Date.now() - started), 0);
93
+ const execute = (command) => run(command, { cwd: repoPath, timeoutMs: remaining(), tailBytes: options.tailBytes });
94
+ // 1. What DiffCI would do: a plan made elsewhere, or an analysis here. Never fatal: the full gate runs
95
+ // whatever happens here.
96
+ const supplied = options.plan !== undefined ? usablePlan(options.plan, options.expectHead) : undefined;
97
+ const plan = supplied ? supplied.plan : await planGate(options);
98
+ const analysis = plan?.analysis ?? { status: "PLAN_UNUSABLE", reason: supplied?.reason, fallback_reasons: [] };
99
+ const unplanned = analysis.reason ?? "the change could not be analysed";
100
+ const analysisMs = supplied?.plan ? 0 : plan?.analysis.duration_ms ?? 0;
101
+ const runChecks = options.only !== "tests";
102
+ const full = runChecks ? plannedChecks(repoPath, undefined, { extraRoots: options.scripts ?? [] }) : [];
103
+ const decisionOf = new Map((plan?.checks ?? []).map((check) => [check.id, check]));
104
+ // 2. The full gate, every leaf, continuing past failures so each one is attributed.
105
+ const checks = full.map((check) => {
106
+ const decided = decisionOf.get(check.id);
107
+ const measured = stepRun(execute(check.command));
108
+ return {
109
+ id: check.id, kind: check.kind,
110
+ decision: decided?.decision ?? "UNPLANNED",
111
+ reason: decided?.reason ?? unplanned,
112
+ command: check.command,
113
+ ...(decided?.decision === "NARROWED" ? { narrowed_command: decided.command } : {}),
114
+ full: measured,
115
+ };
116
+ });
117
+ const testCommand = options.only === "checks" ? undefined : options.tests ?? inferFullCommand(repoPath).command;
118
+ let tests;
119
+ if (testCommand) {
120
+ const measurement = execute(testCommand);
121
+ const fullRun = { ...stepRun(measurement), ...(measurement.failingTests?.length ? { failing_tests: measurement.failingTests } : {}) };
122
+ tests = {
123
+ command: testCommand, full: fullRun,
124
+ selection: plan?.tests.selection ?? "unavailable",
125
+ reason: plan?.tests.reason ?? unplanned,
126
+ tests_selected: plan?.tests.tests_selected ?? 0,
127
+ tests_available: plan?.tests.tests_available ?? 0,
128
+ ...(plan?.tests.selected_commands ? { selected_commands: plan.tests.selected_commands } : {}),
129
+ };
130
+ }
131
+ // 3. Misses, and optional timing of DiffCI's own versions of the steps. Reruns happen only on failure
132
+ // unless --measure-selected asks for timings on a passing build.
133
+ for (const check of checks) {
134
+ if (check.full.status === "passed" && !options.measureSelected)
135
+ continue;
136
+ if (check.decision === "SKIP") {
137
+ check.missed = check.full.status !== "passed";
138
+ continue;
139
+ }
140
+ if (check.decision !== "NARROWED" || !check.narrowed_command)
141
+ continue;
142
+ check.narrowed = stepRun(execute(check.narrowed_command));
143
+ if (check.full.status !== "passed")
144
+ check.missed = check.narrowed.status === "passed";
145
+ }
146
+ if (tests?.selected_commands && (tests.full.status !== "passed" || options.measureSelected)) {
147
+ const runs = tests.selected_commands.map((command) => execute(command));
148
+ const failed = runs.find((measurement) => stepRun(measurement).status !== "passed");
149
+ tests.selected = { ...stepRun(failed ?? runs[runs.length - 1]), wall_ms: runs.reduce((sum, measurement) => sum + measurement.wallMs, 0) };
150
+ if (tests.full.status !== "passed")
151
+ tests.missed = tests.selected.status === "passed";
152
+ }
153
+ // 4. Summary. The build's result is the full gate's, never DiffCI's.
154
+ const failedSteps = [...checks.filter((check) => check.full.status !== "passed").map((check) => check.id), ...(tests && tests.full.status !== "passed" ? ["tests"] : [])];
155
+ const fullMs = checks.reduce((sum, check) => sum + (check.full.wall_ms ?? 0), 0) + (tests?.full.wall_ms ?? 0);
156
+ let estimated = false;
157
+ let diffciMs = analysisMs;
158
+ for (const check of checks) {
159
+ if (check.decision === "SKIP")
160
+ continue;
161
+ if (check.decision === "NARROWED" && check.narrowed?.wall_ms !== undefined)
162
+ diffciMs += check.narrowed.wall_ms;
163
+ else {
164
+ if (check.decision === "NARROWED")
165
+ estimated = true;
166
+ diffciMs += check.full.wall_ms ?? 0;
167
+ }
168
+ }
169
+ if (tests) {
170
+ if (tests.selection !== "selected")
171
+ diffciMs += tests.full.wall_ms ?? 0;
172
+ else if (tests.selected?.wall_ms !== undefined)
173
+ diffciMs += tests.selected.wall_ms;
174
+ else {
175
+ estimated = true;
176
+ diffciMs += Math.round((tests.full.wall_ms ?? 0) * (tests.tests_available ? tests.tests_selected / tests.tests_available : 1));
177
+ }
178
+ }
179
+ const misses = [...checks.filter((check) => check.missed).map((check) => check.id), ...(tests?.missed ? ["tests"] : [])];
180
+ return {
181
+ schema: GATE_SCHEMA, schema_version: "1", produced_at: new Date().toISOString(), diffci_version: options.version, mode: "observe",
182
+ ...(options.only ? { only: options.only } : {}),
183
+ ...(plan?.range ? { range: plan.range } : {}),
184
+ ...(supplied ? { plan: supplied.plan ? "supplied" : "unusable" } : {}),
185
+ analysis,
186
+ gate: {
187
+ status: failedSteps.length ? "failed" : "passed",
188
+ wall_ms: Date.now() - started,
189
+ reason: failedSteps.length ? `failed: ${failedSteps.join(", ")}`
190
+ : options.only === "checks" ? "every gate check passed"
191
+ : options.only === "tests" ? (testCommand ? "the tests passed" : "no test command was found")
192
+ : testCommand ? "every gate step passed" : "every gate check passed; no test command was found",
193
+ },
194
+ checks,
195
+ ...(tests ? { tests } : {}),
196
+ summary: { full_ms: fullMs, diffci_ms: diffciMs, saved_ms: fullMs - diffciMs, basis: estimated ? "estimated" : "measured", misses },
197
+ };
198
+ }
199
+ export function gateExitCode(report) {
200
+ return report.gate.status === "passed" ? 0 : 1;
201
+ }
202
+ const seconds = (ms) => `${(ms / 1000).toFixed(1)}s`;
203
+ export function formatGateSummary(report) {
204
+ const lines = [
205
+ `DiffCI gate (observe): ${report.gate.status.toUpperCase()} - ${report.gate.reason}`,
206
+ ...(report.range ? [` range: ${report.range.base_sha.slice(0, 12)}..${report.range.head_sha.slice(0, 12)}`] : []),
207
+ ` analysis: ${report.analysis.status}${report.analysis.mode ? ` (${report.analysis.mode})` : ""}${report.analysis.reason ? ` - ${report.analysis.reason}` : ""}`,
208
+ ];
209
+ for (const check of report.checks) {
210
+ lines.push(` ${check.full.status === "passed" ? "ok " : "FAIL"} ${check.id} ${seconds(check.full.wall_ms ?? 0)} - DiffCI: ${check.decision}${check.missed ? " (MISSED)" : ""}`);
211
+ }
212
+ if (report.tests) {
213
+ const t = report.tests;
214
+ const scope = t.selection === "selected" ? `${t.tests_selected}/${t.tests_available} test files` : t.selection;
215
+ lines.push(` ${t.full.status === "passed" ? "ok " : "FAIL"} tests ${seconds(t.full.wall_ms ?? 0)} - DiffCI: ${scope}${t.missed ? " (MISSED)" : ""}`);
216
+ }
217
+ const s = report.summary;
218
+ lines.push(` full gate ${seconds(s.full_ms)}, DiffCI ${seconds(s.diffci_ms)} (${s.basis}), would save ${seconds(s.saved_ms)}`);
219
+ lines.push(s.misses.length ? ` MISSES: ${s.misses.join(", ")}` : " misses: none");
220
+ return lines.join("\n");
221
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diffci.com/diffci",
3
- "version": "0.3.20",
3
+ "version": "0.3.21",
4
4
  "description": "Fail-closed, change-aware verification for AI coding agents with conservative affected-test selection",
5
5
  "keywords": [
6
6
  "ci",