@diffci.com/diffci 0.2.13 → 0.3.1

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.
package/README.md CHANGED
@@ -6,25 +6,30 @@
6
6
  [![npm version](https://img.shields.io/npm/v/@diffci.com/diffci.svg)](https://www.npmjs.com/package/@diffci.com/diffci)
7
7
  [![npm provenance](https://img.shields.io/badge/npm-provenance-blue)](https://docs.npmjs.com/generating-provenance-statements)
8
8
  [![MCP server](https://img.shields.io/badge/MCP-server-5f6fff)](https://diffci.com/mcp-server)
9
- [![Agent safe](https://img.shields.io/badge/agent--safe-observation--only-0f766e)](docs/ai-agents.md)
9
+ [![Agent verification](https://img.shields.io/badge/agent--verification-fail--closed-0f766e)](docs/ai-agents.md)
10
10
  [![GitHub Marketplace](https://img.shields.io/badge/GitHub-Marketplace-blue)](https://github.com/marketplace/actions/diffci-observer)
11
11
 
12
- **Find test-selection opportunities in your CI before changing what it runs.** DiffCI analyzes a
13
- commit's changes and dependency graph, then reports which test files it would select, why it falls
14
- back to a full run, and whether it can propose a test command. `check` also runs paired full and
15
- selected commands when it can infer them. The `observe` command and Action remain observation-only.
12
+ **The verification layer between AI-generated code and shipping.** DiffCI snapshots an agent's staged,
13
+ unstaged, and non-ignored untracked changes, determines the minimum executable test verification, and
14
+ runs it. Uncertainty broadens to full verification; a failed, incomplete, or changed snapshot blocks.
15
+ The `check` command remains the paired-runtime evaluation surface. `observe` and the Marketplace Action
16
+ remain observation-only; DiffCI also generates a separate blocking verification workflow.
16
17
 
17
18
  ## Try DiffCI
18
19
 
19
20
  From a Git repository checkout, with Node.js 22.5+ and Git installed, run:
20
21
 
21
22
  ```bash
22
- npx "@diffci.com/diffci@latest" check
23
+ npx "@diffci.com/diffci@latest" verify --changed --json
23
24
  ```
24
25
 
25
- `check` explains affected tests and, when it can infer safe commands, runs both the full and selected
26
- test commands to measure the difference. It sends nothing to DiffCI. Test commands can create files
27
- in the checkout. For analysis without test execution, use `npx "@diffci.com/diffci@latest" observe --no-send`.
26
+ `verify --changed` covers staged, unstaged, and non-ignored untracked content. It runs the selected
27
+ command when DiffCI can prove one, otherwise the inferred full test command. Exit zero means that exact
28
+ content-addressed snapshot passed and remained unchanged while tests ran. The JSON receipt includes
29
+ `verification`, `safe_to_continue`, selection counts, the command result, and tree identities.
30
+
31
+ For paired full-versus-selected runtime measurement, use `check`. For analysis without test execution,
32
+ use `npx "@diffci.com/diffci@latest" observe --no-send`.
28
33
 
29
34
  To add instructions for coding agents, run:
30
35
 
@@ -33,20 +38,26 @@ npx "@diffci.com/diffci@latest" init
33
38
  ```
34
39
 
35
40
  To also pin DiffCI as a development dependency and update the detected npm, pnpm, Yarn, or Bun
36
- lockfile, pass `--install`. Add `--workflow` for a separate non-blocking observation job:
41
+ lockfile, pass `--install`. Add `--workflow` for a non-blocking observation job and
42
+ `--verification-workflow` for a blocking commit-range gate:
37
43
 
38
44
  ```bash
39
- npx "@diffci.com/diffci@latest" init --install --workflow
45
+ npx "@diffci.com/diffci@latest" init --install --workflow --verification-workflow
40
46
  ```
41
47
 
42
- `--install` also adds `diffci:check` and `diffci:observe` package scripts. It preserves same-named
48
+ `--install` also adds `diffci:verify`, `diffci:check`, and `diffci:observe` package scripts. It preserves same-named
43
49
  scripts that the project already owns. After installation, CI or contributors can run
44
- `npm run diffci:check` or `npm run diffci:observe` without knowing the package name or version.
50
+ `npm run diffci:verify`, `npm run diffci:check`, or `npm run diffci:observe` without knowing the package name or version.
51
+ Generated agent rules use the detected package manager's local script when DiffCI is installed.
52
+
53
+ In CI, `diffci verify --json` resolves the pull-request or push range automatically. It requires a
54
+ clean checkout, refuses when the analyzed head differs from executed `HEAD`, and binds the receipt to
55
+ both the resolved range and checkout tree. Use `--base` and `--head` for an explicit range.
45
56
 
46
57
  On Windows PowerShell, quote the package name:
47
58
 
48
59
  ```powershell
49
- npx "@diffci.com/diffci@latest" check
60
+ npx "@diffci.com/diffci@latest" verify --changed --json
50
61
  ```
51
62
 
52
63
  The [copyable adoption kit](docs/agent-adoption-kit.md) includes an `AGENTS.md` instruction and
@@ -127,6 +138,20 @@ npx "@diffci.com/diffci@latest" validate-specs --file change-specifications.json
127
138
  The command exits non-zero and names every conflicting specification ID. This surface is opt-in and
128
139
  does not infer semantic targets from source code; callers must provide stable logical target names.
129
140
 
141
+ ## Block in GitHub Actions
142
+
143
+ Generate a dedicated verification check with:
144
+
145
+ ```bash
146
+ npx "@diffci.com/diffci@latest" init --verification-workflow
147
+ ```
148
+
149
+ The generated `.github/workflows/diffci-verify.yml` checks out the exact pull-request head with full
150
+ history, runs `diffci verify --json`, and uploads the commit-bound receipt even when verification
151
+ fails. It has no `continue-on-error`: configure its **DiffCI verification** job as a required check
152
+ after a successful pilot. A zero exit means the selected verification (or conservative full fallback)
153
+ passed for the exact analyzed commit and checkout tree.
154
+
130
155
  ## Observe in GitHub Actions
131
156
 
132
157
  Save this as `.github/workflows/diffci.yml` to add a dedicated, non-blocking observation job:
@@ -144,13 +169,13 @@ jobs:
144
169
  - uses: actions/checkout@v4
145
170
  with:
146
171
  fetch-depth: 0
147
- - uses: DiffCI/DiffCI.com@2f72b7fc017cc987fb0fd80c7e2351f33240e7d4
172
+ - uses: DiffCI/DiffCI.com@edac0ad48ae4bbdcf7e7839cf0bb371201a46872
148
173
  ```
149
174
 
150
175
  Then check the workflow locally with `npx "@diffci.com/diffci@latest" verify-workflow`. Keep the observer
151
176
  out of required checks and other jobs' `needs` lists. The Action adds a job summary and a
152
177
  `diffci-observation` artifact to the run; it does not alter which tests your other jobs execute.
153
- The example pins release `v0.2.13` to its qualified feature commit SHA for reproducibility.
178
+ The example pins release `v0.3.1` to its qualified feature commit SHA for reproducibility.
154
179
 
155
180
  The CLI sends no report with `--no-send`. The Action uploads a GitHub artifact by default; sending to
156
181
  DiffCI's hosted service requires an explicitly configured endpoint and token.
@@ -181,7 +206,7 @@ npx "@diffci.com/diffci@latest" init
181
206
  Then ask your coding agent to run:
182
207
 
183
208
  ```bash
184
- npx "@diffci.com/diffci@latest" check
209
+ npx "@diffci.com/diffci@latest" verify --changed --json
185
210
  ```
186
211
 
187
212
  Agent-specific docs:
@@ -353,7 +378,7 @@ npm run research:sandbox:deploy
353
378
  DiffCI is intended to be installable as infrastructure, not only as a hosted shadow experiment:
354
379
 
355
380
  ```yaml
356
- - uses: DiffCI/DiffCI.com@2f72b7fc017cc987fb0fd80c7e2351f33240e7d4
381
+ - uses: DiffCI/DiffCI.com@edac0ad48ae4bbdcf7e7839cf0bb371201a46872
357
382
  ```
358
383
 
359
384
  ```bash
@@ -11,6 +11,7 @@
11
11
  * Commands:
12
12
  * init seed a repository with AI-agent instructions for using DiffCI
13
13
  * mcp run the stdio MCP server
14
+ * verify fail-closed verification of a working-tree snapshot or commit range
14
15
  * check analysis plus automatic paired runtime measurement
15
16
  * observe analyse the checkout and write an observation report
16
17
  * verify-savings run a paired full-versus-selected timing check
@@ -31,11 +32,12 @@ import { tmpdir } from "node:os";
31
32
  import { basename, dirname, join, resolve } from "node:path";
32
33
  import { observe, isInsideRepository } from "./observe.js";
33
34
  import { inferFullCommand, inferSelectedCommand } from "./full-command.js";
34
- import { addDiffciPackageScripts, installDiffci } from "./install.js";
35
+ import { addDiffciPackageScripts, detectPackageManager, installDiffci } from "./install.js";
35
36
  import { submitObservation } from "./submit.js";
36
37
  import { githubDeliveryWarning } from "./delivery-warning.js";
37
38
  import { sendUsageSignal } from "./usage-signal.js";
38
39
  import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conflicts.js";
40
+ import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
39
41
  import { formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
40
42
  import { auditWorkflows, isNonInterfering } from "./workflow-guard.js";
41
43
  function parseArgs(argv) {
@@ -106,31 +108,33 @@ function defaultReportPath(env) {
106
108
  }
107
109
  // Quoting the scoped package keeps the same command valid in POSIX shells, cmd.exe, and
108
110
  // PowerShell, where an unquoted leading `@` is parsed as the splatting operator.
109
- const AGENT_DEFAULT_COMMAND = 'npx "@diffci.com/diffci@latest" check';
110
- const AGENT_INSTRUCTIONS = `# DiffCI Agent Instructions
111
+ const PUBLIC_AGENT_DEFAULT_COMMAND = 'npx "@diffci.com/diffci@latest" verify --changed --json';
112
+ function agentInstructions(command) {
113
+ return `# DiffCI Agent Instructions
111
114
 
112
115
  Use DiffCI as the default CI/CD validation lens before proposing, committing, or opening pull requests.
113
116
 
114
117
  Default command:
115
118
 
116
119
  \`\`\`bash
117
- ${AGENT_DEFAULT_COMMAND}
120
+ ${command}
118
121
  \`\`\`
119
122
 
120
123
  What this does:
121
124
 
122
- - analyzes the current checkout and commit range;
123
- - runs the repository's inferred full test command and DiffCI's selected command when safe to compare;
124
- - prints measured paired runtime when both commands pass;
125
- - writes reports outside the repository and sends nothing;
126
- - does not skip, cancel, or reorder required CI tests.
125
+ - snapshots staged, unstaged, and non-ignored untracked changes;
126
+ - selects and runs the minimum executable test verification, broadening to the full test command when uncertain;
127
+ - exits zero only when the exact snapshot passes and remains unchanged during verification;
128
+ - emits a versioned machine-readable receipt and sends nothing.
127
129
 
128
- Test commands may write generated files to the checkout. Use \`observe --no-send\` when analysis
129
- without test execution is needed.
130
+ If verification changes generated files, review those changes and rerun DiffCI so the new snapshot is verified.
131
+ Use \`observe --no-send\` when analysis without test execution is needed.
130
132
 
131
- If DiffCI reports \`REFUSED\` or \`ERROR\`, treat that as an installation or analysis issue and continue with the repository's normal test commands. If DiffCI reports a selected command, prefer using it as evidence for what changed, not as permission to skip required CI.
133
+ Do not propose, commit, push, or deploy when \`safe_to_continue\` is false. If DiffCI is blocked, run the repository's normal required verification and report the blocker; required project CI remains authoritative.
132
134
  `;
133
- const CURSOR_RULE = `---
135
+ }
136
+ function cursorRule(command) {
137
+ return `---
134
138
  description: Use DiffCI as the default CI/CD validation lens
135
139
  alwaysApply: true
136
140
  ---
@@ -138,28 +142,38 @@ alwaysApply: true
138
142
  Before proposing, committing, or opening pull requests, run:
139
143
 
140
144
  \`\`\`bash
141
- ${AGENT_DEFAULT_COMMAND}
145
+ ${command}
142
146
  \`\`\`
143
147
 
144
- DiffCI check analyzes the change and runs full and selected test commands when it can infer them. It sends nothing. Test commands may write generated files. Use observe --no-send for analysis without execution. Required project CI remains authoritative.
148
+ DiffCI verify snapshots staged, unstaged, and untracked changes, runs selected or conservative full-fallback verification, and succeeds only when the exact snapshot passes. It sends nothing. If verification changes generated files, review them and rerun. Required project CI remains authoritative.
145
149
  `;
146
- const GITHUB_COPILOT_INSTRUCTIONS = `# Repository CI/CD Validation
150
+ }
151
+ function githubCopilotInstructions(command) {
152
+ return `# Repository CI/CD Validation
147
153
 
148
154
  Use DiffCI as the default change-aware CI/CD validation lens:
149
155
 
150
156
  \`\`\`bash
151
- ${AGENT_DEFAULT_COMMAND}
157
+ ${command}
152
158
  \`\`\`
153
159
 
154
- DiffCI check analyzes the change and runs inferred full and selected test commands to measure a paired runtime. It sends nothing; required repository checks remain authoritative.
160
+ DiffCI verify binds selected or conservative full-fallback verification to the current working-tree snapshot. Do not continue when safe_to_continue is false. It sends nothing; required repository checks remain authoritative.
155
161
  `;
156
- const DIFFCI_CONFIG = `{
162
+ }
163
+ function diffciConfig(command) {
164
+ return `{
157
165
  "$schema": "https://diffci.com/schemas/diffci.config.schema.json",
158
- "agentDefaultCommand": ${JSON.stringify(AGENT_DEFAULT_COMMAND)},
159
- "mode": "check",
166
+ "agentDefaultCommand": ${JSON.stringify(command)},
167
+ "mode": "verify-changed",
160
168
  "sendReports": false
161
169
  }
162
170
  `;
171
+ }
172
+ const MANAGED_INSTRUCTIONS_BEGIN = "<!-- diffci:managed:start -->";
173
+ const MANAGED_INSTRUCTIONS_END = "<!-- diffci:managed:end -->";
174
+ function managedInstructions(content) {
175
+ return `${MANAGED_INSTRUCTIONS_BEGIN}\n${content.trim()}\n${MANAGED_INSTRUCTIONS_END}\n`;
176
+ }
163
177
  function diffciWorkflow(version) {
164
178
  return `name: DiffCI observation
165
179
  on: [push, pull_request]
@@ -179,6 +193,34 @@ jobs:
179
193
  - run: npx "@diffci.com/diffci@${version}" observe --no-send
180
194
  `;
181
195
  }
196
+ function diffciVerificationWorkflow(version) {
197
+ return `name: DiffCI verification
198
+ on: [push, pull_request]
199
+ permissions:
200
+ contents: read
201
+ jobs:
202
+ diffci-verify:
203
+ name: DiffCI verification
204
+ runs-on: ubuntu-latest
205
+ steps:
206
+ - uses: actions/checkout@v4
207
+ with:
208
+ fetch-depth: 0
209
+ ref: \${{ github.event.pull_request.head.sha || github.sha }}
210
+ - uses: actions/setup-node@v4
211
+ with:
212
+ node-version: 22
213
+ - name: Verify changed code
214
+ run: npx "@diffci.com/diffci@${version}" verify --json --out "$RUNNER_TEMP/diffci-verification.json"
215
+ - name: Upload verification receipt
216
+ if: always()
217
+ uses: actions/upload-artifact@v4
218
+ with:
219
+ name: diffci-verification-\${{ github.run_id }}-\${{ github.run_attempt }}
220
+ path: \${{ runner.temp }}/diffci-verification.json
221
+ if-no-files-found: warn
222
+ `;
223
+ }
182
224
  function writeInitFile(repoPath, relativePath, content, force) {
183
225
  const absolutePath = join(repoPath, relativePath);
184
226
  const existed = existsSync(absolutePath);
@@ -188,21 +230,83 @@ function writeInitFile(repoPath, relativePath, content, force) {
188
230
  writeFileSync(absolutePath, content, "utf8");
189
231
  return `${existed ? "overwrote" : "wrote"} ${relativePath}`;
190
232
  }
233
+ function writeManagedInstructionsFile(repoPath, relativePath, content) {
234
+ const absolutePath = join(repoPath, relativePath);
235
+ const block = managedInstructions(content);
236
+ mkdirSync(dirname(absolutePath), { recursive: true });
237
+ if (!existsSync(absolutePath)) {
238
+ writeFileSync(absolutePath, block, "utf8");
239
+ return `wrote ${relativePath}`;
240
+ }
241
+ const existing = readFileSync(absolutePath, "utf8");
242
+ const start = existing.indexOf(MANAGED_INSTRUCTIONS_BEGIN);
243
+ const end = existing.indexOf(MANAGED_INSTRUCTIONS_END);
244
+ let next;
245
+ if (start >= 0 && end >= start) {
246
+ const after = end + MANAGED_INSTRUCTIONS_END.length;
247
+ next = `${existing.slice(0, start)}${block.trimEnd()}${existing.slice(after)}`;
248
+ if (existing.endsWith("\n") && !next.endsWith("\n"))
249
+ next += "\n";
250
+ }
251
+ else if (existing.trimStart().startsWith("# DiffCI Agent Instructions")) {
252
+ // Files generated by DiffCI before managed markers were introduced were dedicated DiffCI files.
253
+ next = block;
254
+ }
255
+ else {
256
+ next = `${existing.trimEnd()}\n\n${block}`;
257
+ }
258
+ if (next === existing)
259
+ return `kept ${relativePath} (managed section current)`;
260
+ writeFileSync(absolutePath, next, "utf8");
261
+ return `updated ${relativePath} (DiffCI managed section)`;
262
+ }
263
+ function writeDiffciConfig(repoPath, force, command) {
264
+ const relativePath = "diffci.config.json";
265
+ const absolutePath = join(repoPath, relativePath);
266
+ const generated = diffciConfig(command);
267
+ if (!existsSync(absolutePath))
268
+ return writeInitFile(repoPath, relativePath, generated, false);
269
+ try {
270
+ const existing = JSON.parse(readFileSync(absolutePath, "utf8"));
271
+ if (existing.$schema === "https://diffci.com/schemas/diffci.config.schema.json") {
272
+ existing.agentDefaultCommand = command;
273
+ existing.mode = "verify-changed";
274
+ if (existing.sendReports === undefined)
275
+ existing.sendReports = false;
276
+ const next = `${JSON.stringify(existing, null, 2)}\n`;
277
+ if (next === readFileSync(absolutePath, "utf8"))
278
+ return `kept ${relativePath} (current)`;
279
+ writeFileSync(absolutePath, next, "utf8");
280
+ return `updated ${relativePath}`;
281
+ }
282
+ }
283
+ catch {
284
+ // An unrelated or invalid existing file is preserved unless the caller explicitly asked to force.
285
+ }
286
+ return writeInitFile(repoPath, relativePath, generated, force);
287
+ }
288
+ function installedDiffciManager(repoPath) {
289
+ const packagePath = join(repoPath, "package.json");
290
+ if (!existsSync(packagePath))
291
+ return undefined;
292
+ try {
293
+ const manifest = JSON.parse(readFileSync(packagePath, "utf8"));
294
+ const installed = [manifest.dependencies, manifest.devDependencies, manifest.optionalDependencies]
295
+ .some((dependencies) => dependencies && typeof dependencies["@diffci.com/diffci"] === "string");
296
+ return installed ? detectPackageManager(repoPath) : undefined;
297
+ }
298
+ catch {
299
+ return undefined;
300
+ }
301
+ }
191
302
  function runInit(flags, env) {
192
303
  const repoPath = resolve(typeof flags.repo === "string" ? flags.repo : env.GITHUB_WORKSPACE ?? process.cwd());
193
304
  const force = flags.force === true;
194
305
  const includeWorkflow = flags.workflow === true;
306
+ const includeVerificationWorkflow = flags["verification-workflow"] === true;
195
307
  const identity = observerIdentity();
196
- const writes = [
197
- writeInitFile(repoPath, "AGENTS.md", AGENT_INSTRUCTIONS, force),
198
- writeInitFile(repoPath, "CLAUDE.md", AGENT_INSTRUCTIONS, force),
199
- writeInitFile(repoPath, ".cursor/rules/diffci.mdc", CURSOR_RULE, force),
200
- writeInitFile(repoPath, ".github/copilot-instructions.md", GITHUB_COPILOT_INSTRUCTIONS, force),
201
- writeInitFile(repoPath, "diffci.config.json", DIFFCI_CONFIG, force),
202
- ];
203
- if (includeWorkflow)
204
- writes.push(writeInitFile(repoPath, ".github/workflows/diffci.yml", diffciWorkflow(identity.version), force));
205
308
  let installed;
309
+ let manager = installedDiffciManager(repoPath);
206
310
  if (flags.install === true) {
207
311
  const { plan, result } = installDiffci(repoPath, identity.version);
208
312
  if (result.error)
@@ -212,12 +316,35 @@ function runInit(flags, env) {
212
316
  throw new Error(`could not install ${plan.packageSpec}: ${detail}`);
213
317
  }
214
318
  const scripts = addDiffciPackageScripts(repoPath);
319
+ manager = plan.manager;
215
320
  installed = `installed ${plan.packageSpec} as an exact dev dependency with ${plan.manager}`;
216
321
  if (scripts.added.length > 0)
217
322
  installed += `; added package scripts ${scripts.added.join(", ")}`;
218
323
  if (scripts.kept.length > 0)
219
324
  installed += `; kept existing package scripts ${scripts.kept.join(", ")}`;
220
325
  }
326
+ else if (manager) {
327
+ const scripts = addDiffciPackageScripts(repoPath);
328
+ installed = `found the existing exact or ranged @diffci.com/diffci dependency with ${manager}`;
329
+ if (scripts.added.length > 0)
330
+ installed += `; added package scripts ${scripts.added.join(", ")}`;
331
+ if (scripts.kept.length > 0)
332
+ installed += `; kept existing package scripts ${scripts.kept.join(", ")}`;
333
+ }
334
+ const agentCommand = manager ? `${manager} run diffci:verify` : PUBLIC_AGENT_DEFAULT_COMMAND;
335
+ const instructions = agentInstructions(agentCommand);
336
+ const writes = [
337
+ writeManagedInstructionsFile(repoPath, "AGENTS.md", instructions),
338
+ writeManagedInstructionsFile(repoPath, "CLAUDE.md", instructions),
339
+ writeInitFile(repoPath, ".cursor/rules/diffci.mdc", cursorRule(agentCommand), force),
340
+ writeManagedInstructionsFile(repoPath, ".github/copilot-instructions.md", githubCopilotInstructions(agentCommand)),
341
+ writeDiffciConfig(repoPath, force, agentCommand),
342
+ ];
343
+ if (includeWorkflow)
344
+ writes.push(writeInitFile(repoPath, ".github/workflows/diffci.yml", diffciWorkflow(identity.version), force));
345
+ if (includeVerificationWorkflow) {
346
+ writes.push(writeInitFile(repoPath, ".github/workflows/diffci-verify.yml", diffciVerificationWorkflow(identity.version), force));
347
+ }
221
348
  console.log(`DiffCI initialized for AI coding agents in ${repoPath}`);
222
349
  for (const write of writes)
223
350
  console.log(` ${write}`);
@@ -227,7 +354,9 @@ function runInit(flags, env) {
227
354
  console.log(" skipped package installation (pass --install to add an exact dev dependency)");
228
355
  if (!includeWorkflow)
229
356
  console.log(" skipped .github/workflows/diffci.yml (pass --workflow to add it)");
230
- console.log(`\nDefault agent command: ${AGENT_DEFAULT_COMMAND}`);
357
+ if (!includeVerificationWorkflow)
358
+ console.log(" skipped .github/workflows/diffci-verify.yml (pass --verification-workflow to add it)");
359
+ console.log(`\nDefault agent command: ${agentCommand}`);
231
360
  return 0;
232
361
  }
233
362
  function runMcp() {
@@ -243,6 +372,49 @@ function runMcp() {
243
372
  throw result.error;
244
373
  return 0;
245
374
  }
375
+ async function runVerifyCommand(flags, env) {
376
+ const changed = flags.changed === true;
377
+ if (changed && (flags.base !== undefined || flags.head !== undefined)) {
378
+ console.error("diffci verify accepts either --changed or --base/--head, not both");
379
+ return 2;
380
+ }
381
+ const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
382
+ const out = stringFlag(flags, "out");
383
+ const reportPath = out ? resolve(out) : undefined;
384
+ if (reportPath && (reportPath === repoPath || isInsideRepository(repoPath, reportPath))) {
385
+ console.error(`Refusing to write the verification receipt inside the repository: ${reportPath}. Use --out with a path outside the checkout.`);
386
+ return 2;
387
+ }
388
+ const identity = observerIdentity();
389
+ const common = {
390
+ repoPath,
391
+ env: env,
392
+ version: identity.version,
393
+ engineSha: identity.sha,
394
+ timeoutMs: numberFlag(flags, "timeout-ms") ?? 30 * 60 * 1000,
395
+ tailBytes: numberFlag(flags, "tail-bytes") ?? 12_000,
396
+ redactPaths: flags["redact-paths"] === true,
397
+ };
398
+ const report = changed
399
+ ? await verifyChanged(common)
400
+ : await verifyRange({
401
+ ...common,
402
+ baseOverride: stringFlag(flags, "base"),
403
+ headOverride: stringFlag(flags, "head"),
404
+ });
405
+ if (reportPath) {
406
+ mkdirSync(dirname(reportPath), { recursive: true });
407
+ writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
408
+ }
409
+ if (flags.json === true)
410
+ console.log(JSON.stringify(report, null, 2));
411
+ else {
412
+ console.log(formatVerificationSummary(report));
413
+ if (reportPath)
414
+ console.log(` receipt: ${reportPath}`);
415
+ }
416
+ return verificationExitCode(report);
417
+ }
246
418
  function formatFinding(finding) {
247
419
  const where = finding.job ? `${finding.workflow}#${finding.job}` : finding.workflow;
248
420
  return ` [${finding.severity}] ${finding.code} (${where})\n ${finding.message}`;
@@ -661,8 +833,10 @@ function runValidateSpecs(flags) {
661
833
  const USAGE = `diffci - change-aware CI analysis and paired timing
662
834
 
663
835
  Usage:
664
- diffci init [--repo <path>] [--workflow] [--install] [--force]
836
+ diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--force]
665
837
  diffci mcp
838
+ diffci verify [--changed | --base <sha> --head <sha>] [--repo <path>] [--out <file>] [--json]
839
+ [--redact-paths] [--timeout-ms <ms>]
666
840
  diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
667
841
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
668
842
  diffci pilot --full <command> [--repo <path>] [--out-dir <dir>] [--label <name>]
@@ -681,8 +855,13 @@ Usage:
681
855
  init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json.
682
856
  --workflow adds a separate non-blocking observation workflow. --install detects npm, pnpm, Yarn,
683
857
  or Bun, installs this DiffCI version as an exact dev dependency, updates the manager's lockfile,
684
- and adds diffci:check and diffci:observe package scripts without replacing existing scripts.
858
+ and adds diffci:verify, diffci:check, and diffci:observe package scripts without replacing existing scripts.
859
+ --verification-workflow adds a blocking GitHub check that uploads a commit-bound verification receipt.
685
860
  mcp runs the stdio MCP server for native agent integrations.
861
+ verify --changed snapshots staged, unstaged, and non-ignored untracked changes, runs the minimum
862
+ executable verification (or full fallback), and exits zero only when that exact snapshot passes.
863
+ verify without --changed resolves the CI event range (or HEAD^..HEAD locally), requires a clean checkout,
864
+ and exits zero only when the analyzed head is the commit that actually passed verification.
686
865
  check analyzes the change, runs inferred full and selected commands, and shows measured savings.
687
866
  pilot runs observe and verify-savings together, writing reports to ../diffci-output by default.
688
867
  observe analyses the checkout and writes one JSON report. It runs nothing and changes nothing.
@@ -711,6 +890,9 @@ async function main() {
711
890
  case "mcp":
712
891
  process.exitCode = runMcp();
713
892
  return;
893
+ case "verify":
894
+ process.exitCode = await runVerifyCommand(flags, env);
895
+ return;
714
896
  case "check":
715
897
  process.exitCode = await runCheck(flags, env);
716
898
  return;
@@ -2,6 +2,7 @@ import { spawnSync } from "node:child_process";
2
2
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  const DIFFCI_SCRIPTS = {
5
+ "diffci:verify": "diffci verify --changed --json",
5
6
  "diffci:check": "diffci check",
6
7
  "diffci:observe": "diffci observe --no-send",
7
8
  };
@@ -4,6 +4,34 @@ import { dirname, join, resolve } from "node:path";
4
4
  import { StringDecoder } from "node:string_decoder";
5
5
  const SERVER_INFO = { name: "diffci-mcp", version: "0.1.0" };
6
6
  const tools = [
7
+ {
8
+ name: "diffci_verify",
9
+ description: "Verify a clean commit range and return a receipt bound to the checked-out head commit. Resolves the CI event range automatically when base and head are omitted.",
10
+ inputSchema: {
11
+ type: "object",
12
+ properties: {
13
+ repo: { type: "string", description: "Repository path. Defaults to the MCP server working directory." },
14
+ base: { type: "string", description: "Optional base commit SHA. Must be paired with head." },
15
+ head: { type: "string", description: "Optional head commit SHA. Must be paired with base and match checked-out HEAD." },
16
+ timeoutMs: { type: "number", description: "Maximum verification-command runtime in milliseconds." },
17
+ redactPaths: { type: "boolean", description: "Replace paths with stable digests in analysis." },
18
+ },
19
+ additionalProperties: false,
20
+ },
21
+ },
22
+ {
23
+ name: "diffci_verify_changed",
24
+ description: "Verify the current staged, unstaged, and non-ignored untracked changes. Fails closed unless the exact working-tree snapshot passes selected or full fallback verification.",
25
+ inputSchema: {
26
+ type: "object",
27
+ properties: {
28
+ repo: { type: "string", description: "Repository path. Defaults to the MCP server working directory." },
29
+ timeoutMs: { type: "number", description: "Maximum verification-command runtime in milliseconds." },
30
+ redactPaths: { type: "boolean", description: "Replace paths with stable digests in analysis." },
31
+ },
32
+ additionalProperties: false,
33
+ },
34
+ },
7
35
  {
8
36
  name: "diffci_check",
9
37
  description: "Analyze the repository, run inferred full and selected test commands when available, and report paired runtime. Sends nothing to DiffCI Cloud.",
@@ -28,6 +56,7 @@ const tools = [
28
56
  properties: {
29
57
  repo: { type: "string", description: "Repository path. Defaults to the MCP server working directory." },
30
58
  workflow: { type: "boolean", description: "Also add the non-blocking GitHub Actions observer workflow." },
59
+ verificationWorkflow: { type: "boolean", description: "Also add the blocking GitHub Actions verification workflow." },
31
60
  force: { type: "boolean", description: "Overwrite existing instruction files." },
32
61
  },
33
62
  additionalProperties: false,
@@ -58,6 +87,33 @@ function booleanArg(args, name) {
58
87
  function commandForTool(name, args) {
59
88
  const repo = stringArg(args, "repo");
60
89
  switch (name) {
90
+ case "diffci_verify": {
91
+ const command = ["verify", "--json"];
92
+ if (repo)
93
+ command.push("--repo", resolve(repo));
94
+ for (const flag of ["base", "head"]) {
95
+ const value = stringArg(args, flag);
96
+ if (value)
97
+ command.push(`--${flag}`, value);
98
+ }
99
+ const timeoutMs = args.timeoutMs;
100
+ if (typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs >= 0)
101
+ command.push("--timeout-ms", String(timeoutMs));
102
+ if (booleanArg(args, "redactPaths"))
103
+ command.push("--redact-paths");
104
+ return command;
105
+ }
106
+ case "diffci_verify_changed": {
107
+ const command = ["verify", "--changed", "--json"];
108
+ if (repo)
109
+ command.push("--repo", resolve(repo));
110
+ const timeoutMs = args.timeoutMs;
111
+ if (typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs >= 0)
112
+ command.push("--timeout-ms", String(timeoutMs));
113
+ if (booleanArg(args, "redactPaths"))
114
+ command.push("--redact-paths");
115
+ return command;
116
+ }
61
117
  case "diffci_check": {
62
118
  const command = ["check"];
63
119
  if (repo)
@@ -81,6 +137,8 @@ function commandForTool(name, args) {
81
137
  command.push("--repo", resolve(repo));
82
138
  if (booleanArg(args, "workflow"))
83
139
  command.push("--workflow");
140
+ if (booleanArg(args, "verificationWorkflow"))
141
+ command.push("--verification-workflow");
84
142
  if (booleanArg(args, "force"))
85
143
  command.push("--force");
86
144
  return command;
@@ -152,9 +210,17 @@ async function handle(request) {
152
210
  run.stderr.trim() ? `stderr:\n${run.stderr.trim()}` : "",
153
211
  `exitCode: ${run.exitCode}`,
154
212
  ].filter(Boolean).join("\n\n");
213
+ let structuredContent;
214
+ if ((params.name === "diffci_verify" || params.name === "diffci_verify_changed") && run.stdout.trim()) {
215
+ try {
216
+ structuredContent = JSON.parse(run.stdout);
217
+ }
218
+ catch { /* The text and non-zero status still carry the failure. */ }
219
+ }
155
220
  success(id, {
156
221
  content: [{ type: "text", text }],
157
222
  isError: run.exitCode !== 0,
223
+ structuredContent,
158
224
  });
159
225
  return;
160
226
  }