@diffci.com/diffci 0.3.14 → 0.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -661
- package/README.md +1 -1
- package/dist-client/src/client/cli.js +140 -11
- package/dist-client/src/client/context.js +1 -1
- package/dist-client/src/client/enforce-misses-collect.js +157 -0
- package/dist-client/src/client/enforce-misses.js +229 -0
- package/dist-client/src/client/enforce-policy.js +169 -0
- package/dist-client/src/client/feedback-prompt.js +42 -0
- package/dist-client/src/client/mcp.js +1 -1
- package/dist-client/src/client/observe.js +1 -1
- package/dist-client/src/client/telemetry.js +46 -0
- package/dist-client/src/client/usage-signal.js +17 -10
- package/dist-client/src/client/verify.js +29 -5
- package/package.json +5 -3
|
@@ -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
|
+
}
|
|
@@ -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.
|
|
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: {
|
|
@@ -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, {
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { deliverUsageSignal } from "./usage-signal.js";
|
|
6
|
+
export function preferencePath(env) {
|
|
7
|
+
return join(env.DIFFCI_TELEMETRY_HOME ?? join(homedir(), ".diffci"), "telemetry.json");
|
|
8
|
+
}
|
|
9
|
+
export function readTelemetryPreference(env) {
|
|
10
|
+
try {
|
|
11
|
+
const value = JSON.parse(readFileSync(preferencePath(env), "utf8"));
|
|
12
|
+
if (!["off", "anonymous", "installations"].includes(value.mode))
|
|
13
|
+
throw new Error("invalid preference");
|
|
14
|
+
if (value.mode === "installations" && !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.installationId ?? ""))
|
|
15
|
+
throw new Error("invalid identifier");
|
|
16
|
+
return { mode: value.mode, internal: value.internal === true, ...(value.mode === "installations" ? { installationId: value.installationId } : {}) };
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return { mode: "off", internal: false };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function configureTelemetry(mode, internal, env) {
|
|
23
|
+
if (!["off", "anonymous", "installations"].includes(mode))
|
|
24
|
+
throw new Error("Choose off, anonymous, or installations.");
|
|
25
|
+
const previous = readTelemetryPreference(env);
|
|
26
|
+
const value = { mode: mode, internal,
|
|
27
|
+
...(mode === "installations" ? { installationId: previous.installationId ?? randomUUID() } : {}) };
|
|
28
|
+
const path = preferencePath(env);
|
|
29
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
30
|
+
writeFileSync(path, `${JSON.stringify(value)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
export async function recordUsage(command, outcome, version, flags, env) {
|
|
34
|
+
// Explicit denial overrides saved consent and every opt-in route.
|
|
35
|
+
if (flags["no-send"] === true || env.DIFFCI_SHARE_USAGE === "0" || env.DIFFCI_NO_SEND === "1")
|
|
36
|
+
return;
|
|
37
|
+
const preference = readTelemetryPreference(env);
|
|
38
|
+
if (flags["share-usage"] !== true && env.DIFFCI_SHARE_USAGE !== "1" && preference.mode === "off")
|
|
39
|
+
return;
|
|
40
|
+
const result = await deliverUsageSignal({ command, outcome, version,
|
|
41
|
+
surface: env.DIFFCI_MCP === "1" ? "local-mcp" : "cli",
|
|
42
|
+
activity: flags["internal-usage"] === true || env.DIFFCI_USAGE_INTERNAL === "1" || preference.internal ? "internal" : "external",
|
|
43
|
+
...(preference.mode === "installations" ? { installationId: preference.installationId } : {}),
|
|
44
|
+
});
|
|
45
|
+
console.error(`DiffCI telemetry: ${result.status}${result.httpStatus ? ` (HTTP ${result.httpStatus})` : ""}. No repository content sent.`);
|
|
46
|
+
}
|
|
@@ -1,18 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
export async function sendUsageSignal(input) {
|
|
3
|
-
const url = new URL(input.endpoint ?? "https://app.diffci.com/v1/usage-events");
|
|
4
|
-
if (url.protocol !== "https:")
|
|
5
|
-
return false;
|
|
1
|
+
export async function deliverUsageSignal(input) {
|
|
6
2
|
try {
|
|
3
|
+
const url = new URL(input.endpoint ?? "https://app.diffci.com/v1/usage-events");
|
|
4
|
+
if (url.protocol !== "https:")
|
|
5
|
+
return { status: "failed" };
|
|
7
6
|
const response = await (input.fetchImpl ?? fetch)(url, {
|
|
8
7
|
method: "POST",
|
|
9
8
|
headers: { "Content-Type": "application/json" },
|
|
10
|
-
body: JSON.stringify({ schema: "diffci.usage.v1", command: input.command, outcome: input.outcome, version: input.version
|
|
11
|
-
|
|
9
|
+
body: JSON.stringify({ schema: "diffci.usage.v1", command: input.command, outcome: input.outcome, version: input.version,
|
|
10
|
+
...(input.surface ? { surface: input.surface } : {}),
|
|
11
|
+
...(input.activity ? { activity: input.activity } : {}),
|
|
12
|
+
...(input.installationId ? { installation_id: input.installationId } : {}),
|
|
13
|
+
}),
|
|
14
|
+
signal: AbortSignal.timeout(5000),
|
|
12
15
|
});
|
|
13
|
-
return response.ok;
|
|
16
|
+
return { status: !response.ok ? "failed" : response.status === 202 ? "accepted" : "delivered", httpStatus: response.status };
|
|
14
17
|
}
|
|
15
|
-
catch {
|
|
16
|
-
return
|
|
18
|
+
catch (error) {
|
|
19
|
+
return { status: error instanceof Error && error.name === "TimeoutError" ? "timed-out" : "failed" };
|
|
17
20
|
}
|
|
18
21
|
}
|
|
22
|
+
export async function sendUsageSignal(input) {
|
|
23
|
+
const result = await deliverUsageSignal(input);
|
|
24
|
+
return result.status === "delivered" || result.status === "accepted";
|
|
25
|
+
}
|
|
@@ -3,8 +3,9 @@ import { tmpdir } from "node:os";
|
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
4
|
import { batchCommand, measureCommands } from "./command-batches.js";
|
|
5
5
|
import { compareWithBaseline } from "./failure-baseline.js";
|
|
6
|
+
import { collectEnforcementContext, evaluateEnforcement } from "./enforce-policy.js";
|
|
6
7
|
import { inferFullCommand, inferSelectedCommand } from "./full-command.js";
|
|
7
|
-
import { observe } from "./observe.js";
|
|
8
|
+
import { makeGitRunner, observe } from "./observe.js";
|
|
8
9
|
import { captureWorkingTreeSnapshot } from "./working-tree.js";
|
|
9
10
|
export const VERIFICATION_SCHEMA = "diffci.verification.v1";
|
|
10
11
|
function receiptRange(range) {
|
|
@@ -49,6 +50,18 @@ function unknownSnapshot() {
|
|
|
49
50
|
return { baseSha: "unknown", treeSha: "unknown", commitSha: "unknown", changed: true };
|
|
50
51
|
}
|
|
51
52
|
async function executeObservation(options, scope, before, observation) {
|
|
53
|
+
const enforcement = options.policy === "enforce"
|
|
54
|
+
? evaluateEnforcement(collectEnforcementContext(makeGitRunner(options.repoPath), options.env, observation), observation)
|
|
55
|
+
: undefined;
|
|
56
|
+
const report = await executeWithPolicy(options, scope, before, observation, enforcement);
|
|
57
|
+
if (!enforcement)
|
|
58
|
+
return report;
|
|
59
|
+
return { ...report, enforcement: { ...enforcement, applied: enforcement.fired_fallback === null && report.selection === "selected" } };
|
|
60
|
+
}
|
|
61
|
+
async function executeWithPolicy(options, scope, before, observation, enforcement) {
|
|
62
|
+
// Under enforce, a fired fallback runs the full suite even where plain verify would block: an
|
|
63
|
+
// unusable analysis is a reason to run everything, never a reason to pass with nothing run.
|
|
64
|
+
const enforcedFull = enforcement !== undefined && enforcement.fired_fallback !== null;
|
|
52
65
|
const result = observation.result;
|
|
53
66
|
const range = observation.commitRange;
|
|
54
67
|
const boundRange = scope === "commit-range" ? range : undefined;
|
|
@@ -66,13 +79,13 @@ async function executeObservation(options, scope, before, observation) {
|
|
|
66
79
|
...(observation.timings?.totalMs !== undefined ? { duration_ms: observation.timings.totalMs } : {}),
|
|
67
80
|
...(result?.graph ? { graph_confidence: result.graph.confidence, effective_graph_confidence: result.graph.effectiveConfidence } : {}),
|
|
68
81
|
};
|
|
69
|
-
if (observation.status !== "OBSERVED" || !result) {
|
|
82
|
+
if ((observation.status !== "OBSERVED" || !result) && !enforcedFull) {
|
|
70
83
|
return blocked(before, scope, observation.reason ?? "DiffCI analysis did not produce a verification plan", analysis, counts, boundRange);
|
|
71
84
|
}
|
|
72
85
|
if (scope === "commit-range") {
|
|
73
|
-
if (!range)
|
|
86
|
+
if (!range && !enforcedFull)
|
|
74
87
|
return blocked(before, scope, "DiffCI did not resolve a commit range", analysis, counts);
|
|
75
|
-
if (range.headSha !== before.baseSha) {
|
|
88
|
+
if (range && range.headSha !== before.baseSha) {
|
|
76
89
|
return blocked(before, scope, `the analyzed head ${range.headSha} is not the checked-out HEAD ${before.baseSha}`, analysis, counts, range);
|
|
77
90
|
}
|
|
78
91
|
}
|
|
@@ -90,7 +103,9 @@ async function executeObservation(options, scope, before, observation) {
|
|
|
90
103
|
report.snapshot.after_tree_sha = afterAnalysis.treeSha;
|
|
91
104
|
return report;
|
|
92
105
|
}
|
|
93
|
-
const { selection, command, commands, reason, outsideSuite } =
|
|
106
|
+
const { selection, command, commands, reason, outsideSuite } = enforcedFull || !result
|
|
107
|
+
? fullSelection(options.repoPath, `enforce fallback (${enforcement?.fired_fallback}): ${enforcement?.detail}`)
|
|
108
|
+
: executableSelection(options.repoPath, result);
|
|
94
109
|
if (!command) {
|
|
95
110
|
const inferred = inferFullCommand(options.repoPath);
|
|
96
111
|
return blocked(before, scope, `no executable verification command is available: ${inferred.reason}`, analysis, counts, boundRange);
|
|
@@ -137,6 +152,7 @@ async function executeObservation(options, scope, before, observation) {
|
|
|
137
152
|
tests_selected: selection === "full" ? counts.testsAvailable : counts.testsSelected,
|
|
138
153
|
...(outsideSuite ? { tests_outside_full_suite: outsideSuite } : {}),
|
|
139
154
|
selection,
|
|
155
|
+
...(selection === "selected" && result ? { selected_tests: result.selectedTests } : {}),
|
|
140
156
|
command,
|
|
141
157
|
...(commands.length > 1 ? { commands } : {}),
|
|
142
158
|
execution,
|
|
@@ -262,8 +278,16 @@ export function formatVerificationSummary(report) {
|
|
|
262
278
|
lines.splice(2, 0, ` range: ${report.commit_range.base_sha.slice(0, 12)}..${report.commit_range.head_sha.slice(0, 12)}`);
|
|
263
279
|
if (report.command)
|
|
264
280
|
lines.push(` command: ${report.command}`);
|
|
281
|
+
if (report.enforcement) {
|
|
282
|
+
const fired = report.enforcement.fired_fallback;
|
|
283
|
+
lines.push(` enforce: ${report.enforcement.applied ? "applied" : fired ? `fell back to full (${fired}: ${report.enforcement.detail})` : "not applied"}`);
|
|
284
|
+
}
|
|
265
285
|
return lines.join("\n");
|
|
266
286
|
}
|
|
287
|
+
function fullSelection(repoPath, reason) {
|
|
288
|
+
const command = inferFullCommand(repoPath).command;
|
|
289
|
+
return { selection: "full", command, commands: command ? [command] : [], reason, outsideSuite: 0 };
|
|
290
|
+
}
|
|
267
291
|
/** Shared executable plan for read-only agent selection and verification. */
|
|
268
292
|
export function executableSelection(repoPath, result) {
|
|
269
293
|
let selection;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@diffci.com/diffci",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.15",
|
|
4
4
|
"description": "Fail-closed, change-aware verification for AI coding agents with conservative affected-test selection",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ci",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"affected-tests",
|
|
21
21
|
"github-actions"
|
|
22
22
|
],
|
|
23
|
-
"license": "
|
|
23
|
+
"license": "MIT",
|
|
24
24
|
"mcpName": "io.github.DiffCI/diffci",
|
|
25
25
|
"repository": {
|
|
26
26
|
"type": "git",
|
|
@@ -55,7 +55,8 @@
|
|
|
55
55
|
"build:client": "tsc -p tsconfig.client.json && node scripts/ensure-client-executables.mjs",
|
|
56
56
|
"prepack": "npm run build:client",
|
|
57
57
|
"package:check": "node scripts/check-package-boundary.mjs",
|
|
58
|
-
"package:smoke": "node scripts/package-smoke.mjs"
|
|
58
|
+
"package:smoke": "node scripts/package-smoke.mjs",
|
|
59
|
+
"test": "node scripts/run-tests.mjs"
|
|
59
60
|
},
|
|
60
61
|
"dependencies": {
|
|
61
62
|
"@diffci.com/core": "git+https://github.com/DiffCI/core.git#e7ffdaf103800e71d74375afe4bc82604953bf19",
|
|
@@ -63,6 +64,7 @@
|
|
|
63
64
|
},
|
|
64
65
|
"devDependencies": {
|
|
65
66
|
"@types/node": "^22.15.12",
|
|
67
|
+
"tsx": "^4.23.15",
|
|
66
68
|
"typescript": "^5.8.3"
|
|
67
69
|
},
|
|
68
70
|
"bundleDependencies": [
|