@diffci.com/diffci 0.3.2 → 0.3.4

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 (51) hide show
  1. package/.agents/plugins/marketplace.json +12 -0
  2. package/README.md +25 -5
  3. package/action.yml +3 -3
  4. package/dist-client/src/client/agent-selection.js +67 -0
  5. package/dist-client/src/client/cli.js +42 -13
  6. package/dist-client/src/client/full-command.js +30 -0
  7. package/dist-client/src/client/mcp.js +74 -7
  8. package/dist-client/src/client/observe.js +1 -0
  9. package/dist-client/src/client/verify-savings.js +24 -7
  10. package/dist-client/src/client/verify.js +29 -24
  11. package/docs/adoption-metrics.md +31 -5
  12. package/docs/adoption-outreach.md +43 -8
  13. package/docs/agent-adoption-kit.md +3 -3
  14. package/docs/agent-plugin.md +80 -0
  15. package/docs/claude-code.md +4 -4
  16. package/docs/codex.md +4 -4
  17. package/docs/cursor.md +5 -4
  18. package/docs/distribution.md +6 -4
  19. package/docs/mcp.md +4 -0
  20. package/docs/npm-adoption.md +3 -3
  21. package/node_modules/@diffci.com/core/README.md +41 -2
  22. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  23. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +1 -1
  24. package/node_modules/@diffci.com/core/dist/planner/test-command.js +76 -0
  25. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  26. package/node_modules/@diffci.com/core/dist/repo/analyzer.js +19 -1
  27. package/node_modules/@diffci.com/core/dist/repo/analyzer.js.map +1 -1
  28. package/node_modules/@diffci.com/core/dist/repo/graph.js +34 -6
  29. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  30. package/node_modules/@diffci.com/core/dist/repo/test-discovery.d.ts +7 -0
  31. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +58 -0
  32. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  33. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +5 -0
  34. package/node_modules/@diffci.com/core/dist/repo/workspaces.d.ts +2 -0
  35. package/node_modules/@diffci.com/core/dist/repo/workspaces.js +37 -0
  36. package/node_modules/@diffci.com/core/dist/repo/workspaces.js.map +1 -0
  37. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +1 -1
  38. package/node_modules/@diffci.com/core/src/planner/test-command.ts +59 -0
  39. package/node_modules/@diffci.com/core/src/repo/analyzer.ts +18 -1
  40. package/node_modules/@diffci.com/core/src/repo/graph.ts +33 -6
  41. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +54 -0
  42. package/node_modules/@diffci.com/core/src/repo/types.ts +2 -0
  43. package/node_modules/@diffci.com/core/src/repo/workspaces.ts +29 -0
  44. package/package.json +10 -4
  45. package/packaging/agent-plugin/.claude-plugin/plugin.json +6 -0
  46. package/packaging/agent-plugin/.codex-plugin/plugin.json +8 -0
  47. package/packaging/agent-plugin/.mcp.json +13 -0
  48. package/packaging/agent-plugin/skills/diffci-verify/SKILL.md +35 -0
  49. package/server.json +2 -2
  50. package/site/assets/calcom-runtime-evidence.svg +11 -0
  51. package/site/llms.txt +44 -0
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "diffci-local",
3
+ "interface": { "displayName": "DiffCI" },
4
+ "plugins": [
5
+ {
6
+ "name": "diffci",
7
+ "source": { "source": "local", "path": "./packaging/agent-plugin" },
8
+ "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" },
9
+ "category": "Productivity"
10
+ }
11
+ ]
12
+ }
package/README.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # DiffCI
2
2
 
3
+ **Open-source test-impact analysis for faster CI.** DiffCI finds tests affected by a code change and measures full versus selected runtime for teams evaluating CI savings.
4
+
5
+ ```bash
6
+ npx "@diffci.com/diffci@latest" check
7
+ ```
8
+
9
+ Requires Git and Node.js 22.5+. Runs tests locally and sends nothing by default; keep required CI authoritative.
10
+
11
+ **Measured example:** a controlled Cal.com sandbox replay measured **44.2% net reduction** in an install + pretest + test workload, including analysis overhead. This is one job-equivalent comparison, not production savings or a forecast.
12
+ [Timings and limitations](docs/research/2026-08-24-calcom-execution-observability/11-frozen-identity-and-complete-job-savings.md).
13
+
14
+ ![Recorded Cal.com sandbox runtime comparison](site/assets/calcom-runtime-evidence.svg)
15
+
16
+ [Star the open-source engine](https://github.com/DiffCI/core) · [Volunteer a pilot repository](https://diffci.com/#pilot).
17
+ Watch → Custom → Releases and Discussions on Core to follow support and benchmark updates.
18
+
19
+ The engine lives in **[DiffCI/core](https://github.com/DiffCI/core)**. This repository contains the CLI, integrations, website, and product surfaces.
20
+
3
21
  [Website](https://diffci.com/) · [Test impact analysis guide](https://diffci.com/test-impact-analysis/github-actions) · [Open evidence study](https://diffci.com/research/diffci-open-evidence-2026)
4
22
 
5
23
 
@@ -163,19 +181,19 @@ permissions:
163
181
  contents: read
164
182
  jobs:
165
183
  diffci:
166
- runs-on: ubuntu-latest
184
+ runs-on: ubuntu-24.04
167
185
  continue-on-error: true
168
186
  steps:
169
- - uses: actions/checkout@v4
187
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # immutable checkout pin
170
188
  with:
171
189
  fetch-depth: 0
172
- - uses: DiffCI/DiffCI.com@edac0ad48ae4bbdcf7e7839cf0bb371201a46872
190
+ - uses: DiffCI/DiffCI.com@cc870c9258adf8a278d7fe678f0d793ff65cdae6
173
191
  ```
174
192
 
175
193
  Then check the workflow locally with `npx "@diffci.com/diffci@latest" verify-workflow`. Keep the observer
176
194
  out of required checks and other jobs' `needs` lists. The Action adds a job summary and a
177
195
  `diffci-observation` artifact to the run; it does not alter which tests your other jobs execute.
178
- The example pins release `v0.3.2` to its qualified feature commit SHA for reproducibility.
196
+ The example pins release `v0.3.4` to its qualified feature commit SHA for reproducibility.
179
197
 
180
198
  The CLI sends no report with `--no-send`. The Action uploads a GitHub artifact by default; sending to
181
199
  DiffCI's hosted service requires an explicitly configured endpoint and token.
@@ -378,7 +396,7 @@ npm run research:sandbox:deploy
378
396
  DiffCI is intended to be installable as infrastructure, not only as a hosted shadow experiment:
379
397
 
380
398
  ```yaml
381
- - uses: DiffCI/DiffCI.com@edac0ad48ae4bbdcf7e7839cf0bb371201a46872
399
+ - uses: DiffCI/DiffCI.com@cc870c9258adf8a278d7fe678f0d793ff65cdae6
382
400
  ```
383
401
 
384
402
  ```bash
@@ -393,3 +411,5 @@ DiffCI Cloud build on that trust boundary for teams that want shared reports and
393
411
  [`docs/distribution.md`](docs/distribution.md) for the package and Action positioning,
394
412
  [`docs/open-core-packaging.md`](docs/open-core-packaging.md) for the commercial split, and
395
413
  [`docs/npm-adoption.md`](docs/npm-adoption.md) for copy-paste pilot material.
414
+
415
+ Useful? [Star DiffCI/core](https://github.com/DiffCI/core), watch Releases and Discussions, or [volunteer a pilot repository](https://diffci.com/#pilot).
package/action.yml CHANGED
@@ -14,12 +14,12 @@
14
14
  #
15
15
  # jobs:
16
16
  # diffci:
17
- # runs-on: ubuntu-latest
17
+ # runs-on: ubuntu-24.04
18
18
  # continue-on-error: true # a DiffCI failure must not become the workflow's conclusion
19
19
  # permissions:
20
20
  # contents: read
21
21
  # steps:
22
- # - uses: actions/checkout@v4
22
+ # - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
23
23
  # with:
24
24
  # fetch-depth: 0 # the base commit must exist locally, or DiffCI refuses
25
25
  # - uses: DiffCI/DiffCI.com@<40-character commit sha>
@@ -103,7 +103,7 @@ runs:
103
103
  using: composite
104
104
  steps:
105
105
  - name: Set up Node for the observer
106
- uses: actions/setup-node@v4
106
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
107
107
  with:
108
108
  node-version: ${{ inputs.node-version }}
109
109
 
@@ -0,0 +1,67 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { resolve } from "node:path";
3
+ import { observe } from "./observe.js";
4
+ import { executableSelection } from "./verify.js";
5
+ import { captureWorkingTreeSnapshot } from "./working-tree.js";
6
+ function changedPaths(repoPath, snapshot) {
7
+ return execFileSync("git", ["diff", "--name-only", "-z", snapshot.baseSha, snapshot.commitSha], {
8
+ cwd: repoPath, encoding: "utf8", windowsHide: true,
9
+ }).split("\0").filter(Boolean);
10
+ }
11
+ /** Cheap change discovery, without building the dependency graph. */
12
+ export function agentChangedFiles(repoInput) {
13
+ const repoPath = resolve(repoInput);
14
+ const before = captureWorkingTreeSnapshot(repoPath);
15
+ const changedFiles = changedPaths(repoPath, before);
16
+ const after = captureWorkingTreeSnapshot(repoPath);
17
+ const unchanged = before.baseSha === after.baseSha && before.treeSha === after.treeSha;
18
+ return {
19
+ schema: "diffci.agent-changes.v1", scope: "working-tree",
20
+ status: unchanged ? "observed" : "blocked", tests_executed: false,
21
+ snapshot: { base_sha: before.baseSha, tree_sha: before.treeSha, unchanged },
22
+ changed_files: changedFiles,
23
+ reason: unchanged ? "current changes relative to HEAD" : "working tree changed during discovery; retry",
24
+ };
25
+ }
26
+ /** Analyze the live snapshot using the same engine as verification. Never executes tests. */
27
+ export async function agentSelection(repoInput) {
28
+ const repoPath = resolve(repoInput);
29
+ const before = captureWorkingTreeSnapshot(repoPath);
30
+ const changedFiles = changedPaths(repoPath, before);
31
+ const observation = before.changed ? await observe({
32
+ repoPath, env: process.env, version: "agent-selection-v1",
33
+ baseOverride: before.baseSha, headOverride: before.commitSha,
34
+ }) : undefined;
35
+ const result = observation?.result;
36
+ const after = captureWorkingTreeSnapshot(repoPath);
37
+ const unchanged = before.baseSha === after.baseSha && before.treeSha === after.treeSha;
38
+ let command;
39
+ let selection = "none";
40
+ let reason = "no uncommitted changes; use diffci_verify for a committed range";
41
+ if (before.changed) {
42
+ reason = observation?.reason ?? "analysis did not produce a runnable plan";
43
+ if (observation?.status === "OBSERVED" && result) {
44
+ ({ command, selection, reason } = executableSelection(repoPath, result));
45
+ if (!command)
46
+ reason = `no executable verification command is available: ${reason}`;
47
+ }
48
+ }
49
+ const ready = unchanged && (!before.changed || Boolean(command));
50
+ return {
51
+ schema: "diffci.agent-selection.v1", scope: "working-tree",
52
+ status: ready ? "planned" : "blocked", tests_executed: false,
53
+ snapshot: { base_sha: before.baseSha, tree_sha: before.treeSha, unchanged },
54
+ changed_files: changedFiles, selection,
55
+ selected_tests: selection === "selected" ? result?.selectedTests ?? [] : [],
56
+ tests_available: result?.totalTestCount ?? 0,
57
+ tests_selected: selection === "full" ? result?.totalTestCount ?? 0 : selection === "selected" ? result?.selectedTests.length ?? 0 : 0,
58
+ command: ready ? command : undefined,
59
+ reason: unchanged ? reason : "working tree changed during analysis; reanalyze",
60
+ fallback_reasons: result?.fallbackReasons ?? [],
61
+ analysis_status: observation?.status ?? "not_needed",
62
+ analysis_mode: result?.mode,
63
+ graph_confidence: result?.graph.effectiveConfidence ?? result?.graph.confidence,
64
+ risk_signals: result?.riskSignals ?? [],
65
+ required_ci_authoritative: true,
66
+ };
67
+ }
@@ -31,14 +31,14 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
31
31
  import { tmpdir } from "node:os";
32
32
  import { basename, dirname, join, resolve } from "node:path";
33
33
  import { observe, isInsideRepository } from "./observe.js";
34
- import { inferFullCommand, inferComparableSelectedCommand } from "./full-command.js";
34
+ import { inferFullCommand, inferComparableSelectedCommand, inferWorkspaceComparison } from "./full-command.js";
35
35
  import { addDiffciPackageScripts, detectPackageManager, installDiffci } from "./install.js";
36
36
  import { submitObservation } from "./submit.js";
37
37
  import { githubDeliveryWarning } from "./delivery-warning.js";
38
38
  import { sendUsageSignal } from "./usage-signal.js";
39
39
  import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conflicts.js";
40
40
  import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
41
- import { formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
41
+ import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
42
42
  import { auditWorkflows, isNonInterfering } from "./workflow-guard.js";
43
43
  function parseArgs(argv) {
44
44
  const args = argv.slice(2);
@@ -79,7 +79,19 @@ function observerIdentity() {
79
79
  if (parsed.name === "@diffci.com/diffci" || parsed.name === "diffci") {
80
80
  let sha;
81
81
  try {
82
- sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: current, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
82
+ const gitRoot = execFileSync("git", ["rev-parse", "--show-toplevel"], {
83
+ cwd: current,
84
+ encoding: "utf8",
85
+ stdio: ["ignore", "pipe", "ignore"],
86
+ }).trim();
87
+ const packageRoot = resolve(current);
88
+ const normalizedGitRoot = resolve(gitRoot);
89
+ const rootsMatch = process.platform === "win32"
90
+ ? packageRoot.toLowerCase() === normalizedGitRoot.toLowerCase()
91
+ : packageRoot === normalizedGitRoot;
92
+ if (rootsMatch) {
93
+ sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: current, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
94
+ }
83
95
  }
84
96
  catch {
85
97
  // Installed from a tarball rather than a checkout: there is no commit to report, and
@@ -181,13 +193,13 @@ permissions:
181
193
  contents: read
182
194
  jobs:
183
195
  diffci:
184
- runs-on: ubuntu-latest
196
+ runs-on: ubuntu-24.04
185
197
  continue-on-error: true
186
198
  steps:
187
- - uses: actions/checkout@v4
199
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # immutable checkout pin
188
200
  with:
189
201
  fetch-depth: 0
190
- - uses: actions/setup-node@v4
202
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # immutable setup-node pin
191
203
  with:
192
204
  node-version: 22
193
205
  - run: npx "@diffci.com/diffci@${version}" observe --no-send
@@ -201,13 +213,13 @@ permissions:
201
213
  jobs:
202
214
  diffci-verify:
203
215
  name: DiffCI verification
204
- runs-on: ubuntu-latest
216
+ runs-on: ubuntu-24.04
205
217
  steps:
206
- - uses: actions/checkout@v4
218
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # immutable checkout pin
207
219
  with:
208
220
  fetch-depth: 0
209
221
  ref: \${{ github.event.pull_request.head.sha || github.sha }}
210
- - uses: actions/setup-node@v4
222
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # immutable setup-node pin
211
223
  with:
212
224
  node-version: 22
213
225
  - name: Verify changed code
@@ -442,6 +454,9 @@ function summarise(report, executionFollows = false) {
442
454
  else if (result.commandRefusalReason || result.proposedCommands.length === 0) {
443
455
  lines.push(" planned reduction: unavailable (no runnable selected command); runtime savings unmeasured");
444
456
  }
457
+ else if (result.workspaceCommands) {
458
+ lines.push(" workspace execution retains full auxiliary and non-isolated suites; affected-file counts do not measure execution reduction");
459
+ }
445
460
  else if (result.totalTestCount > 0) {
446
461
  const avoided = Math.max(0, result.totalTestCount - result.selectedTests.length);
447
462
  const percent = (avoided / result.totalTestCount) * 100;
@@ -502,7 +517,10 @@ async function runCheck(flags, env) {
502
517
  console.log(JSON.stringify({ observation, timing: null, reason }, null, 2));
503
518
  return 1;
504
519
  }
505
- const inferred = inferFullCommand(repoPath);
520
+ const commandPlanningStarted = performance.now();
521
+ const workspace = observation.result.mode !== "FULL" && !observation.result.commandRefusalReason
522
+ ? inferWorkspaceComparison(repoPath, observation.result.proposedCommands, observation.result.selectedTests) : undefined;
523
+ const inferred = workspace?.full ? { command: workspace.full, reason: workspace.reason } : inferFullCommand(repoPath);
506
524
  if (!inferred.command) {
507
525
  print(` timing: unavailable (${inferred.reason})`);
508
526
  if (flags.json === true)
@@ -526,14 +544,15 @@ async function runCheck(flags, env) {
526
544
  console.log(JSON.stringify({ observation, full }, null, 2));
527
545
  return full.exitCode === 0 && !full.timedOut ? 0 : 1;
528
546
  }
529
- if (observation.result.commandRefusalReason || observation.result.proposedCommands.length !== 1) {
547
+ if (observation.result.commandRefusalReason || (!workspace?.selected && observation.result.proposedCommands.length !== 1)) {
530
548
  const reason = observation.result.commandRefusalReason ?? "the selection has no single runnable command";
531
549
  print(` timing: unavailable (${reason})`);
532
550
  if (flags.json === true)
533
551
  console.log(JSON.stringify({ observation, timing: null, reason }, null, 2));
534
552
  return 0;
535
553
  }
536
- const selected = inferComparableSelectedCommand(repoPath, observation.result.proposedCommands[0], observation.result.selectedTests);
554
+ const selected = workspace?.selected ? { command: workspace.selected, reason: workspace.reason }
555
+ : inferComparableSelectedCommand(repoPath, observation.result.proposedCommands[0], observation.result.selectedTests);
537
556
  if (!selected.command) {
538
557
  print(` timing: unavailable (${selected.reason})`);
539
558
  if (flags.json === true)
@@ -547,6 +566,7 @@ async function runCheck(flags, env) {
547
566
  full: inferred.command,
548
567
  selectedFromReport: reportPath,
549
568
  selectedCommandOverride: selected.command,
569
+ analysisOverheadMs: observation.timings.totalMs + performance.now() - commandPlanningStarted,
550
570
  out: savingsPath,
551
571
  markdown: markdownPath,
552
572
  label: stringFlag(flags, "label") ?? basename(repoPath),
@@ -560,6 +580,8 @@ async function runCheck(flags, env) {
560
580
  });
561
581
  writeVerifySavingsReport(savings, { out: savingsPath, markdown: markdownPath });
562
582
  print(formatVerifySavingsSummary(savings));
583
+ if (formatGrowthPrompt(savings))
584
+ print(formatGrowthPrompt(savings));
563
585
  print(` savings report: ${savingsPath}`);
564
586
  print(` markdown: ${markdownPath}`);
565
587
  if (flags.json === true)
@@ -641,7 +663,7 @@ async function runObserve(flags, env) {
641
663
  // says the same thing the report says, including when the answer is "refused" or "not sent".
642
664
  if (env.GITHUB_STEP_SUMMARY) {
643
665
  try {
644
- writeFileSync(env.GITHUB_STEP_SUMMARY, `### DiffCI (observation only)\n\n\`\`\`\n${summary}${delivery ? `\n delivery: ${delivery}` : ""}\n\`\`\`\n`, { flag: "a" });
666
+ writeFileSync(env.GITHUB_STEP_SUMMARY, `### DiffCI (observation only)\n\n\`\`\`\n${summary}${delivery ? `\n delivery: ${delivery}` : ""}\n\`\`\`\n\n[Open-source engine: DiffCI/core](https://github.com/DiffCI/core)\n`, { flag: "a" });
645
667
  }
646
668
  catch {
647
669
  // Losing the summary is cosmetic; the report on disk is the record.
@@ -742,6 +764,8 @@ function runVerifySavingsCommand(flags, env) {
742
764
  const report = runVerifySavings(options);
743
765
  writeVerifySavingsReport(report, { out: options.out, markdown: options.markdown });
744
766
  console.log(formatVerifySavingsSummary(report));
767
+ if (formatGrowthPrompt(report))
768
+ console.log(formatGrowthPrompt(report));
745
769
  console.log(` report: ${options.out}`);
746
770
  if (options.markdown)
747
771
  console.log(` markdown: ${options.markdown}`);
@@ -810,6 +834,8 @@ async function runPilot(flags, env) {
810
834
  });
811
835
  writeVerifySavingsReport(savings, { out: savingsPath, markdown: markdownPath });
812
836
  console.log(formatVerifySavingsSummary(savings));
837
+ if (formatGrowthPrompt(savings))
838
+ console.log(formatGrowthPrompt(savings));
813
839
  console.log(` savings report: ${savingsPath}`);
814
840
  console.log(` markdown: ${markdownPath}`);
815
841
  return savings.comparison.evidenceValid ? 0 : 1;
@@ -832,6 +858,9 @@ function runValidateSpecs(flags) {
832
858
  }
833
859
  const USAGE = `diffci - change-aware CI analysis and paired timing
834
860
 
861
+ Open-source engine: https://github.com/DiffCI/core
862
+ Pilot a repository: https://diffci.com/#pilot
863
+
835
864
  Usage:
836
865
  diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--force]
837
866
  diffci mcp
@@ -1,6 +1,36 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { readRepositoryConfig } from "@diffci.com/core/repo/repo-config";
4
+ import { analyzeRepository } from "@diffci.com/core/repo/analyzer";
5
+ import { commandSpecToString, planSelectiveTestCommands } from "@diffci.com/core/planner/test-command";
6
+ /** Rebuild the complete plan locally; never join arbitrary report commands. */
7
+ export function inferWorkspaceComparison(repoPath, proposed, selectedTests) {
8
+ const profile = analyzeRepository({ repoPath });
9
+ if (!profile.workspaceTestPackages?.length)
10
+ return { reason: "No declared workspace test suites" };
11
+ const scripts = profile.packageJson.scripts;
12
+ if (scripts.pretest || scripts.posttest)
13
+ return { reason: "Root lifecycle hooks cannot be omitted" };
14
+ const npm = profile.packageManager === "npm" && !scripts.test;
15
+ const pnpm = profile.packageManager === "pnpm" && scripts.test === "pnpm -r run test";
16
+ if (!npm && !pnpm)
17
+ return { reason: "Workspace full validation scope is not recognized" };
18
+ const plan = planSelectiveTestCommands(profile, selectedTests);
19
+ if (plan.refusalReason || !plan.commands.length)
20
+ return { reason: plan.refusalReason ?? "No workspace commands" };
21
+ const expected = plan.commands.map(commandSpecToString);
22
+ if (JSON.stringify(expected) !== JSON.stringify(proposed))
23
+ return { reason: "Report commands differ from the verified workspace plan" };
24
+ // This deliberately limited shell vocabulary works on both cmd.exe and sh.
25
+ // Unusual names require structured execution rather than guessed escaping.
26
+ if (plan.commands.some(command => command.env || !/^[\w-]+$/.test(command.executable) || command.args.some(arg => !/^[\w./:@=-]+$/.test(arg))))
27
+ return { reason: "Workspace command contains unsupported shell arguments" };
28
+ const full = npm ? profile.workspaceTestPackages.map(suite => `npm test --workspace=${suite.packageRoot} -- --run`).join(" && ") : "pnpm test";
29
+ const selected = plan.commands.map(command => [command.executable, ...command.args].join(" ")).join(" && ");
30
+ if (full.length > 6000 || selected.length > 6000)
31
+ return { reason: "Complete workspace chain exceeds the safe shell command length" };
32
+ return { full, selected, reason: "Verified workspace plan with full auxiliary validation retained" };
33
+ }
4
34
  /** Automatic timing must retain the non-selected phases of the declared test script. */
5
35
  export function inferComparableSelectedCommand(repoPath, proposed, selectedTests) {
6
36
  const selected = inferSelectedCommand(repoPath, proposed, selectedTests);
@@ -2,8 +2,26 @@
2
2
  import { execFile } from "node:child_process";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { StringDecoder } from "node:string_decoder";
5
+ import { agentChangedFiles, agentSelection } from "./agent-selection.js";
5
6
  const SERVER_INFO = { name: "diffci-mcp", version: "0.1.0" };
6
7
  const tools = [
8
+ ...["diffci_changed_files", "diffci_select_tests", "diffci_explain_selection", "diffci_run_affected_tests"].map((name) => ({
9
+ name,
10
+ description: name === "diffci_run_affected_tests"
11
+ ? "Reanalyze and verify the current working-tree snapshot with affected tests or conservative full fallback. Required CI remains authoritative."
12
+ : name === "diffci_changed_files"
13
+ ? "List staged, unstaged and non-ignored untracked changed paths relative to HEAD, with a snapshot identity. Builds no dependency graph and runs no tests."
14
+ : "Inspect current staged, unstaged and non-ignored untracked changes and return a snapshot-bound affected-test plan and fallback reasons. Runs no tests; a plan is not a passing receipt.",
15
+ inputSchema: {
16
+ type: "object",
17
+ properties: {
18
+ repo: { type: "string", description: "Absolute repository path; defaults to server working directory. Always pass the edited repository when using a plugin." },
19
+ ...(name === "diffci_run_affected_tests" ? { timeoutMs: { type: "number", minimum: 0 } } : {}),
20
+ },
21
+ additionalProperties: false,
22
+ },
23
+ annotations: { readOnlyHint: name !== "diffci_run_affected_tests", openWorldHint: false },
24
+ })),
7
25
  {
8
26
  name: "diffci_verify",
9
27
  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.",
@@ -103,6 +121,7 @@ function commandForTool(name, args) {
103
121
  command.push("--redact-paths");
104
122
  return command;
105
123
  }
124
+ case "diffci_run_affected_tests":
106
125
  case "diffci_verify_changed": {
107
126
  const command = ["verify", "--changed", "--json"];
108
127
  if (repo)
@@ -170,7 +189,7 @@ function runCli(args) {
170
189
  }
171
190
  function writeMessage(message) {
172
191
  const body = JSON.stringify(message);
173
- process.stdout.write(`Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`);
192
+ process.stdout.write(lineTransport ? `${body}\n` : `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`);
174
193
  }
175
194
  function success(id, result) {
176
195
  if (id === undefined)
@@ -204,6 +223,25 @@ async function handle(request) {
204
223
  return;
205
224
  }
206
225
  const args = params.arguments ?? {};
226
+ const tool = tools.find((entry) => entry.name === params.name);
227
+ if (!tool || !args || typeof args !== "object" || Array.isArray(args)) {
228
+ failure(id, -32602, "unknown tool or invalid arguments");
229
+ return;
230
+ }
231
+ const properties = tool.inputSchema.properties;
232
+ for (const [key, value] of Object.entries(args)) {
233
+ const property = properties[key];
234
+ if (!property || typeof value !== property.type || (key === "timeoutMs" && (!Number.isFinite(value) || value < 0))) {
235
+ failure(id, -32602, `invalid argument: ${key}`);
236
+ return;
237
+ }
238
+ }
239
+ if (["diffci_changed_files", "diffci_select_tests", "diffci_explain_selection"].includes(params.name)) {
240
+ const repo = stringArg(args, "repo") ?? process.cwd();
241
+ const plan = params.name === "diffci_changed_files" ? agentChangedFiles(repo) : await agentSelection(repo);
242
+ success(id, { content: [{ type: "text", text: JSON.stringify(plan) }], structuredContent: plan, isError: plan.status === "blocked" });
243
+ return;
244
+ }
207
245
  const run = await runCli(commandForTool(params.name, args));
208
246
  const text = [
209
247
  run.stdout.trim(),
@@ -211,7 +249,7 @@ async function handle(request) {
211
249
  `exitCode: ${run.exitCode}`,
212
250
  ].filter(Boolean).join("\n\n");
213
251
  let structuredContent;
214
- if ((params.name === "diffci_verify" || params.name === "diffci_verify_changed") && run.stdout.trim()) {
252
+ if (["diffci_verify", "diffci_verify_changed", "diffci_run_affected_tests"].includes(params.name) && run.stdout.trim()) {
215
253
  try {
216
254
  structuredContent = JSON.parse(run.stdout);
217
255
  }
@@ -229,9 +267,25 @@ async function handle(request) {
229
267
  }
230
268
  }
231
269
  let buffer = Buffer.alloc(0);
270
+ let lineTransport = false;
232
271
  const decoder = new StringDecoder("utf8");
233
272
  function readMessages() {
234
273
  while (true) {
274
+ while (buffer.length && [9, 10, 13, 32].includes(buffer[0]))
275
+ buffer = buffer.subarray(1);
276
+ if (buffer.length === 0)
277
+ return;
278
+ if (buffer[0] === 123 || buffer[0] === 91 || lineTransport) {
279
+ lineTransport = true;
280
+ const end = buffer.indexOf("\n");
281
+ if (end === -1)
282
+ return;
283
+ const body = buffer.subarray(0, end).toString("utf8").trim();
284
+ buffer = buffer.subarray(end + 1);
285
+ if (body)
286
+ dispatch(body);
287
+ continue;
288
+ }
235
289
  const headerEnd = buffer.indexOf("\r\n\r\n");
236
290
  if (headerEnd === -1)
237
291
  return;
@@ -248,12 +302,25 @@ function readMessages() {
248
302
  return;
249
303
  const body = buffer.subarray(bodyStart, bodyEnd).toString("utf8");
250
304
  buffer = buffer.subarray(bodyEnd);
251
- const request = JSON.parse(body);
252
- void handle(request).catch((error) => {
253
- const message = error instanceof Error ? error.message : String(error);
254
- failure(request.id, -32603, message);
255
- });
305
+ dispatch(body);
306
+ }
307
+ }
308
+ function dispatch(body) {
309
+ let request;
310
+ try {
311
+ request = JSON.parse(body);
312
+ }
313
+ catch {
314
+ failure(null, -32700, "invalid JSON");
315
+ return;
256
316
  }
317
+ if (!request || typeof request !== "object" || Array.isArray(request)) {
318
+ failure(null, -32600, "invalid request");
319
+ return;
320
+ }
321
+ void handle(request).catch((error) => {
322
+ failure(request.id, -32603, error instanceof Error ? error.message : String(error));
323
+ });
257
324
  }
258
325
  process.stdin.on("data", (chunk) => {
259
326
  buffer = Buffer.concat([buffer, chunk]);
@@ -213,6 +213,7 @@ export async function observe(options) {
213
213
  totalTestCount: profile.testFilePaths.length,
214
214
  fallbackReasons: impact.fallbackReasons,
215
215
  proposedCommands: (commandPlan?.commands ?? []).map(commandSpecToString),
216
+ workspaceCommands: Boolean(profile.workspaceTestPackages?.length),
216
217
  goScope: profile.diffciConfig?.go?.scope,
217
218
  vueScope: profile.vueScope ? { packageRoot: hashPath(profile.vueScope.packageRoot), testConfig: hashPath(profile.vueScope.testConfig) } : undefined,
218
219
  scopedTestFiles: profile.vueScope ? profile.testFilePaths.map(hashPath) : undefined,
@@ -9,17 +9,17 @@ function tail(value, bytes) {
9
9
  return value;
10
10
  return value.slice(-bytes);
11
11
  }
12
- function readSelectionFromObservation(path) {
12
+ function readSelectionFromObservation(path, override) {
13
13
  const absolutePath = resolve(path);
14
14
  const bytes = readFileSync(absolutePath);
15
15
  const parsed = JSON.parse(bytes.toString("utf8"));
16
16
  if (parsed.status !== "OBSERVED")
17
17
  throw new Error(`--selected-from-report requires an OBSERVED report; got ${String(parsed.status)}`);
18
18
  const commands = parsed.result?.proposedCommands;
19
- if (!Array.isArray(commands) || commands.length !== 1 || typeof commands[0] !== "string" || !commands[0].trim()) {
19
+ if (!Array.isArray(commands) || !commands.length || commands.some(command => typeof command !== "string" || !command.trim()) || (commands.length !== 1 && !override)) {
20
20
  throw new Error("--selected-from-report requires exactly one non-empty proposed command; use --selected with an explicit command covering the complete selection for multi-command plans");
21
21
  }
22
- const command = commands[0];
22
+ const command = override ?? commands[0];
23
23
  const selectedTests = Array.isArray(parsed.result?.selectedTests) ? parsed.result.selectedTests : undefined;
24
24
  return {
25
25
  command,
@@ -154,8 +154,7 @@ function buildProvenance(selection, beforeFull, afterFull, afterSelected, snapsh
154
154
  }
155
155
  function resolveSelection(options) {
156
156
  if (options.selectedFromReport) {
157
- const selection = readSelectionFromObservation(options.selectedFromReport);
158
- return options.selectedCommandOverride ? { ...selection, command: options.selectedCommandOverride } : selection;
157
+ return readSelectionFromObservation(options.selectedFromReport, options.selectedCommandOverride);
159
158
  }
160
159
  if (!options.selected)
161
160
  throw new Error("--selected <command> or --selected-from-report <path> is required");
@@ -241,6 +240,8 @@ function assessFailures(trials) {
241
240
  export function measureCommand(command, options) {
242
241
  const startedAt = new Date().toISOString();
243
242
  const started = Date.now();
243
+ // Match the shell used by Windows package scripts, including && short-circuiting
244
+ // and native exit codes; Windows PowerShell 5 cannot execute those chains.
244
245
  const shellCommand = process.platform === "win32" ? "cmd.exe" : "sh";
245
246
  const shellArgv = process.platform === "win32" ? ["/d", "/s", "/c", command] : ["-c", command];
246
247
  const result = spawnSync(shellCommand, shellArgv, {
@@ -306,7 +307,11 @@ export function buildVerifySavingsReport(input) {
306
307
  const selectedCommandSucceeded = trials.every((trial) => trial.selected.exitCode === 0 && !trial.selected.timedOut);
307
308
  const missedFailureSignal = trials.some((trial) => (trial.full.exitCode !== 0 || trial.full.timedOut) && trial.selected.exitCode === 0 && !trial.selected.timedOut);
308
309
  const preparationsSucceeded = trials.every((trial) => trial.preparations.every((preparation) => preparation.exitCode === 0 && !preparation.timedOut));
309
- const evidenceValid = fullCommandSucceeded && selectedCommandSucceeded && provenance.checkoutStable && preparationsSucceeded;
310
+ // A suspended runner or clock discontinuity can exceed spawnSync's active timeout
311
+ // while the child still exits zero. Such elapsed times cannot establish savings.
312
+ const elapsedTimesValid = trials.every((trial) => [...trial.preparations, trial.full, trial.selected]
313
+ .every((measurement) => Number.isFinite(measurement.wallMs) && measurement.wallMs >= 0 && (input.timeoutMs === 0 || measurement.wallMs <= input.timeoutMs)));
314
+ const evidenceValid = fullCommandSucceeded && selectedCommandSucceeded && provenance.checkoutStable && preparationsSucceeded && elapsedTimesValid;
310
315
  const performanceEvidence = !evidenceValid
311
316
  ? "INVALID"
312
317
  : protocol.repetitions >= 3 && protocol.alternatingOrder && protocol.cacheStateControlled
@@ -325,6 +330,8 @@ export function buildVerifySavingsReport(input) {
325
330
  : "Runtime evidence is preliminary until at least three alternating, cache-prepared repetitions agree.");
326
331
  if (missedFailureSignal)
327
332
  notes.push("Full failed while selected passed; inspect outputs before treating the selection as safe.");
333
+ if (!elapsedTimesValid)
334
+ notes.push("Timing invalid: elapsed wall time is outside the configured timeout bounds; runner suspension or a clock discontinuity may have occurred.");
328
335
  if (input.provenance && !input.provenance.checkoutStable)
329
336
  notes.push(`Checkout provenance invalid: ${input.provenance.invalidReasons.join("; ")}.`);
330
337
  return {
@@ -372,6 +379,11 @@ function formatMs(ms) {
372
379
  function formatPercent(value) {
373
380
  return `${value >= 0 ? "+" : ""}${value.toFixed(1)}%`;
374
381
  }
382
+ export function formatGrowthPrompt(report) {
383
+ return report.comparison.evidenceValid && report.comparison.percentChange > 0
384
+ ? "Useful? Star the open-source engine: https://github.com/DiffCI/core"
385
+ : "";
386
+ }
375
387
  export function renderVerifySavingsMarkdown(report) {
376
388
  const deltaLabel = report.comparison.deltaMs >= 0 ? "faster" : "slower";
377
389
  const overhead = report.analysisOverheadMs === undefined ? "not provided" : formatMs(report.analysisOverheadMs);
@@ -471,6 +483,9 @@ ${!report.comparison.fullCommandSucceeded || !report.comparison.selectedCommandS
471
483
  ## Interpretation Notes
472
484
 
473
485
  ${report.notes.map((note) => `- ${note}`).join("\n")}
486
+
487
+ Open-source engine: [DiffCI/core](https://github.com/DiffCI/core).
488
+ ${formatGrowthPrompt(report) ? "\nUseful? [Star DiffCI](https://github.com/DiffCI/core) or [volunteer a pilot repository](https://diffci.com/#pilot).\n" : ""}
474
489
  `;
475
490
  }
476
491
  function writeText(path, value) {
@@ -561,7 +576,9 @@ export function formatVerifySavingsSummary(report) {
561
576
  (report.comparison.missedFailureSignal ? "\n warning: full failed while selected passed; inspect outputs before claiming safety" : "");
562
577
  }
563
578
  if (!report.comparison.evidenceValid) {
564
- return `DiffCI verify-savings: comparison invalid because checkout provenance failed\n ${report.provenance.invalidReasons.join("; ")}`;
579
+ if (!report.provenance.checkoutStable)
580
+ return `DiffCI verify-savings: comparison invalid because checkout provenance failed\n ${report.provenance.invalidReasons.join("; ")}`;
581
+ return `DiffCI verify-savings: comparison invalid\n ${report.notes.find(note => note.startsWith("Timing invalid:")) ?? "Cache preparation failed."}`;
565
582
  }
566
583
  const lines = [
567
584
  `DiffCI verify-savings: ${report.comparison.performanceEvidence === "CONTROLLED" ? "controlled repeated" : "preliminary"} test execution ${Math.abs(report.comparison.grossPercentChange).toFixed(1)}% ${report.comparison.grossPercentChange >= 0 ? "faster" : "slower"} (${report.comparison.repetitions} ${report.comparison.repetitions === 1 ? "trial" : "trials"})`,