@diffci.com/diffci 0.3.14 → 0.3.16

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 (100) hide show
  1. package/LICENSE +20 -661
  2. package/README.md +1 -1
  3. package/dist-client/src/client/agent-selection.js +20 -0
  4. package/dist-client/src/client/cli.js +155 -12
  5. package/dist-client/src/client/context.js +1 -1
  6. package/dist-client/src/client/enforce-misses-collect.js +157 -0
  7. package/dist-client/src/client/enforce-misses.js +229 -0
  8. package/dist-client/src/client/enforce-policy.js +169 -0
  9. package/dist-client/src/client/feedback-prompt.js +42 -0
  10. package/dist-client/src/client/hook.js +94 -0
  11. package/dist-client/src/client/mcp.js +12 -4
  12. package/dist-client/src/client/observe.js +8 -3
  13. package/dist-client/src/client/telemetry.js +46 -0
  14. package/dist-client/src/client/usage-signal.js +17 -10
  15. package/dist-client/src/client/verify.js +48 -6
  16. package/node_modules/@diffci.com/core/LICENSE +21 -661
  17. package/node_modules/@diffci.com/core/NOTICE +2 -2
  18. package/node_modules/@diffci.com/core/README.md +21 -3
  19. package/node_modules/@diffci.com/core/dist/analyze.js +1 -1
  20. package/node_modules/@diffci.com/core/dist/analyze.js.map +1 -1
  21. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +1 -1
  22. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/ci-inference/evidence.js +1 -1
  24. package/node_modules/@diffci.com/core/dist/ci-inference/evidence.js.map +1 -1
  25. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js +1 -1
  26. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js.map +1 -1
  27. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js +1 -1
  28. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js.map +1 -1
  29. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js +1 -1
  30. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js.map +1 -1
  31. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js +1 -1
  32. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js.map +1 -1
  33. package/node_modules/@diffci.com/core/dist/ci-inference/schema.js +1 -1
  34. package/node_modules/@diffci.com/core/dist/ci-inference/schema.js.map +1 -1
  35. package/node_modules/@diffci.com/core/dist/cli.js +1 -1
  36. package/node_modules/@diffci.com/core/dist/cli.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +29 -4
  38. package/node_modules/@diffci.com/core/dist/git/git-diff.js +136 -22
  39. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  40. package/node_modules/@diffci.com/core/dist/git/types.d.ts +7 -0
  41. package/node_modules/@diffci.com/core/dist/index.js +1 -1
  42. package/node_modules/@diffci.com/core/dist/index.js.map +1 -1
  43. package/node_modules/@diffci.com/core/dist/measurement.js +1 -1
  44. package/node_modules/@diffci.com/core/dist/measurement.js.map +1 -1
  45. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js +1 -1
  46. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js.map +1 -1
  47. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +32 -0
  48. package/node_modules/@diffci.com/core/dist/repo/file-references.js +180 -9
  49. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  50. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +4 -0
  51. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +19 -0
  52. package/node_modules/@diffci.com/core/dist/repo/impact.js +105 -3
  53. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  54. package/node_modules/@diffci.com/core/dist/repo/npm-lockfile.d.ts +27 -0
  55. package/node_modules/@diffci.com/core/dist/repo/npm-lockfile.js +116 -0
  56. package/node_modules/@diffci.com/core/dist/repo/npm-lockfile.js.map +1 -0
  57. package/node_modules/@diffci.com/core/dist/repo/script-universe.js +1 -1
  58. package/node_modules/@diffci.com/core/dist/repo/script-universe.js.map +1 -1
  59. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +1 -1
  60. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -1
  61. package/node_modules/@diffci.com/core/dist/repo/workspaces.js +1 -1
  62. package/node_modules/@diffci.com/core/dist/repo/workspaces.js.map +1 -1
  63. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js +1 -1
  64. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js.map +1 -1
  65. package/node_modules/@diffci.com/core/dist/research/baseline/test-activity.js +1 -1
  66. package/node_modules/@diffci.com/core/dist/research/baseline/test-activity.js.map +1 -1
  67. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js +1 -1
  68. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js.map +1 -1
  69. package/node_modules/@diffci.com/core/package.json +1 -1
  70. package/node_modules/@diffci.com/core/src/analyze.ts +1 -1
  71. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +1 -1
  72. package/node_modules/@diffci.com/core/src/ci-inference/causal.ts +1 -1
  73. package/node_modules/@diffci.com/core/src/ci-inference/evidence.ts +1 -1
  74. package/node_modules/@diffci.com/core/src/ci-inference/expression.ts +1 -1
  75. package/node_modules/@diffci.com/core/src/ci-inference/infer.ts +1 -1
  76. package/node_modules/@diffci.com/core/src/ci-inference/jobs.ts +1 -1
  77. package/node_modules/@diffci.com/core/src/ci-inference/matrix.ts +1 -1
  78. package/node_modules/@diffci.com/core/src/ci-inference/purpose.ts +1 -1
  79. package/node_modules/@diffci.com/core/src/ci-inference/reference-graph.ts +1 -1
  80. package/node_modules/@diffci.com/core/src/ci-inference/resolve.ts +1 -1
  81. package/node_modules/@diffci.com/core/src/ci-inference/schema.ts +1 -1
  82. package/node_modules/@diffci.com/core/src/cli.ts +1 -1
  83. package/node_modules/@diffci.com/core/src/git/git-diff.ts +127 -21
  84. package/node_modules/@diffci.com/core/src/git/types.ts +7 -0
  85. package/node_modules/@diffci.com/core/src/index.ts +1 -1
  86. package/node_modules/@diffci.com/core/src/measurement.ts +1 -1
  87. package/node_modules/@diffci.com/core/src/repo/compiled-projects.ts +1 -1
  88. package/node_modules/@diffci.com/core/src/repo/file-references.ts +170 -9
  89. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +4 -0
  90. package/node_modules/@diffci.com/core/src/repo/impact.ts +115 -2
  91. package/node_modules/@diffci.com/core/src/repo/npm-lockfile.ts +109 -0
  92. package/node_modules/@diffci.com/core/src/repo/script-universe.ts +1 -1
  93. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +1 -1
  94. package/node_modules/@diffci.com/core/src/repo/workspaces.ts +1 -1
  95. package/node_modules/@diffci.com/core/src/research/baseline/matcher.ts +1 -1
  96. package/node_modules/@diffci.com/core/src/research/baseline/path-baseline.ts +1 -1
  97. package/node_modules/@diffci.com/core/src/research/baseline/registry.ts +1 -1
  98. package/node_modules/@diffci.com/core/src/research/baseline/test-activity.ts +1 -1
  99. package/node_modules/@diffci.com/core/src/research/baseline/workflow-parser.ts +1 -1
  100. package/package.json +6 -4
package/README.md CHANGED
@@ -19,7 +19,7 @@ the [cross-agent installation guide](https://github.com/DiffCI/core/blob/main/do
19
19
 
20
20
  ## Source and license
21
21
 
22
- This package is AGPL-3.0-only. Its current source lives in
22
+ This package is MIT-licensed. Its current source lives in
23
23
  [`DiffCI/core`](https://github.com/DiffCI/core/tree/main/packages/diffci-cli).
24
24
  The corresponding source for the previously published `0.3.10` package is
25
25
  preserved at [tagged Core commit `4c76be14`](https://github.com/DiffCI/core/tree/4c76be14cec37d94eb7df93922f3c29d202f4e65/packages/diffci-cli)
@@ -31,6 +31,8 @@ export async function agentSelection(repoInput) {
31
31
  const observation = before.changed ? await observe({
32
32
  repoPath, env: process.env, version: "agent-selection-v1",
33
33
  baseOverride: before.baseSha, headOverride: before.commitSha,
34
+ // The returned commands include any test-script phases (executableSelection).
35
+ selectTestPhases: true,
34
36
  }) : undefined;
35
37
  const result = observation?.result;
36
38
  const after = captureWorkingTreeSnapshot(repoPath);
@@ -68,3 +70,21 @@ export async function agentSelection(repoInput) {
68
70
  required_ci_authoritative: true,
69
71
  };
70
72
  }
73
+ /**
74
+ * One plain sentence ahead of the JSON, naming the exact command to run (2026-10-28). Agents given only
75
+ * the JSON plan mostly went on to pick their own test files or run the whole suite; the first line is
76
+ * what they act on, so it says what to run and nothing else.
77
+ */
78
+ export function selectionInstruction(plan) {
79
+ if (plan.status === "blocked")
80
+ return `DiffCI could not plan this change: ${plan.reason}. Run the repository's normal verification and report this.`;
81
+ if (plan.selection === "none")
82
+ return `Nothing to verify: ${plan.reason}.`;
83
+ const scope = plan.selection === "selected"
84
+ ? `DiffCI selected ${plan.tests_selected} of ${plan.tests_available} test files`
85
+ : `DiffCI requires the full suite (${plan.reason})`;
86
+ const run = plan.commands && plan.commands.length > 1
87
+ ? `Run these commands in order, exactly as given:\n${plan.commands.join("\n")}`
88
+ : `Run exactly:\n${plan.command}`;
89
+ return `${scope}. ${run}\nDo not substitute your own test files or the full suite.`;
90
+ }
@@ -17,6 +17,7 @@
17
17
  * verify-savings run a paired full-versus-selected timing check
18
18
  * validate-specs block conflicting same-turn change specifications
19
19
  * verify-workflow check that a DiffCI job in this repository's workflows cannot affect other jobs
20
+ * enforce-misses after a full run on main, find failures enforce mode would have skipped
20
21
  * version print the observer version
21
22
  *
22
23
  * Exit codes: `observe` exits 0 even when it refuses or errors, because a broken observer must not
@@ -33,9 +34,11 @@ import { basename, dirname, join, resolve } from "node:path";
33
34
  import { observe, isInsideRepository } from "./observe.js";
34
35
  import { inferFullCommand, inferComparableSelectedCommand, inferWorkspaceComparison } from "./full-command.js";
35
36
  import { addDiffciPackageScripts, detectPackageManager, installDiffci } from "./install.js";
37
+ import { hookCommand, installPrePushHook } from "./hook.js";
36
38
  import { submitObservation } from "./submit.js";
37
39
  import { githubDeliveryWarning } from "./delivery-warning.js";
38
- import { sendUsageSignal } from "./usage-signal.js";
40
+ import { configureTelemetry, readTelemetryPreference, recordUsage } from "./telemetry.js";
41
+ import { formatFeedbackPrompt, markFeedbackPromptShown, shouldShowFeedbackPrompt } from "./feedback-prompt.js";
39
42
  import { detectSpecificationConflicts, readSpecificationFile } from "./spec-conflicts.js";
40
43
  import { formatVerificationSummary, verificationExitCode, verifyChanged, verifyRange } from "./verify.js";
41
44
  import { formatGrowthPrompt, formatVerifySavingsSummary, measureCommand, runVerifySavings, writeVerifySavingsReport } from "./verify-savings.js";
@@ -43,6 +46,8 @@ import { auditWorkflows, isNonInterfering } from "./workflow-guard.js";
43
46
  import { renderPilotPacket } from "./pilot-packet.js";
44
47
  import { observerIdentity } from "./package-identity.js";
45
48
  import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "./workflow-templates.js";
49
+ import { buildMissReport, formatMissReportMarkdown, parseJunit } from "./enforce-misses.js";
50
+ import { findReceipt, findWindowStart, inferRerunArgs, mergedPullRequests, MISS_REPORT_FILE, rerunFailingFiles, spawnRunner, } from "./enforce-misses-collect.js";
46
51
  function parseArgs(argv) {
47
52
  const args = argv.slice(2);
48
53
  const flags = {};
@@ -86,6 +91,12 @@ Default command:
86
91
  ${command}
87
92
  \`\`\`
88
93
 
94
+ Use it instead of choosing test files yourself and instead of re-running the full suite:
95
+
96
+ - Run it once after each change and before every commit. Do not pick individual test files to run instead; a hand-picked set misses tests that depend on your change through imports, fixtures and scripts.
97
+ - Do not run the full test suite to be safe. DiffCI already falls back to the full suite when it cannot prove a smaller set is enough, and says why in \`reason\`.
98
+ - When the MCP server is available, \`diffci_select_tests\` returns the one exact \`command\` to run; run that command as given.
99
+
89
100
  What this does:
90
101
 
91
102
  - snapshots staged, unstaged, and non-ignored untracked changes;
@@ -94,6 +105,7 @@ What this does:
94
105
  - emits a versioned machine-readable receipt and sends nothing.
95
106
 
96
107
  If verification changes generated files, review those changes and rerun DiffCI so the new snapshot is verified.
108
+ If the repository has the DiffCI pre-push hook (\`diffci init --hook\`), a push verifies the pushed commits again; do not bypass it with \`--no-verify\` unless the user asks.
97
109
  Use \`observe --no-send\` when analysis without test execution is needed.
98
110
 
99
111
  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.
@@ -264,6 +276,8 @@ function runInit(flags, env) {
264
276
  if (includeVerificationWorkflow) {
265
277
  writes.push(writeInitFile(repoPath, ".github/workflows/diffci-verify.yml", diffciVerificationWorkflow(identity.version), force));
266
278
  }
279
+ if (flags.hook === true)
280
+ writes.push(installPrePushHook(repoPath, hookCommand(manager, identity.version), force));
267
281
  console.log(`DiffCI initialized for AI coding agents in ${repoPath}`);
268
282
  for (const write of writes)
269
283
  console.log(` ${write}`);
@@ -271,11 +285,14 @@ function runInit(flags, env) {
271
285
  console.log(` ${installed}`);
272
286
  else
273
287
  console.log(" skipped package installation (pass --install to add an exact dev dependency)");
288
+ if (flags.hook !== true)
289
+ console.log(" skipped the pre-push hook (pass --hook to verify pushed commits before every push)");
274
290
  if (!includeWorkflow)
275
291
  console.log(" skipped .github/workflows/diffci.yml (pass --workflow to add it)");
276
292
  if (!includeVerificationWorkflow)
277
293
  console.log(" skipped .github/workflows/diffci-verify.yml (pass --verification-workflow to add it)");
278
294
  console.log(`\nDefault agent command: ${agentCommand}`);
295
+ console.log("\nOptional telemetry is off unless you have opted in. Use diffci telemetry --mode anonymous for execution counts, or --mode installations to also share a random installation ID. No repository content is sent. Use --mode off to disable; --no-send always overrides consent.");
279
296
  return 0;
280
297
  }
281
298
  function runMcp() {
@@ -297,6 +314,15 @@ async function runVerifyCommand(flags, env) {
297
314
  console.error("diffci verify accepts either --changed or --base/--head, not both");
298
315
  return 2;
299
316
  }
317
+ const policy = flags.policy === true ? "" : stringFlag(flags, "policy");
318
+ if (policy !== undefined && policy !== "enforce") {
319
+ console.error(`diffci verify --policy accepts only "enforce", got ${JSON.stringify(policy)}`);
320
+ return 2;
321
+ }
322
+ if (policy !== undefined && changed) {
323
+ console.error("diffci verify --policy enforce applies to a commit range, not --changed");
324
+ return 2;
325
+ }
300
326
  const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
301
327
  const out = stringFlag(flags, "out");
302
328
  const reportPath = out ? resolve(out) : undefined;
@@ -321,7 +347,9 @@ async function runVerifyCommand(flags, env) {
321
347
  ...common,
322
348
  baseOverride: stringFlag(flags, "base"),
323
349
  headOverride: stringFlag(flags, "head"),
350
+ policy,
324
351
  });
352
+ await recordUsage("verify", report.verification, identity.version, flags, env);
325
353
  if (reportPath) {
326
354
  mkdirSync(dirname(reportPath), { recursive: true });
327
355
  writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
@@ -404,9 +432,7 @@ async function runCheck(flags, env) {
404
432
  if (observationCode !== 0)
405
433
  return observationCode;
406
434
  const observation = JSON.parse(readFileSync(reportPath, "utf8"));
407
- if ((flags["share-usage"] === true || env.DIFFCI_SHARE_USAGE === "1") && flags["no-send"] !== true) {
408
- await sendUsageSignal({ command: "check", outcome: observation.status === "OBSERVED" ? "observed" : observation.status === "REFUSED" ? "refused" : "error", version: observerIdentity().version });
409
- }
435
+ await recordUsage("check", observation.status === "OBSERVED" ? "observed" : observation.status === "REFUSED" ? "refused" : "error", observerIdentity().version, flags, env);
410
436
  const print = (message) => { if (flags.quiet !== true && flags.json !== true)
411
437
  console.log(message); };
412
438
  print(summarise(observation, true));
@@ -531,9 +557,7 @@ async function runObserve(flags, env) {
531
557
  });
532
558
  mkdirSync(dirname(reportPath), { recursive: true });
533
559
  writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
534
- if ((flags["share-usage"] === true || env.DIFFCI_SHARE_USAGE === "1") && flags["no-send"] !== true) {
535
- await sendUsageSignal({ command: "observe", outcome: report.status === "OBSERVED" ? "observed" : report.status === "REFUSED" ? "refused" : "error", version: identity.version });
536
- }
560
+ await recordUsage("observe", report.status === "OBSERVED" ? "observed" : report.status === "REFUSED" ? "refused" : "error", identity.version, flags, env);
537
561
  const summary = summarise(report);
538
562
  if (flags.json === true) {
539
563
  console.log(JSON.stringify(report, null, 2));
@@ -615,6 +639,93 @@ function runVerifyWorkflow(flags, env) {
615
639
  console.log("\nBlocking findings above: as written, this installation CAN change what the rest of CI does.");
616
640
  return 1;
617
641
  }
642
+ /**
643
+ * Miss detection (docs/enforce-mode-01-plan.md, step 5). Exit 0: no miss. Exit 1: at least one miss.
644
+ * Exit 2: the full run left no results to classify, or the invocation is wrong. It never edits
645
+ * diffci.config.json or repository variables; it prints the entries for a human to add.
646
+ */
647
+ function runEnforceMisses(flags, env) {
648
+ const repoPath = resolve(stringFlag(flags, "repo") ?? env.GITHUB_WORKSPACE ?? process.cwd());
649
+ const junitPath = stringFlag(flags, "junit");
650
+ const outFlag = stringFlag(flags, "out-dir");
651
+ const repository = stringFlag(flags, "repository") ?? env.GITHUB_REPOSITORY;
652
+ if (!junitPath || !outFlag || !repository) {
653
+ console.error("diffci enforce-misses needs --junit <file>, --out-dir <dir> and --repository <owner/name> (or GITHUB_REPOSITORY)");
654
+ return 2;
655
+ }
656
+ const outDir = resolve(outFlag);
657
+ if (outDir === repoPath || isInsideRepository(repoPath, outDir)) {
658
+ console.error(`Refusing to write the miss report inside the repository: ${outDir}. Use --out-dir outside the checkout.`);
659
+ return 2;
660
+ }
661
+ if (!existsSync(junitPath)) {
662
+ console.error(`No full-suite results at ${junitPath}: nothing can be classified, so no miss can be ruled out.`);
663
+ return 2;
664
+ }
665
+ const headSha = stringFlag(flags, "head") ?? execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoPath, encoding: "utf8" }).trim();
666
+ const fullRun = parseJunit(readFileSync(junitPath, "utf8"), repoPath);
667
+ const failing = fullRun.filter((outcome) => outcome.failed);
668
+ const runUrl = env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL ?? "https://github.com"}/${repository}/actions/runs/${env.GITHUB_RUN_ID}` : undefined;
669
+ const notes = [];
670
+ let report;
671
+ if (failing.length === 0) {
672
+ // A green run is the cheapest case and the most common one: no GitHub calls, and its record
673
+ // (no failures) becomes the next run's window start.
674
+ report = buildMissReport({ fullRun, rerun: undefined, baseline: [], pullRequests: [], headSha, producedAt: new Date().toISOString(), runUrl, window: { from_sha: null, source: "none" } });
675
+ }
676
+ else {
677
+ const rerunJunit = stringFlag(flags, "rerun-junit");
678
+ const rerunArgs = inferRerunArgs(repoPath);
679
+ const files = [...new Set(failing.map((outcome) => outcome.file).filter(Boolean))];
680
+ const rerun = rerunJunit
681
+ ? parseJunit(readFileSync(rerunJunit, "utf8"), repoPath)
682
+ : rerunArgs && files.length > 0 ? rerunFailingFiles(repoPath, rerunArgs, files) : undefined;
683
+ if (!rerun)
684
+ notes.push("failures were not re-run, so none could be ruled flaky; every failure was treated as deterministic");
685
+ const collect = {
686
+ repoPath,
687
+ repository,
688
+ headSha,
689
+ runId: env.GITHUB_RUN_ID,
690
+ workDir: join(outDir, "downloads"),
691
+ run: spawnRunner,
692
+ };
693
+ const window = findWindowStart(collect);
694
+ if (!window.fromSha)
695
+ notes.push("no earlier detector record or green full run was found, so no pull request could be held against these failures");
696
+ const pullRequests = mergedPullRequests(collect, window.fromSha).map((pr) => ({ ...pr, receipt: findReceipt(collect, pr) }));
697
+ report = buildMissReport({
698
+ fullRun,
699
+ rerun,
700
+ baseline: window.baseline,
701
+ pullRequests,
702
+ headSha,
703
+ producedAt: new Date().toISOString(),
704
+ runUrl,
705
+ window: { from_sha: window.fromSha, source: window.source },
706
+ notes,
707
+ });
708
+ }
709
+ mkdirSync(outDir, { recursive: true });
710
+ const markdown = formatMissReportMarkdown(report);
711
+ writeFileSync(join(outDir, MISS_REPORT_FILE), `${JSON.stringify(report, null, 2)}
712
+ `, "utf8");
713
+ writeFileSync(join(outDir, "enforce-misses.md"), markdown, "utf8");
714
+ console.log(markdown);
715
+ if (report.misses === 0)
716
+ return 0;
717
+ console.log("Add to enforce.openUnsafeMisses in diffci.config.json (not done automatically):");
718
+ console.log(JSON.stringify(report.open_unsafe_misses, null, 2));
719
+ if (flags["open-issue"] === true) {
720
+ const title = `DiffCI enforce: unsafe miss on main at ${headSha.slice(0, 12)}`;
721
+ const created = spawnRunner("gh", ["issue", "create", "--repo", repository, "--title", title, "--body-file", join(outDir, "enforce-misses.md")]);
722
+ if (created.ok)
723
+ console.log(`Opened ${created.stdout.trim()}`);
724
+ else
725
+ console.error(`Could not open an issue (${created.stderr.trim()}); the report is in ${outDir}.`);
726
+ }
727
+ return 1;
728
+ }
618
729
  function stringFlag(flags, name) {
619
730
  const value = flags[name];
620
731
  return typeof value === "string" ? value : undefined;
@@ -809,10 +920,11 @@ Open-source engine: https://github.com/DiffCI/core
809
920
  Pilot a repository: https://diffci.com/#pilot
810
921
 
811
922
  Usage:
812
- diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--force]
923
+ diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--hook] [--force]
813
924
  diffci mcp
814
- diffci verify [--changed | --base <sha> --head <sha>] [--repo <path>] [--out <file>] [--json]
815
- [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure]
925
+ diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
926
+ [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--share-usage] [--no-send]
927
+ diffci telemetry [--mode off|anonymous|installations] [--internal-usage]
816
928
  diffci check [--repo <path>] [--out <file>] [--base <sha> --head <sha>]
817
929
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
818
930
  diffci pilot --full <command> [--selected <command>] [--repo <path>] [--out-dir <dir>] [--label <name>]
@@ -828,6 +940,8 @@ Usage:
828
940
  [--cache-prepare <command>] [--fixed-order]
829
941
  diffci validate-specs --file <json> [--json]
830
942
  diffci verify-workflow [--repo <path>]
943
+ diffci enforce-misses --junit <file> --out-dir <dir> [--repository <owner/name>] [--repo <path>]
944
+ [--head <sha>] [--rerun-junit <file>] [--open-issue]
831
945
  diffci version
832
946
 
833
947
  init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json.
@@ -835,6 +949,8 @@ init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci
835
949
  or Bun, installs this DiffCI version as an exact dev dependency, updates the manager's lockfile,
836
950
  and adds diffci:verify, diffci:check, and diffci:observe package scripts without replacing existing scripts.
837
951
  --verification-workflow adds a blocking GitHub check that uploads a commit-bound verification receipt.
952
+ --hook installs a Git pre-push hook that runs diffci verify on the commits being pushed and blocks the push
953
+ when verification fails (git push --no-verify skips it; DIFFCI_HOOK_STRICT=1 also blocks when it cannot verify).
838
954
  mcp runs the stdio MCP server for native agent integrations.
839
955
  verify --changed snapshots staged, unstaged, and non-ignored untracked changes, runs the minimum
840
956
  executable verification (or full fallback), and exits zero only when that exact snapshot passes.
@@ -848,13 +964,27 @@ observe analyses the checkout and writes one JSON report. It runs nothing and ch
848
964
  verify-savings runs both commands and reports measured paired runtime; it is an opt-in pilot command.
849
965
  validate-specs checks an explicit list of specification IDs and logical targets and blocks duplicates.
850
966
  verify-workflow checks that the job running DiffCI cannot affect any other job, and exits 1 if it can.
967
+ enforce-misses classifies a full run's failures on main against the enforce dry-run receipts of the pull
968
+ requests merged since the last recorded run, and exits 1 on a miss. It never edits configuration.
969
+ Failures are re-run with the package.json tsx --test runner, or read from --rerun-junit for other runners.
851
970
 
852
971
  The report is sent only when both --api-url and --api-token are given (or DIFFCI_API_URL and
853
972
  DIFFCI_TOKEN are set). A failed send is reported and never fails the step - the report is on disk
854
973
  either way. Plain http is refused; the token is never printed.
855
- --share-usage (or DIFFCI_SHARE_USAGE=1) sends only command, outcome, and version to DiffCI.
856
- No repository, commit, test, report, or persistent identifier is sent. --no-send disables it.
974
+ --share-usage (or DIFFCI_SHARE_USAGE=1) opts in to command, outcome, version, surface and activity reporting.
975
+ diffci telemetry --mode anonymous saves consent; --mode installations also shares a random local installation ID.
976
+ --mode off disables saved consent and deletes the ID. --internal-usage labels tests/internal activity.
977
+ No repository, commit, test, report, paths, or machine details are sent. --no-send or DIFFCI_NO_SEND=1 disables it.
978
+ Interactive check and observe runs print feedback links to stderr at most weekly; they send nothing.
979
+ CI, MCP, --json and --quiet never show them; DIFFCI_NO_FEEDBACK_PROMPT=1 hides them.
857
980
  `;
981
+ function maybeShowFeedbackPrompt(flags, env) {
982
+ if (!shouldShowFeedbackPrompt(flags, env, process.stderr.isTTY === true))
983
+ return;
984
+ // stderr keeps piped stdout unchanged.
985
+ console.error(formatFeedbackPrompt(readTelemetryPreference(env).mode));
986
+ markFeedbackPromptShown(env);
987
+ }
858
988
  async function main() {
859
989
  const { command, flags } = parseArgs(process.argv);
860
990
  const env = process.env;
@@ -864,6 +994,14 @@ async function main() {
864
994
  return;
865
995
  }
866
996
  switch (command) {
997
+ case "telemetry": {
998
+ const mode = stringFlag(flags, "mode");
999
+ const preference = mode ? configureTelemetry(mode, flags["internal-usage"] === true, env) : readTelemetryPreference(env);
1000
+ console.log(`DiffCI telemetry: ${preference.mode}; activity: ${preference.internal ? "internal" : "external"}.`);
1001
+ console.log("Reporting includes command, outcome, version, surface and activity. Installation mode adds a random local ID; installations are not people. No repository content or machine details are sent. --no-send always overrides consent.");
1002
+ process.exitCode = 0;
1003
+ return;
1004
+ }
867
1005
  case "init":
868
1006
  process.exitCode = runInit(flags, env);
869
1007
  return;
@@ -875,6 +1013,7 @@ async function main() {
875
1013
  return;
876
1014
  case "check":
877
1015
  process.exitCode = await runCheck(flags, env);
1016
+ maybeShowFeedbackPrompt(flags, env);
878
1017
  return;
879
1018
  case "pilot":
880
1019
  process.exitCode = await runPilot(flags, env);
@@ -884,6 +1023,7 @@ async function main() {
884
1023
  return;
885
1024
  case "observe":
886
1025
  process.exitCode = await runObserve(flags, env);
1026
+ maybeShowFeedbackPrompt(flags, env);
887
1027
  return;
888
1028
  case "verify-savings":
889
1029
  process.exitCode = runVerifySavingsCommand(flags, env);
@@ -894,6 +1034,9 @@ async function main() {
894
1034
  case "verify-workflow":
895
1035
  process.exitCode = runVerifyWorkflow(flags, env);
896
1036
  return;
1037
+ case "enforce-misses":
1038
+ process.exitCode = runEnforceMisses(flags, env);
1039
+ return;
897
1040
  case "version":
898
1041
  console.log(observerIdentity().version);
899
1042
  return;
@@ -22,7 +22,7 @@ import { existsSync, readFileSync } from "node:fs";
22
22
  /** Triggers that carry no inherent "what changed" - a range for these would have to be invented. */
23
23
  const SYNTHETIC_TRIGGERS = new Set(["schedule", "workflow_dispatch", "repository_dispatch", "release"]);
24
24
  const ZERO_SHA = "0000000000000000000000000000000000000000";
25
- function readEventPayload(env) {
25
+ export function readEventPayload(env) {
26
26
  const path = env.GITHUB_EVENT_PATH;
27
27
  if (!path || !existsSync(path))
28
28
  return undefined;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * The side effects of miss detection (docs/enforce-mode-01-plan.md, step 5): finding the window, the
3
+ * pull requests merged in it, their dry-run receipts, and re-running the failing test files. GitHub is
4
+ * reached only through the `gh` CLI, and every external call goes through an injectable runner.
5
+ *
6
+ * The window starts at the most recent earlier run of the detector itself (its uploaded report lists
7
+ * the failures that were already there), or, before the first such run exists, at the last green
8
+ * `ci.yml` push run on `main`. Either commit must be an ancestor of the commit being checked.
9
+ */
10
+ import { spawnSync } from "node:child_process";
11
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
12
+ import { createRequire } from "node:module";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { MISS_REPORT_SCHEMA, parseJunit } from "./enforce-misses.js";
16
+ import { VERIFICATION_SCHEMA } from "./verify.js";
17
+ export const DRY_RUN_ARTIFACT_PREFIX = "diffci-enforce-dry-run-";
18
+ export const MISS_RECORD_ARTIFACT_PREFIX = "diffci-enforce-misses-";
19
+ export const MISS_REPORT_FILE = "enforce-misses.json";
20
+ const DRY_RUN_RECEIPT_FILE = "diffci-enforce-dry-run.json";
21
+ export const spawnRunner = (executable, args, options = {}) => {
22
+ const result = spawnSync(executable, args, { cwd: options.cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
23
+ return { ok: result.status === 0, stdout: result.stdout ?? "", stderr: result.stderr ?? result.error?.message ?? "" };
24
+ };
25
+ function ghJson(options, path) {
26
+ const result = options.run("gh", ["api", path]);
27
+ if (!result.ok)
28
+ return undefined;
29
+ try {
30
+ return JSON.parse(result.stdout);
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ }
36
+ function isAncestor(options, ancestor) {
37
+ return options.run("git", ["merge-base", "--is-ancestor", ancestor, options.headSha], { cwd: options.repoPath }).ok;
38
+ }
39
+ function workflowRuns(options, workflow, query) {
40
+ return ghJson(options, `repos/${options.repository}/actions/workflows/${workflow}/runs?${query}`)?.workflow_runs ?? [];
41
+ }
42
+ function runArtifacts(options, runId, prefix) {
43
+ const artifacts = ghJson(options, `repos/${options.repository}/actions/runs/${runId}/artifacts?per_page=100`)?.artifacts ?? [];
44
+ return artifacts.filter((artifact) => !artifact.expired && artifact.name.startsWith(prefix));
45
+ }
46
+ /** Download one artifact and parse the named JSON file from it. */
47
+ function downloadJson(options, runId, artifact, file) {
48
+ mkdirSync(options.workDir, { recursive: true });
49
+ const directory = mkdtempSync(join(options.workDir, "artifact-"));
50
+ const result = options.run("gh", ["run", "download", String(runId), "--repo", options.repository, "--name", artifact, "--dir", directory]);
51
+ if (!result.ok)
52
+ return undefined;
53
+ const path = join(directory, file);
54
+ if (!existsSync(path))
55
+ return undefined;
56
+ try {
57
+ return JSON.parse(readFileSync(path, "utf8"));
58
+ }
59
+ catch {
60
+ return undefined;
61
+ }
62
+ }
63
+ export function findWindowStart(options) {
64
+ const detector = options.detectorWorkflow ?? "diffci-enforce-misses.yml";
65
+ for (const run of workflowRuns(options, detector, "branch=main&status=completed&per_page=30")) {
66
+ if (String(run.id) === options.runId || !isAncestor(options, run.head_sha))
67
+ continue;
68
+ for (const artifact of runArtifacts(options, run.id, MISS_RECORD_ARTIFACT_PREFIX)) {
69
+ const record = downloadJson(options, run.id, artifact.name, MISS_REPORT_FILE);
70
+ if (record?.schema === MISS_REPORT_SCHEMA && Array.isArray(record.deterministic_failures)) {
71
+ return { fromSha: run.head_sha, source: "detector-record", baseline: record.deterministic_failures };
72
+ }
73
+ }
74
+ }
75
+ const fullSuite = options.fullSuiteWorkflow ?? "ci.yml";
76
+ for (const run of workflowRuns(options, fullSuite, "branch=main&event=push&status=success&per_page=30")) {
77
+ if (isAncestor(options, run.head_sha))
78
+ return { fromSha: run.head_sha, source: "green-full-run", baseline: [] };
79
+ }
80
+ return { fromSha: null, source: "none", baseline: [] };
81
+ }
82
+ /** Pull requests merged into `main` by the first-parent commits after `fromSha`, oldest first. */
83
+ export function mergedPullRequests(options, fromSha) {
84
+ if (!fromSha)
85
+ return [];
86
+ const listed = options.run("git", ["rev-list", "--first-parent", "--reverse", `${fromSha}..${options.headSha}`], { cwd: options.repoPath });
87
+ if (!listed.ok)
88
+ return [];
89
+ const commits = listed.stdout.split(/\s+/).filter(Boolean).slice(-(options.maxCommits ?? 100));
90
+ const found = new Map();
91
+ for (const sha of commits) {
92
+ for (const pull of ghJson(options, `repos/${options.repository}/commits/${sha}/pulls`) ?? []) {
93
+ if (!pull.merged_at || pull.base?.ref !== "main" || !pull.head?.sha || found.has(pull.number))
94
+ continue;
95
+ found.set(pull.number, { number: pull.number, title: pull.title, mergeSha: sha, headSha: pull.head.sha });
96
+ }
97
+ }
98
+ return [...found.values()];
99
+ }
100
+ /** The newest dry-run receipt recorded for the pull request's final head commit. */
101
+ export function findReceipt(options, pr) {
102
+ const workflow = options.dryRunWorkflow ?? "diffci-enforce-dry-run.yml";
103
+ for (const run of workflowRuns(options, workflow, `head_sha=${pr.headSha}&per_page=20`)) {
104
+ for (const artifact of runArtifacts(options, run.id, `${DRY_RUN_ARTIFACT_PREFIX}${pr.number}-`)) {
105
+ const report = downloadJson(options, run.id, artifact.name, DRY_RUN_RECEIPT_FILE);
106
+ if (report?.schema === VERIFICATION_SCHEMA)
107
+ return { artifact: artifact.name, report };
108
+ }
109
+ }
110
+ return undefined;
111
+ }
112
+ /**
113
+ * Node arguments that re-run test files the way package.json's `tsx --test` script runs them: tsx's own
114
+ * CLI under this Node, so no shell and no `.cmd` shim is involved and test paths stay literal argv.
115
+ */
116
+ export function inferRerunArgs(repoPath) {
117
+ try {
118
+ const script = JSON.parse(readFileSync(join(repoPath, "package.json"), "utf8")).scripts?.test;
119
+ if (typeof script !== "string")
120
+ return undefined;
121
+ const runners = [...script.matchAll(/\btsx(?:\s+--conditions\s+([\w,-]+))?\s+--test\b/g)];
122
+ if (runners.length !== 1)
123
+ return undefined;
124
+ const cli = createRequire(join(repoPath, "package.json")).resolve("tsx/cli");
125
+ const conditions = runners[0][1];
126
+ return [cli, ...(conditions ? ["--conditions", conditions] : []), "--test"];
127
+ }
128
+ catch {
129
+ return undefined;
130
+ }
131
+ }
132
+ /**
133
+ * Re-run only the failing files with node:test's JUnit reporter, set through NODE_OPTIONS so the runner
134
+ * arguments stay what package.json declares. Returns undefined when no result file was written.
135
+ */
136
+ export function rerunFailingFiles(repoPath, runnerArgs, files) {
137
+ const directory = mkdtempSync(join(tmpdir(), "diffci-misses-rerun-"));
138
+ const junit = join(directory, "rerun.junit.xml");
139
+ try {
140
+ spawnSync(process.execPath, [...runnerArgs, ...files], {
141
+ cwd: repoPath,
142
+ stdio: "inherit",
143
+ env: {
144
+ ...process.env,
145
+ NODE_OPTIONS: [process.env.NODE_OPTIONS, "--test-reporter=spec", "--test-reporter-destination=stdout", "--test-reporter=junit", `--test-reporter-destination=${junit}`]
146
+ .filter(Boolean)
147
+ .join(" "),
148
+ },
149
+ });
150
+ if (!existsSync(junit))
151
+ return undefined;
152
+ return parseJunit(readFileSync(junit, "utf8"), repoPath);
153
+ }
154
+ finally {
155
+ rmSync(directory, { recursive: true, force: true });
156
+ }
157
+ }