@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
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Enforce mode miss detection (docs/enforce-mode-01-plan.md, step 5).
3
+ *
4
+ * After a full run on `main`, every failing test is held against the enforce receipts of the pull
5
+ * requests merged since the last full run that was recorded. A MISS is a test that fails on `main`,
6
+ * fails again when re-run, was not failing before those pull requests merged, and was left out by a
7
+ * pull request whose receipt says `selection: "selected"`. That is exactly the failure enforce mode
8
+ * would have let through.
9
+ *
10
+ * Everything here is pure: parsing, classification and the report. GitHub, git and the re-run live in
11
+ * `enforce-misses-collect.ts`, so each classification can be tested without a repository or a token.
12
+ *
13
+ * Nothing here changes configuration. A miss produces the exact `enforce.openUnsafeMisses` entry for
14
+ * a human to add; re-enabling enforcement is never automatic.
15
+ */
16
+ import { isAbsolute, relative, resolve } from "node:path";
17
+ export const MISS_REPORT_SCHEMA = "diffci.enforce-misses.v1";
18
+ // ---------------------------------------------------------------------------------------------------
19
+ // JUnit (node:test's `--test-reporter=junit`, which also matches the common Jest/Vitest shape)
20
+ function decodeEntities(text) {
21
+ return text.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (_, entity) => {
22
+ const lower = entity.toLowerCase();
23
+ if (lower.startsWith("#x"))
24
+ return String.fromCodePoint(Number.parseInt(lower.slice(2), 16));
25
+ if (lower.startsWith("#"))
26
+ return String.fromCodePoint(Number.parseInt(lower.slice(1), 10));
27
+ return { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" }[lower];
28
+ });
29
+ }
30
+ function attributes(source) {
31
+ const result = {};
32
+ for (const match of source.matchAll(/([\w:.-]+)\s*=\s*"([^"]*)"/g))
33
+ result[match[1]] = decodeEntities(match[2]);
34
+ return result;
35
+ }
36
+ /** Repository-relative with forward slashes; paths outside the repository stay absolute. */
37
+ export function normalizeTestPath(path, repoRoot) {
38
+ const slashed = path.replace(/\\/g, "/").replace(/^\.\//, "");
39
+ if (!slashed)
40
+ return "";
41
+ if (!isAbsolute(path))
42
+ return slashed;
43
+ const inside = relative(resolve(repoRoot), resolve(path));
44
+ return inside && !inside.startsWith("..") && !isAbsolute(inside) ? inside.replace(/\\/g, "/") : slashed;
45
+ }
46
+ /** Testcases in document order, named by their enclosing suites. Repeated ids are merged: any failure wins. */
47
+ export function parseJunit(xml, repoRoot) {
48
+ const byId = new Map();
49
+ const suites = [];
50
+ let current;
51
+ const finish = () => {
52
+ if (!current)
53
+ return;
54
+ const seen = byId.get(current.id);
55
+ if (seen) {
56
+ seen.failed ||= current.failed;
57
+ seen.skipped &&= current.skipped;
58
+ }
59
+ else
60
+ byId.set(current.id, current);
61
+ current = undefined;
62
+ };
63
+ // Attribute values may hold a raw `>` (failure messages), so the tag body skips over quoted strings.
64
+ const tags = /<(\/?)(testsuite|testcase|failure|error|skipped)\b((?:[^>"]|"[^"]*")*?)(\/?)>/g;
65
+ for (const [, closing, tag, body, selfClosing] of xml.matchAll(tags)) {
66
+ if (tag === "testsuite") {
67
+ if (closing)
68
+ suites.pop();
69
+ else if (!selfClosing)
70
+ suites.push(attributes(body).name ?? "");
71
+ }
72
+ else if (tag === "testcase") {
73
+ if (closing) {
74
+ finish();
75
+ continue;
76
+ }
77
+ finish();
78
+ const attrs = attributes(body);
79
+ const file = normalizeTestPath(attrs.file ?? "", repoRoot);
80
+ const name = [...suites, attrs.name ?? ""].filter(Boolean).join(" > ");
81
+ current = { id: `${file} > ${name}`, file, name, failed: attrs.failure !== undefined, skipped: false };
82
+ if (selfClosing)
83
+ finish();
84
+ }
85
+ else if (current && !closing) {
86
+ if (tag === "skipped")
87
+ current.skipped = true;
88
+ else
89
+ current.failed = true;
90
+ }
91
+ }
92
+ finish();
93
+ return [...byId.values()];
94
+ }
95
+ // ---------------------------------------------------------------------------------------------------
96
+ // Receipts
97
+ const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/;
98
+ function normalizeSelected(path) {
99
+ return path.replace(/\\/g, "/").replace(/^\.\//, "");
100
+ }
101
+ /**
102
+ * The test files a `selected` receipt ran. Receipts from before `selected_tests` existed fall back to the
103
+ * test-file arguments of the command. `undefined` means the receipt does not say.
104
+ */
105
+ export function selectedFiles(report) {
106
+ if (Array.isArray(report.selected_tests))
107
+ return new Set(report.selected_tests.map(normalizeSelected));
108
+ const fromCommand = (report.command ?? "")
109
+ .split(/\s+/)
110
+ .map((token) => normalizeSelected(token.replace(/^["']|["']$/g, "")))
111
+ .filter((token) => TEST_FILE.test(token));
112
+ return fromCommand.length > 0 ? new Set(fromCommand) : undefined;
113
+ }
114
+ function verdict(pr, file) {
115
+ const report = pr.receipt?.report;
116
+ if (!report)
117
+ return "no-receipt";
118
+ if (report.selection === "full")
119
+ return "ran-full";
120
+ if (report.selection !== "selected")
121
+ return "no-tests-run";
122
+ const files = selectedFiles(report);
123
+ if (!files)
124
+ return "selection-unrecorded";
125
+ return files.has(file) ? "selected" : "missed";
126
+ }
127
+ export function classifyFailures(input) {
128
+ const rerun = new Map((input.rerun ?? []).map((outcome) => [outcome.id, outcome]));
129
+ const baseline = new Set(input.baseline);
130
+ return input.fullRun
131
+ .filter((outcome) => outcome.failed)
132
+ .map((outcome) => {
133
+ const base = { id: outcome.id, file: outcome.file, name: outcome.name };
134
+ const again = rerun.get(outcome.id);
135
+ if (again && !again.failed && !again.skipped) {
136
+ return { ...base, classification: "flaky", pull_requests: [], detail: "passed when re-run" };
137
+ }
138
+ // Not found in the re-run (or no re-run at all) is treated as deterministic: "cannot tell" must
139
+ // never be what keeps a miss from being counted.
140
+ const rerunNote = !input.rerun ? "not re-run" : again ? "failed again when re-run" : "absent from the re-run";
141
+ if (baseline.has(outcome.id)) {
142
+ return { ...base, classification: "pre-existing", pull_requests: [], detail: `already failing at the start of the window; ${rerunNote}` };
143
+ }
144
+ const pullRequests = input.pullRequests.map((pr) => ({
145
+ number: pr.number,
146
+ verdict: verdict(pr, outcome.file),
147
+ ...(pr.receipt ? { artifact: pr.receipt.artifact } : {}),
148
+ }));
149
+ const skippedBy = pullRequests.filter((pr) => pr.verdict === "missed" || pr.verdict === "selection-unrecorded");
150
+ if (skippedBy.length > 0) {
151
+ return {
152
+ ...base,
153
+ classification: "miss",
154
+ pull_requests: pullRequests,
155
+ detail: `${rerunNote}; not selected by ${skippedBy.map((pr) => `#${pr.number}`).join(", ")}`,
156
+ };
157
+ }
158
+ if (pullRequests.every((pr) => pr.verdict === "no-receipt" || pr.verdict === "no-tests-run")) {
159
+ return { ...base, classification: "unattributed", pull_requests: pullRequests, detail: `${rerunNote}; no merged pull request in the window ran or skipped it` };
160
+ }
161
+ return { ...base, classification: "covered", pull_requests: pullRequests, detail: `${rerunNote}; every pull request with a receipt ran it` };
162
+ });
163
+ }
164
+ export function unsafeMissEntries(failures, context) {
165
+ return failures
166
+ .filter((failure) => failure.classification === "miss")
167
+ .flatMap((failure) => failure.pull_requests
168
+ .filter((pr) => pr.verdict === "missed" || pr.verdict === "selection-unrecorded")
169
+ .map((pr) => ({
170
+ test: failure.id,
171
+ pullRequest: pr.number,
172
+ receipt: pr.artifact ?? null,
173
+ mainSha: context.headSha,
174
+ detectedAt: context.detectedAt,
175
+ ...(context.runUrl ? { run: context.runUrl } : {}),
176
+ })));
177
+ }
178
+ export function buildMissReport(input) {
179
+ const failures = classifyFailures(input);
180
+ const open = unsafeMissEntries(failures, { headSha: input.headSha, detectedAt: input.producedAt, runUrl: input.runUrl });
181
+ return {
182
+ schema: MISS_REPORT_SCHEMA,
183
+ produced_at: input.producedAt,
184
+ head_sha: input.headSha,
185
+ ...(input.runUrl ? { run_url: input.runUrl } : {}),
186
+ full_suite: input.fullRun.some((outcome) => outcome.failed) ? "failed" : "passed",
187
+ rerun: input.rerun ? "done" : "not-run",
188
+ window: input.window,
189
+ pull_requests: input.pullRequests.map((pr) => ({
190
+ number: pr.number,
191
+ merge_sha: pr.mergeSha,
192
+ head_sha: pr.headSha,
193
+ receipt: pr.receipt?.artifact ?? null,
194
+ selection: pr.receipt?.report.selection ?? null,
195
+ })),
196
+ deterministic_failures: failures.filter((failure) => failure.classification !== "flaky").map((failure) => failure.id),
197
+ failures,
198
+ misses: failures.filter((failure) => failure.classification === "miss").length,
199
+ open_unsafe_misses: open,
200
+ notes: input.notes ?? [],
201
+ };
202
+ }
203
+ const CLASS_ORDER = ["miss", "unattributed", "pre-existing", "covered", "flaky"];
204
+ export function formatMissReportMarkdown(report) {
205
+ const lines = [
206
+ report.misses > 0 ? `# DiffCI enforce: ${report.misses} unsafe miss(es) on main` : "# DiffCI enforce: no misses on main",
207
+ "",
208
+ `- main: \`${report.head_sha}\`${report.run_url ? ` ([run](${report.run_url}))` : ""}`,
209
+ `- full suite: ${report.full_suite}; re-run of failures: ${report.rerun}`,
210
+ `- window: ${report.window.from_sha ? `\`${report.window.from_sha.slice(0, 12)}..${report.head_sha.slice(0, 12)}\`` : "none found"} (${report.window.source})`,
211
+ `- merged pull requests: ${report.pull_requests.length === 0 ? "none" : report.pull_requests.map((pr) => `#${pr.number} (${pr.selection ?? "no receipt"})`).join(", ")}`,
212
+ ];
213
+ for (const note of report.notes)
214
+ lines.push(`- note: ${note}`);
215
+ for (const classification of CLASS_ORDER) {
216
+ const group = report.failures.filter((failure) => failure.classification === classification);
217
+ if (group.length === 0)
218
+ continue;
219
+ lines.push("", `## ${classification} (${group.length})`, "");
220
+ for (const failure of group) {
221
+ const prs = failure.pull_requests.map((pr) => `#${pr.number}: ${pr.verdict}`).join(", ");
222
+ lines.push(`- \`${failure.id}\` - ${failure.detail}${prs ? ` [${prs}]` : ""}`);
223
+ }
224
+ }
225
+ if (report.open_unsafe_misses.length > 0) {
226
+ lines.push("", "## What to do", "", "Enforce mode must stop skipping tests until a human has looked at this. Add these entries to", "`enforce.openUnsafeMisses` in `diffci.config.json` (fallback 4 then forces the full suite), and turn", "the `DIFFCI_ENFORCE` repository variable off if enforcement is live. Nothing was changed automatically;", "clearing the entries is the deliberate step that re-enables enforcement.", "", "```json", JSON.stringify(report.open_unsafe_misses, null, 2), "```");
227
+ }
228
+ return `${lines.join("\n")}\n`;
229
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Enforce mode, Level 1 (docs/enforce-mode-01-plan.md, step 1).
3
+ *
4
+ * Shadow mode only predicts. Enforce mode lets `diffci verify` run the selected tests INSTEAD of the
5
+ * full suite - so every way the selection could be wrong has to be answered here with "run FULL", never
6
+ * with "run less". The checks are ordered: repository-level conditions first (is enforcement on at all,
7
+ * approved, not demoted), then per-run conditions (is this range and this analysis trustworthy). The
8
+ * first one that fires is recorded in the receipt; nothing after it is evaluated.
9
+ *
10
+ * `evaluateEnforcement` is pure. Everything that touches git, the event payload or the environment is
11
+ * in `collectEnforcementContext`, so each fallback can be tested without a repository.
12
+ */
13
+ import { extname } from "node:path";
14
+ import { readEventPayload } from "./context.js";
15
+ /** The only policy shape this CLI understands. A newer or older `enforce` block falls back to FULL. */
16
+ export const ENFORCE_POLICY_VERSION = 1;
17
+ export const FORCE_FULL_LABEL = "diffci:force-full";
18
+ export const ENFORCE_VARIABLE = "DIFFCI_ENFORCE";
19
+ /**
20
+ * Paths whose change can affect every test without appearing in the import graph. The analyzer already
21
+ * falls back for many of these; enforce mode lists them again because here a gap costs a missed failure,
22
+ * not a mis-scored prediction.
23
+ */
24
+ const GLOBAL_RISK_PATTERNS = [
25
+ /^\.github\//,
26
+ /(?:^|\/)package\.json$/,
27
+ /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|bun\.lockb?)$/,
28
+ /(?:^|\/)\.(?:npmrc|nvmrc|node-version|tool-versions)$/,
29
+ /(?:^|\/)tsconfig(?:\.[^/]+)?\.json$/,
30
+ /(?:^|\/)(?:jest|vitest|vite|playwright|cypress|mocha|ava|karma|babel)\.config\.[^/]+$/,
31
+ /(?:^|\/)\.(?:mocharc|babelrc)(?:\.[^/]+)?$/,
32
+ /(?:^|\/)diffci(?:\.config)?\.json$/,
33
+ ];
34
+ const DOC_DIRECTORIES = ["docs", "doc", "documentation"];
35
+ /** Same rule as RepositoryLayout.isDocumentationPath, without needing a repository profile. */
36
+ function isDocumentationPath(path) {
37
+ const ext = extname(path).toLowerCase();
38
+ if (ext === ".md" || ext === ".mdx")
39
+ return true;
40
+ const first = path.split("/")[0];
41
+ return first !== undefined && DOC_DIRECTORIES.includes(first.toLowerCase());
42
+ }
43
+ function policyProblem(policy) {
44
+ if (policy === undefined)
45
+ return "diffci.config.json at the range base has no `enforce` block";
46
+ if (policy === null || typeof policy !== "object" || Array.isArray(policy))
47
+ return "`enforce` must be an object";
48
+ const block = policy;
49
+ if (block.policyVersion !== ENFORCE_POLICY_VERSION) {
50
+ return `enforce.policyVersion is ${JSON.stringify(block.policyVersion)}; this DiffCI supports ${ENFORCE_POLICY_VERSION}`;
51
+ }
52
+ if (block.level !== 1)
53
+ return `enforce.level is ${JSON.stringify(block.level)}; only level 1 is implemented`;
54
+ if (typeof block.approvedBy !== "string" || block.approvedBy.trim() === "")
55
+ return "enforce.approvedBy is missing";
56
+ if (typeof block.approvedAt !== "string" || Number.isNaN(Date.parse(block.approvedAt)))
57
+ return "enforce.approvedAt is not a date";
58
+ if (block.openUnsafeMisses !== undefined && !Array.isArray(block.openUnsafeMisses))
59
+ return "enforce.openUnsafeMisses must be an array";
60
+ return undefined;
61
+ }
62
+ function openMisses(policy) {
63
+ const misses = policy.openUnsafeMisses;
64
+ return Array.isArray(misses) ? misses : [];
65
+ }
66
+ /** Matches a `DiffCI: full` trailer line anywhere in the head commit message. */
67
+ export function hasForceFullTrailer(message) {
68
+ return message !== undefined && /^diffci:\s*full\s*$/im.test(message);
69
+ }
70
+ export function evaluateEnforcement(context, observation) {
71
+ const decide = (fired, detail) => ({
72
+ policy: "enforce",
73
+ policy_version: ENFORCE_POLICY_VERSION,
74
+ fired_fallback: fired,
75
+ detail,
76
+ });
77
+ if (context.killSwitch !== "on")
78
+ return decide("kill-switch", `${ENFORCE_VARIABLE} is not "on"`);
79
+ if (context.pullRequestLabels.includes(FORCE_FULL_LABEL))
80
+ return decide("per-run-override", `pull request is labelled ${FORCE_FULL_LABEL}`);
81
+ if (hasForceFullTrailer(context.headCommitMessage))
82
+ return decide("per-run-override", "head commit carries a `DiffCI: full` trailer");
83
+ const problem = policyProblem(context.policy);
84
+ if (problem)
85
+ return decide("policy-not-approved", problem);
86
+ const misses = openMisses(context.policy);
87
+ if (misses.length > 0)
88
+ return decide("open-unsafe-miss", `${misses.length} unsafe miss(es) recorded and not yet cleared`);
89
+ if (!context.range.trusted)
90
+ return decide("untrusted-range", context.range.reason);
91
+ const result = observation.result;
92
+ if (observation.status !== "OBSERVED" || !result) {
93
+ return decide("analysis-failure", observation.reason ?? `analysis status ${observation.status}`);
94
+ }
95
+ const confidence = result.graph.effectiveConfidence ?? result.graph.confidence;
96
+ if (confidence !== "COMPLETE")
97
+ return decide("graph-confidence", `effective graph confidence is ${confidence}, not COMPLETE`);
98
+ if (context.pathsRedacted)
99
+ return decide("global-risk", "changed paths are redacted, so global-risk paths cannot be checked");
100
+ const critical = result.riskSignals.find((signal) => signal.level === "critical");
101
+ if (critical)
102
+ return decide("global-risk", `critical risk signal: ${critical.reason}`);
103
+ if (result.mode === "FULL")
104
+ return decide("global-risk", `analyzer required full validation: ${result.fallbackReasons[0] ?? "no reason given"}`);
105
+ const risky = result.changedFiles.find((path) => GLOBAL_RISK_PATTERNS.some((pattern) => pattern.test(path)));
106
+ if (risky)
107
+ return decide("global-risk", `global-risk path changed: ${risky}`);
108
+ if (result.selectedTests.length === 0 && result.changedFiles.some((path) => !isDocumentationPath(path))) {
109
+ return decide("empty-selection", "source files changed but no tests were selected");
110
+ }
111
+ return decide(null, "every enforce check passed");
112
+ }
113
+ function git(runner, args) {
114
+ const result = runner(args);
115
+ return result.ok ? result.stdout : undefined;
116
+ }
117
+ function rangeTrust(runner, range) {
118
+ if (!range)
119
+ return { trusted: false, reason: "no commit range was resolved" };
120
+ // A head-parent range covers one commit, not the whole push or branch it stands in for.
121
+ if (range.source === "head-parent")
122
+ return { trusted: false, reason: "range is the head commit's parent, not the full push" };
123
+ if (git(runner, ["rev-parse", "--is-shallow-repository"])?.trim() !== "false") {
124
+ return { trusted: false, reason: "checkout is shallow; use fetch-depth: 0" };
125
+ }
126
+ // Force-pushes leave `before` off the new history; a diff from it is not "what this push changed".
127
+ if (git(runner, ["merge-base", "--is-ancestor", range.baseSha, range.headSha]) === undefined) {
128
+ return { trusted: false, reason: `base ${range.baseSha.slice(0, 12)} is not an ancestor of head ${range.headSha.slice(0, 12)}` };
129
+ }
130
+ return { trusted: true };
131
+ }
132
+ function policyAtBase(runner, range) {
133
+ if (!range)
134
+ return undefined;
135
+ const text = git(runner, ["show", `${range.baseSha}:diffci.config.json`]);
136
+ if (text === undefined)
137
+ return undefined;
138
+ try {
139
+ const parsed = JSON.parse(text);
140
+ return parsed !== null && typeof parsed === "object" ? parsed.enforce : undefined;
141
+ }
142
+ catch {
143
+ return undefined;
144
+ }
145
+ }
146
+ function pullRequestLabels(env) {
147
+ const payload = readEventPayload(env);
148
+ const pullRequest = payload?.pull_request;
149
+ if (pullRequest === null || typeof pullRequest !== "object")
150
+ return [];
151
+ const labels = pullRequest.labels;
152
+ if (!Array.isArray(labels))
153
+ return [];
154
+ return labels.flatMap((label) => {
155
+ const name = label !== null && typeof label === "object" ? label.name : undefined;
156
+ return typeof name === "string" ? [name] : [];
157
+ });
158
+ }
159
+ export function collectEnforcementContext(runner, env, observation) {
160
+ const range = observation.commitRange;
161
+ return {
162
+ killSwitch: env[ENFORCE_VARIABLE],
163
+ pullRequestLabels: pullRequestLabels(env),
164
+ headCommitMessage: range ? git(runner, ["log", "-1", "--format=%B", range.headSha]) : undefined,
165
+ policy: policyAtBase(runner, range),
166
+ range: rangeTrust(runner, range),
167
+ pathsRedacted: observation.payload.pathRedaction !== undefined,
168
+ };
169
+ }
@@ -0,0 +1,42 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { preferencePath } from "./telemetry.js";
4
+ /** Interactive runs only; CI, agents and machine-readable output never see it. At most once a week. */
5
+ const INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
6
+ function stampPath(env) {
7
+ return join(dirname(preferencePath(env)), "feedback-prompt.json");
8
+ }
9
+ export function shouldShowFeedbackPrompt(flags, env, interactive, now = Date.now()) {
10
+ if (!interactive || flags.json === true || flags.quiet === true)
11
+ return false;
12
+ if (env.CI || env.GITHUB_ACTIONS || env.DIFFCI_MCP === "1" || env.DIFFCI_NO_FEEDBACK_PROMPT === "1")
13
+ return false;
14
+ try {
15
+ const last = JSON.parse(readFileSync(stampPath(env), "utf8")).shownAt;
16
+ if (typeof last === "number" && now - last < INTERVAL_MS)
17
+ return false;
18
+ }
19
+ catch { /* Never shown, or unreadable: show it. */ }
20
+ return true;
21
+ }
22
+ export function formatFeedbackPrompt(telemetry) {
23
+ const lines = [
24
+ "",
25
+ "Using DiffCI on a real repository? We read every reply:",
26
+ " tell us how it went: https://github.com/DiffCI/core/discussions",
27
+ " volunteer a pilot: https://diffci.com/#pilot",
28
+ " star the engine: https://github.com/DiffCI/core",
29
+ ];
30
+ if (telemetry === "off")
31
+ lines.push(" share anonymous run counts: diffci telemetry --mode anonymous (no repository content)");
32
+ lines.push("Shown at most weekly; DIFFCI_NO_FEEDBACK_PROMPT=1 hides it.");
33
+ return lines.join("\n");
34
+ }
35
+ export function markFeedbackPromptShown(env, now = Date.now()) {
36
+ try {
37
+ const path = stampPath(env);
38
+ mkdirSync(dirname(path), { recursive: true });
39
+ writeFileSync(path, `${JSON.stringify({ shownAt: now })}\n`, { encoding: "utf8", mode: 0o600 });
40
+ }
41
+ catch { /* A read-only home only means the prompt may repeat. */ }
42
+ }
@@ -0,0 +1,94 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, relative } from "node:path";
4
+ /**
5
+ * The pre-push hook `diffci init --hook` installs (2026-10-28).
6
+ *
7
+ * WHY. In 449 agent sessions on DentalPresence, agents ran DiffCI in 24 of over 1,500 test commands:
8
+ * they picked test files themselves (928) or ran the whole suite (282), and 104 pushes then failed the
9
+ * repository gates in CI. Instructions alone did not make DiffCI the default. A hook does: every push,
10
+ * by an agent or a person, verifies the commits being pushed before they leave the machine.
11
+ *
12
+ * BEHAVIOUR. For each pushed ref that is the checked-out HEAD, the hook runs
13
+ * `diffci verify --base <remote sha> --head <local sha>` (a new branch uses its merge base with the
14
+ * remote's default branch). Failing verification (exit 1) blocks the push. When DiffCI cannot verify
15
+ * (exit 2: dirty checkout, unknown base, analysis refused) it says why and lets the push through,
16
+ * because required CI still runs; `DIFFCI_HOOK_STRICT=1` blocks instead. `git push --no-verify` skips it.
17
+ */
18
+ export const HOOK_MARKER = "# diffci:managed pre-push hook";
19
+ export function prePushHook(command) {
20
+ return `#!/bin/sh
21
+ ${HOOK_MARKER}
22
+ # Verifies the commits being pushed with DiffCI's affected tests. Skip once: git push --no-verify
23
+ # Block when DiffCI cannot verify, not only when tests fail: DIFFCI_HOOK_STRICT=1
24
+ remote="$1"
25
+ zero=0000000000000000000000000000000000000000
26
+ head=$(git rev-parse HEAD)
27
+ status=0
28
+ while read -r local_ref local_sha remote_ref remote_sha; do
29
+ [ "$local_sha" = "$zero" ] && continue
30
+ if [ "$local_sha" != "$head" ]; then
31
+ echo "diffci: $local_ref is not checked out; not verified here" >&2
32
+ continue
33
+ fi
34
+ base="$remote_sha"
35
+ if [ "$base" = "$zero" ] || ! git cat-file -e "$base^{commit}" 2>/dev/null; then
36
+ base=$(git merge-base HEAD "refs/remotes/$remote/HEAD" 2>/dev/null || true)
37
+ fi
38
+ if [ -z "$base" ] || [ "$base" = "$local_sha" ]; then
39
+ echo "diffci: no base commit for $local_ref; not verified" >&2
40
+ continue
41
+ fi
42
+ echo "diffci: verifying $base..$local_sha before push" >&2
43
+ ${command} verify --base "$base" --head "$local_sha" </dev/null
44
+ code=$?
45
+ if [ "$code" -eq 1 ]; then
46
+ echo "diffci: verification failed; push blocked. Fix it, or skip once with git push --no-verify" >&2
47
+ status=1
48
+ elif [ "$code" -ne 0 ]; then
49
+ if [ "$DIFFCI_HOOK_STRICT" = "1" ]; then
50
+ echo "diffci: could not verify (exit $code); push blocked because DIFFCI_HOOK_STRICT=1" >&2
51
+ status=1
52
+ else
53
+ echo "diffci: could not verify (exit $code); pushing anyway, required CI still runs" >&2
54
+ fi
55
+ fi
56
+ done
57
+ exit $status
58
+ `;
59
+ }
60
+ /** The command the hook runs: the installed binary when the repository has DiffCI as a dependency,
61
+ * otherwise a pinned npx invocation, so the hook never floats to a newer release. */
62
+ export function hookCommand(manager, version) {
63
+ switch (manager) {
64
+ case "npm": return "npx --no-install diffci";
65
+ case "pnpm": return "pnpm exec diffci";
66
+ case "yarn": return "yarn diffci";
67
+ case "bun": return "bunx diffci";
68
+ default: return `npx --yes "@diffci.com/diffci@${version}"`;
69
+ }
70
+ }
71
+ /** Writes the hook into the directory Git actually runs hooks from (`core.hooksPath` included, such as
72
+ * `.husky`). An existing hook DiffCI did not write is kept unless `force` is set. */
73
+ export function installPrePushHook(repoPath, command, force) {
74
+ const hooksDir = execFileSync("git", ["rev-parse", "--git-path", "hooks"], { cwd: repoPath, encoding: "utf8", windowsHide: true }).trim();
75
+ const absoluteDir = isAbsolute(hooksDir) ? hooksDir : join(repoPath, hooksDir);
76
+ const hookPath = join(absoluteDir, "pre-push");
77
+ const shown = relative(repoPath, hookPath).replace(/\\/g, "/") || hookPath;
78
+ const content = prePushHook(command);
79
+ if (existsSync(hookPath)) {
80
+ const existing = readFileSync(hookPath, "utf8");
81
+ if (existing === content)
82
+ return `kept ${shown} (current)`;
83
+ if (!existing.includes(HOOK_MARKER) && !force) {
84
+ return `kept ${shown} (existing hook not written by DiffCI; add \`${command} verify --base <remote-sha> --head <local-sha>\` to it, or pass --force)`;
85
+ }
86
+ }
87
+ mkdirSync(dirname(hookPath), { recursive: true });
88
+ writeFileSync(hookPath, content, "utf8");
89
+ try {
90
+ chmodSync(hookPath, 0o755);
91
+ }
92
+ catch { /* Git for Windows runs hooks through sh regardless of mode. */ }
93
+ return `wrote ${shown} (verifies pushed commits; skip once with git push --no-verify)`;
94
+ }
@@ -2,7 +2,7 @@
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
+ import { agentChangedFiles, agentSelection, selectionInstruction } from "./agent-selection.js";
6
6
  import { requireDiffciPackageIdentity } from "./package-identity.js";
7
7
  const SERVER_INFO = { name: "diffci-mcp", version: requireDiffciPackageIdentity().version };
8
8
  const tools = [
@@ -53,7 +53,7 @@ const tools = [
53
53
  },
54
54
  {
55
55
  name: "diffci_check",
56
- description: "Analyze the repository, run inferred full and selected test commands when available, and report paired runtime. Sends nothing to DiffCI Cloud.",
56
+ description: "Analyze the repository, run inferred full and selected test commands when available, and report paired runtime. No report is uploaded. Optional aggregate telemetry follows the user's saved consent; DIFFCI_NO_SEND=1 overrides it.",
57
57
  inputSchema: {
58
58
  type: "object",
59
59
  properties: {
@@ -76,6 +76,7 @@ const tools = [
76
76
  repo: { type: "string", description: "Repository path. Defaults to the MCP server working directory." },
77
77
  workflow: { type: "boolean", description: "Also add the non-blocking GitHub Actions observer workflow." },
78
78
  verificationWorkflow: { type: "boolean", description: "Also add the blocking GitHub Actions verification workflow." },
79
+ hook: { type: "boolean", description: "Also install a Git pre-push hook that verifies the commits being pushed." },
79
80
  force: { type: "boolean", description: "Overwrite existing instruction files." },
80
81
  },
81
82
  additionalProperties: false,
@@ -159,6 +160,8 @@ function commandForTool(name, args) {
159
160
  command.push("--workflow");
160
161
  if (booleanArg(args, "verificationWorkflow"))
161
162
  command.push("--verification-workflow");
163
+ if (booleanArg(args, "hook"))
164
+ command.push("--hook");
162
165
  if (booleanArg(args, "force"))
163
166
  command.push("--force");
164
167
  return command;
@@ -239,8 +242,13 @@ async function handle(request) {
239
242
  }
240
243
  if (["diffci_changed_files", "diffci_select_tests", "diffci_explain_selection"].includes(params.name)) {
241
244
  const repo = stringArg(args, "repo") ?? process.cwd();
242
- const plan = params.name === "diffci_changed_files" ? agentChangedFiles(repo) : await agentSelection(repo);
243
- success(id, { content: [{ type: "text", text: JSON.stringify(plan) }], structuredContent: plan, isError: plan.status === "blocked" });
245
+ if (params.name === "diffci_changed_files") {
246
+ const changes = agentChangedFiles(repo);
247
+ success(id, { content: [{ type: "text", text: JSON.stringify(changes) }], structuredContent: changes, isError: changes.status === "blocked" });
248
+ return;
249
+ }
250
+ const plan = await agentSelection(repo);
251
+ success(id, { content: [{ type: "text", text: `${selectionInstruction(plan)}\n\n${JSON.stringify(plan)}` }], structuredContent: plan, isError: plan.status === "blocked" });
244
252
  return;
245
253
  }
246
254
  const run = await runCli(commandForTool(params.name, args));
@@ -28,7 +28,7 @@ import { OBSERVATION_SCHEMA, readTypeScriptProgramMetrics, redactPath, } from ".
28
28
  import { auditWorkflows } from "./workflow-guard.js";
29
29
  /** Build output and dependencies are never sources of truth about a repository's own structure. */
30
30
  const EXCLUDE_DIRS = ["node_modules", ".next", "dist", "build"];
31
- function makeGitRunner(repoPath) {
31
+ export function makeGitRunner(repoPath) {
32
32
  return (args) => {
33
33
  try {
34
34
  const stdout = execFileSync("git", args, {
@@ -191,10 +191,14 @@ export async function observe(options) {
191
191
  });
192
192
  }
193
193
  const profile = graphResult.profile;
194
- const impact = new ImpactAnalyzer().analyze(delta, graphResult, profile, {
194
+ // `selectTestPhases` and `testPhases` are newer than some bundled engines; an engine without them
195
+ // ignores the option and never returns phases, so it keeps falling back.
196
+ const analyzeOptions = {
195
197
  repositoryFiles: deltaResult.inventory?.files,
196
198
  readRepositoryFile: repositoryFileReader(repoPath),
197
- });
199
+ selectTestPhases: options.selectTestPhases === true,
200
+ };
201
+ const impact = new ImpactAnalyzer().analyze(delta, graphResult, profile, analyzeOptions);
198
202
  const baseline = runPathBaseline(profile.testFilePaths, delta.files, profile);
199
203
  const selectedTests = impact.affectedTests.map((test) => test.path).sort();
200
204
  // The comparator's own identities, sorted and redacted identically so the two arms of an economics
@@ -221,6 +225,7 @@ export async function observe(options) {
221
225
  } : {}),
222
226
  fallbackReasons: impact.fallbackReasons,
223
227
  proposedCommands: (commandPlan?.commands ?? []).map(commandSpecToString),
228
+ ...(impact.testPhases?.length ? { testPhases: [...impact.testPhases] } : {}),
224
229
  workspaceCommands: Boolean(profile.workspaceTestPackages?.length),
225
230
  goScope: profile.diffciConfig?.go?.scope,
226
231
  vueScope: profile.vueScope ? { packageRoot: hashPath(profile.vueScope.packageRoot), testConfig: hashPath(profile.vueScope.testConfig) } : undefined,