@diffci.com/diffci 0.3.30 → 0.3.32
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/dist-client/src/client/agent-setup.d.ts +18 -0
- package/dist-client/src/client/agent-setup.js +77 -0
- package/dist-client/src/client/agent-stop.d.ts +52 -0
- package/dist-client/src/client/agent-stop.js +101 -0
- package/dist-client/src/client/cli.js +102 -7
- package/dist-client/src/client/command-batches.d.ts +5 -0
- package/dist-client/src/client/command-batches.js +9 -0
- package/dist-client/src/client/coverage-map.d.ts +46 -0
- package/dist-client/src/client/coverage-map.js +213 -0
- package/dist-client/src/client/failure-baseline.js +0 -0
- package/dist-client/src/client/hook.d.ts +1 -1
- package/dist-client/src/client/hook.js +1 -1
- package/dist-client/src/client/job-summary.d.ts +7 -0
- package/dist-client/src/client/job-summary.js +78 -0
- package/dist-client/src/client/observe.js +3 -0
- package/dist-client/src/client/report.d.ts +3 -0
- package/dist-client/src/client/verify.d.ts +6 -0
- package/dist-client/src/client/verify.js +43 -4
- package/dist-client/src/client/working-tree.d.ts +13 -0
- package/dist-client/src/client/working-tree.js +40 -1
- package/node_modules/@diffci.com/core/dist/git/git-diff.js +59 -0
- package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/git/types.d.ts +4 -0
- package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +11 -0
- package/node_modules/@diffci.com/core/dist/planner/test-command.js +65 -9
- package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +10 -1
- package/node_modules/@diffci.com/core/dist/repo/file-references.js +57 -16
- package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +3 -0
- package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +7 -0
- package/node_modules/@diffci.com/core/dist/repo/impact.js +43 -16
- package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.d.ts +1 -1
- package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.js +48 -5
- package/node_modules/@diffci.com/core/dist/repo/test-fixture-ownership.js.map +1 -1
- package/node_modules/@diffci.com/core/src/git/git-diff.ts +48 -0
- package/node_modules/@diffci.com/core/src/git/types.ts +4 -0
- package/node_modules/@diffci.com/core/src/planner/test-command.ts +54 -9
- package/node_modules/@diffci.com/core/src/repo/file-references.ts +60 -18
- package/node_modules/@diffci.com/core/src/repo/impact-types.ts +3 -0
- package/node_modules/@diffci.com/core/src/repo/impact.ts +39 -16
- package/node_modules/@diffci.com/core/src/repo/test-fixture-ownership.ts +39 -5
- package/package.json +2 -2
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { isAbsolute, join, relative, sep } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { outcomeLogPath } from "./outcome-log.js";
|
|
6
|
+
import { measureCommand } from "./verify-savings.js";
|
|
7
|
+
/**
|
|
8
|
+
* The coverage map (2026-11-06), the idea of Datadog Test Impact Analysis and pytest-testmon.
|
|
9
|
+
*
|
|
10
|
+
* WHY. The dependency graph sees imports. A test also reaches files it never imports: a fixture it reads
|
|
11
|
+
* by name, a directory it lists, a module loaded through a computed specifier or a framework. Those edges
|
|
12
|
+
* are the commonest reason a change runs the full suite, and the ones static analysis cannot find.
|
|
13
|
+
*
|
|
14
|
+
* WHAT. `diffci coverage` runs the full test command once with every `node --test` process (one per test
|
|
15
|
+
* file) under a probe and V8 coverage. The probe records the files the test reads and the directories it
|
|
16
|
+
* lists; V8 coverage records every module it loads, ESM included. The result, per test file, is kept in
|
|
17
|
+
* `<git common dir>/diffci/coverage-map.json` beside the outcome log, never committed and never sent.
|
|
18
|
+
*
|
|
19
|
+
* Phase A, the only use so far: a verify run adds the tests whose map entry names a changed file and the
|
|
20
|
+
* graph did not select. Adding a test is always safe, so a stale map costs time, never a miss. Replacing
|
|
21
|
+
* a full-suite fallback with what the map says (phase B) waits until a replay shows it loses no catches.
|
|
22
|
+
* Only node:test is supported: Vitest and Jest run many files in one worker, so reads cannot be told apart.
|
|
23
|
+
*/
|
|
24
|
+
export const COVERAGE_MAP_SCHEMA = "diffci.coverage-map.v1";
|
|
25
|
+
const PROBE = `"use strict";
|
|
26
|
+
if (process.env.NODE_TEST_CONTEXT && process.argv[1] && process.env.DIFFCI_COVERAGE_LOG) {
|
|
27
|
+
const fs = require("node:fs");
|
|
28
|
+
const { fileURLToPath } = require("node:url");
|
|
29
|
+
const file = process.argv[1];
|
|
30
|
+
const reads = new Set();
|
|
31
|
+
const listed = new Set();
|
|
32
|
+
const note = (set, target) => {
|
|
33
|
+
try { set.add(typeof target === "string" ? target : target instanceof URL ? fileURLToPath(target) : Buffer.isBuffer(target) ? target.toString() : ""); } catch {}
|
|
34
|
+
};
|
|
35
|
+
const wrap = (owner, name, set) => {
|
|
36
|
+
const original = owner[name];
|
|
37
|
+
if (typeof original !== "function") return;
|
|
38
|
+
owner[name] = function (target, ...rest) { note(set, target); return original.call(this, target, ...rest); };
|
|
39
|
+
};
|
|
40
|
+
for (const name of ["readFileSync", "readFile", "createReadStream", "existsSync"]) wrap(fs, name, reads);
|
|
41
|
+
for (const name of ["readdirSync", "readdir", "opendirSync", "opendir"]) wrap(fs, name, listed);
|
|
42
|
+
wrap(fs.promises, "readFile", reads);
|
|
43
|
+
wrap(fs.promises, "readdir", listed);
|
|
44
|
+
wrap(fs.promises, "opendir", listed);
|
|
45
|
+
try { require("node:module").syncBuiltinESMExports(); } catch {}
|
|
46
|
+
process.on("exit", () => {
|
|
47
|
+
try { fs.appendFileSync(process.env.DIFFCI_COVERAGE_LOG, JSON.stringify({ file, pid: process.pid, reads: [...reads], listed: [...listed] }) + "\\n"); } catch {}
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
`;
|
|
51
|
+
export function coverageMapPath(repoPath) {
|
|
52
|
+
const log = outcomeLogPath(repoPath);
|
|
53
|
+
return log ? join(log, "..", "coverage-map.json") : undefined;
|
|
54
|
+
}
|
|
55
|
+
export function readCoverageMap(repoPath) {
|
|
56
|
+
const path = coverageMapPath(repoPath);
|
|
57
|
+
if (!path || !existsSync(path))
|
|
58
|
+
return undefined;
|
|
59
|
+
try {
|
|
60
|
+
const map = JSON.parse(readFileSync(path, "utf8"));
|
|
61
|
+
return map.schema === COVERAGE_MAP_SCHEMA && map.tests && typeof map.tests === "object" ? map : undefined;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** Runs `command` under the probe and V8 coverage, and writes the map. */
|
|
68
|
+
export function buildCoverageMap(repoPath, command, options) {
|
|
69
|
+
const dir = mkdtempSync(join(tmpdir(), "diffci-coverage-"));
|
|
70
|
+
try {
|
|
71
|
+
const probe = join(dir, "probe.cjs");
|
|
72
|
+
const log = join(dir, "reads.jsonl");
|
|
73
|
+
const v8 = join(dir, "v8");
|
|
74
|
+
mkdirSync(v8);
|
|
75
|
+
writeFileSync(probe, PROBE);
|
|
76
|
+
const nodeOptions = options.nodeOptions ?? process.env.NODE_OPTIONS;
|
|
77
|
+
const required = `--require "${probe.split(sep).join("/")}"`;
|
|
78
|
+
const execution = measureCommand(command, {
|
|
79
|
+
cwd: repoPath,
|
|
80
|
+
timeoutMs: options.timeoutMs,
|
|
81
|
+
tailBytes: options.tailBytes ?? 4000,
|
|
82
|
+
env: { NODE_OPTIONS: nodeOptions?.trim() ? `${nodeOptions} ${required}` : required, DIFFCI_COVERAGE_LOG: log, NODE_V8_COVERAGE: v8 },
|
|
83
|
+
});
|
|
84
|
+
let records = [];
|
|
85
|
+
try {
|
|
86
|
+
records = readFileSync(log, "utf8").split("\n").filter(Boolean).flatMap((line) => { try {
|
|
87
|
+
return [JSON.parse(line)];
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return [];
|
|
91
|
+
} });
|
|
92
|
+
}
|
|
93
|
+
catch { }
|
|
94
|
+
if (records.length === 0) {
|
|
95
|
+
return { execution, error: "no node --test process reported to the probe; the coverage map needs node:test, which runs each test file in its own process" };
|
|
96
|
+
}
|
|
97
|
+
const root = realpath(repoPath);
|
|
98
|
+
const inRepo = (absolute) => {
|
|
99
|
+
if (!absolute || !isAbsolute(absolute))
|
|
100
|
+
return undefined;
|
|
101
|
+
const path = relative(root, realpath(absolute)).split(sep).join("/");
|
|
102
|
+
if (!path || path.startsWith("..") || isAbsolute(path))
|
|
103
|
+
return undefined;
|
|
104
|
+
if (path.split("/").some((part) => part === "node_modules" || part === ".git"))
|
|
105
|
+
return undefined;
|
|
106
|
+
return path;
|
|
107
|
+
};
|
|
108
|
+
const loaded = loadedModulesByPid(v8);
|
|
109
|
+
const tests = {};
|
|
110
|
+
for (const record of records) {
|
|
111
|
+
const test = inRepo(record.file);
|
|
112
|
+
if (!test)
|
|
113
|
+
continue;
|
|
114
|
+
const entry = tests[test] ??= new Set();
|
|
115
|
+
for (const read of [...record.reads, ...(loaded.get(record.pid) ?? [])]) {
|
|
116
|
+
const path = inRepo(read);
|
|
117
|
+
if (path && path !== test && isFile(join(root, path)))
|
|
118
|
+
entry.add(path);
|
|
119
|
+
}
|
|
120
|
+
for (const listed of record.listed) {
|
|
121
|
+
const path = inRepo(listed);
|
|
122
|
+
if (path && isDirectory(join(root, path)))
|
|
123
|
+
entry.add(`${path}/`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const map = {
|
|
127
|
+
schema: COVERAGE_MAP_SCHEMA,
|
|
128
|
+
produced_at: new Date().toISOString(),
|
|
129
|
+
command,
|
|
130
|
+
tests: Object.fromEntries(Object.entries(tests).sort(([a], [b]) => a.localeCompare(b)).map(([test, paths]) => [test, [...paths].sort()])),
|
|
131
|
+
};
|
|
132
|
+
const path = coverageMapPath(repoPath);
|
|
133
|
+
if (path) {
|
|
134
|
+
mkdirSync(join(path, ".."), { recursive: true });
|
|
135
|
+
writeFileSync(path, `${JSON.stringify(map)}\n`, "utf8");
|
|
136
|
+
}
|
|
137
|
+
return { map, ...(path ? { path } : {}), execution };
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
rmSync(dir, { recursive: true, force: true });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** Script URLs in each process's V8 coverage file (`coverage-<pid>-<time>-<n>.json`), by pid. */
|
|
144
|
+
function loadedModulesByPid(dir) {
|
|
145
|
+
const byPid = new Map();
|
|
146
|
+
for (const name of readdirSync(dir)) {
|
|
147
|
+
const pid = Number(/^coverage-(\d+)-/.exec(name)?.[1]);
|
|
148
|
+
if (!Number.isFinite(pid))
|
|
149
|
+
continue;
|
|
150
|
+
try {
|
|
151
|
+
const { result } = JSON.parse(readFileSync(join(dir, name), "utf8"));
|
|
152
|
+
const files = result.flatMap(({ url }) => { try {
|
|
153
|
+
return url.startsWith("file:") ? [fileURLToPath(url)] : isAbsolute(url) ? [url] : [];
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return [];
|
|
157
|
+
} });
|
|
158
|
+
byPid.set(pid, [...(byPid.get(pid) ?? []), ...files]);
|
|
159
|
+
}
|
|
160
|
+
catch { }
|
|
161
|
+
}
|
|
162
|
+
return byPid;
|
|
163
|
+
}
|
|
164
|
+
function realpath(path) {
|
|
165
|
+
try {
|
|
166
|
+
return realpathSync.native(path);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return path;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
function isFile(path) {
|
|
173
|
+
try {
|
|
174
|
+
return statSync(path).isFile();
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function isDirectory(path) {
|
|
181
|
+
try {
|
|
182
|
+
return statSync(path).isDirectory();
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Tests whose map entry names one of `changed` (or lists a directory holding one), that `selected` lacks. */
|
|
189
|
+
export function coverageAdditions(map, changed, selected) {
|
|
190
|
+
const have = new Set(selected);
|
|
191
|
+
const additions = [];
|
|
192
|
+
for (const [test, paths] of Object.entries(map.tests)) {
|
|
193
|
+
if (have.has(test))
|
|
194
|
+
continue;
|
|
195
|
+
const hit = changed.find((file) => paths.some((path) => path === file || (path.endsWith("/") && file.startsWith(path))));
|
|
196
|
+
if (hit)
|
|
197
|
+
additions.push({ test, changed_file: hit });
|
|
198
|
+
}
|
|
199
|
+
return additions;
|
|
200
|
+
}
|
|
201
|
+
export function formatCoverageRun(run) {
|
|
202
|
+
if (!run.map)
|
|
203
|
+
return `diffci coverage: ${run.error ?? "no map was built"}`;
|
|
204
|
+
const tests = Object.keys(run.map.tests).length;
|
|
205
|
+
const files = new Set(Object.values(run.map.tests).flat()).size;
|
|
206
|
+
const lines = [`DiffCI coverage map: ${tests} test file(s), ${files} file(s) and directories they load, read or list`];
|
|
207
|
+
if (run.path)
|
|
208
|
+
lines.push(` written to ${run.path} (inside .git, never committed or sent)`);
|
|
209
|
+
if (run.execution.exitCode !== 0)
|
|
210
|
+
lines.push(` the test command exited ${String(run.execution.exitCode)}; the map still records what each test touched`);
|
|
211
|
+
lines.push(" verify now adds tests this map connects to a changed file when the dependency graph did not select them");
|
|
212
|
+
return lines.join("\n");
|
|
213
|
+
}
|
|
Binary file
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The pre-push hook `diffci init
|
|
2
|
+
* The pre-push hook `diffci init` installs (2026-10-28; on by default since 0.3.24).
|
|
3
3
|
*
|
|
4
4
|
* WHY. In 449 agent sessions on DentalPresence, agents ran DiffCI in 24 of over 1,500 test commands:
|
|
5
5
|
* they picked test files themselves (928) or ran the whole suite (282), and 104 pushes then failed the
|
|
@@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process";
|
|
|
2
2
|
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { dirname, isAbsolute, join, relative } from "node:path";
|
|
4
4
|
/**
|
|
5
|
-
* The pre-push hook `diffci init
|
|
5
|
+
* The pre-push hook `diffci init` installs (2026-10-28; on by default since 0.3.24).
|
|
6
6
|
*
|
|
7
7
|
* WHY. In 449 agent sessions on DentalPresence, agents ran DiffCI in 24 of over 1,500 test commands:
|
|
8
8
|
* they picked test files themselves (928) or ran the whole suite (282), and 104 pushes then failed the
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ObservationReport } from "./report.js";
|
|
2
|
+
/**
|
|
3
|
+
* The GitHub job summary for `diffci observe`: the place most people will ever read a report, so it
|
|
4
|
+
* leads with the answer (what this change affects) and keeps the full text summary one click away.
|
|
5
|
+
* It claims nothing the report doesn't: no savings, and every fallback and refusal says so.
|
|
6
|
+
*/
|
|
7
|
+
export declare function formatJobSummary(report: ObservationReport, textSummary: string, delivery?: string): string;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/** Selected tests listed by name before the rest collapse into a count. */
|
|
2
|
+
const MAX_LISTED_TESTS = 20;
|
|
3
|
+
/** Inline code that survives any path: no backticks to close it early, no pipes to split a table cell. */
|
|
4
|
+
function code(text) {
|
|
5
|
+
return `\`${text.replace(/`/g, "'").replace(/\|/g, "\\|")}\``;
|
|
6
|
+
}
|
|
7
|
+
function plural(count, one, many = `${one}s`) {
|
|
8
|
+
return `${count} ${count === 1 ? one : many}`;
|
|
9
|
+
}
|
|
10
|
+
/** `DIRECT_IMPORT` reads as "direct import"; prose reasons pass through. */
|
|
11
|
+
function readableReason(reason) {
|
|
12
|
+
return /^[A-Z0-9_]+$/.test(reason) ? reason.toLowerCase().replace(/_/g, " ") : reason;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The GitHub job summary for `diffci observe`: the place most people will ever read a report, so it
|
|
16
|
+
* leads with the answer (what this change affects) and keeps the full text summary one click away.
|
|
17
|
+
* It claims nothing the report doesn't: no savings, and every fallback and refusal says so.
|
|
18
|
+
*/
|
|
19
|
+
export function formatJobSummary(report, textSummary, delivery) {
|
|
20
|
+
const lines = ["### DiffCI: what this change affects", ""];
|
|
21
|
+
const result = report.result;
|
|
22
|
+
if (report.status !== "OBSERVED" || !result) {
|
|
23
|
+
lines.push(`**No plan for this change** (${report.status.toLowerCase()} at ${report.stage}).`);
|
|
24
|
+
if (report.reason)
|
|
25
|
+
lines.push("", report.reason);
|
|
26
|
+
}
|
|
27
|
+
else if (result.mode === "FULL") {
|
|
28
|
+
lines.push(`**The full test suite is needed** for ${plural(result.changedFileCount, "changed file")}: DiffCI could not prove which of the ${plural(result.totalTestCount, "test file")} this change leaves untouched, so it would run them all.`);
|
|
29
|
+
if (result.fallbackReasons.length > 0) {
|
|
30
|
+
lines.push("", "Why:");
|
|
31
|
+
for (const reason of result.fallbackReasons)
|
|
32
|
+
lines.push(`- ${reason}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
const selected = result.selectedTests.length;
|
|
37
|
+
lines.push(`**${selected} of ${plural(result.totalTestCount, "test file")}** ${selected === 1 ? "is" : "are"} affected by ${plural(result.changedFileCount, "changed file")}.`);
|
|
38
|
+
const baseline = result.pathBaseline.mode === "FULL"
|
|
39
|
+
? "everything"
|
|
40
|
+
: plural(result.pathBaseline.selectedTestCount, "test file");
|
|
41
|
+
lines.push(`A simple path-rule CI would have run ${baseline}.`);
|
|
42
|
+
if (selected > 0) {
|
|
43
|
+
const reasons = result.selectionReasons ?? {};
|
|
44
|
+
lines.push("", `<details><summary>Why these ${plural(selected, "test")}</summary>`, "");
|
|
45
|
+
lines.push("| Test | Because |", "| --- | --- |");
|
|
46
|
+
for (const test of result.selectedTests.slice(0, MAX_LISTED_TESTS)) {
|
|
47
|
+
const why = reasons[test];
|
|
48
|
+
const because = why
|
|
49
|
+
? `${readableReason(why.reason)}${why.changed_file ? ` from ${code(why.changed_file)}` : ""}`
|
|
50
|
+
: "affected by the change";
|
|
51
|
+
lines.push(`| ${code(test)} | ${because} |`);
|
|
52
|
+
}
|
|
53
|
+
if (selected > MAX_LISTED_TESTS)
|
|
54
|
+
lines.push(`| and ${selected - MAX_LISTED_TESTS} more | see the report artifact |`);
|
|
55
|
+
lines.push("", "</details>");
|
|
56
|
+
}
|
|
57
|
+
if (result.proposedCommands.length > 0) {
|
|
58
|
+
lines.push("", "Would run:", "");
|
|
59
|
+
for (const command of result.proposedCommands)
|
|
60
|
+
lines.push("```", command, "```");
|
|
61
|
+
}
|
|
62
|
+
else if (result.commandRefusalReason) {
|
|
63
|
+
lines.push("", `No runnable command: ${result.commandRefusalReason}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// A broken promise of non-interference is the one thing that must never hide in a collapsed block.
|
|
67
|
+
const blocking = report.nonInterference.workflowFindings.filter((finding) => finding.severity === "BLOCKING");
|
|
68
|
+
if (!report.nonInterference.worktreeUnchanged) {
|
|
69
|
+
lines.push("", "> [!WARNING]", "> The working tree changed while DiffCI observed it. Please report this at https://github.com/DiffCI/core/issues.");
|
|
70
|
+
}
|
|
71
|
+
if (blocking.length > 0) {
|
|
72
|
+
lines.push("", "> [!WARNING]", `> ${plural(blocking.length, "blocking workflow finding")}: this installation can affect other jobs. Details are in the full report below.`);
|
|
73
|
+
}
|
|
74
|
+
if (delivery?.startsWith("not sent"))
|
|
75
|
+
lines.push("", `Delivery: ${delivery}`);
|
|
76
|
+
lines.push("", "<details><summary>Full report</summary>", "", "```", `${textSummary}${delivery ? `\n delivery: ${delivery}` : ""}`, "```", "", "</details>", "", "<sub>Observation only: DiffCI ran, skipped and changed nothing in this workflow. [DiffCI](https://github.com/DiffCI/core) is open source (MIT) and tells AI coding agents what their change breaks.</sub>", "");
|
|
77
|
+
return lines.join("\n");
|
|
78
|
+
}
|
|
@@ -250,6 +250,8 @@ export async function observe(options) {
|
|
|
250
250
|
const outsideSuite = [...(impact.testsOutsideFullSuite ?? []).map((test) => test.path), ...planOutside].sort();
|
|
251
251
|
const outsidePlan = outsideSuite.length ? planSelectiveTestCommands(profile, outsideSuite) : undefined;
|
|
252
252
|
markPhase("impactAndCommands");
|
|
253
|
+
// Newer than some bundled engines, which never return it.
|
|
254
|
+
const fallbackDetails = impact.fallbackDetails;
|
|
253
255
|
return finish("OBSERVED", "complete", {
|
|
254
256
|
result: {
|
|
255
257
|
mode: impact.fallbackRequired ? "FULL" : "SELECTIVE",
|
|
@@ -265,6 +267,7 @@ export async function observe(options) {
|
|
|
265
267
|
outsideSuiteCommands: outsidePlan?.refusalReason ? [] : (outsidePlan?.commands ?? []).map(commandSpecToString),
|
|
266
268
|
} : {}),
|
|
267
269
|
fallbackReasons: impact.fallbackReasons,
|
|
270
|
+
...(fallbackDetails ? { fallbackDetails } : {}),
|
|
268
271
|
proposedCommands: (commandPlan?.commands ?? []).map(commandSpecToString),
|
|
269
272
|
...(impact.testPhases?.length ? { testPhases: [...impact.testPhases] } : {}),
|
|
270
273
|
workspaceCommands: Boolean(profile.workspaceTestPackages?.length),
|
|
@@ -192,6 +192,9 @@ export interface ObservationResult {
|
|
|
192
192
|
* are commands and are not redacted. */
|
|
193
193
|
testPhases?: string[];
|
|
194
194
|
fallbackReasons: string[];
|
|
195
|
+
/** For each changed file whose readers could not be resolved, every blocker with the readers leading to it.
|
|
196
|
+
* Like `fallbackReasons`, these name repository paths. Present only on a fallback. */
|
|
197
|
+
fallbackDetails?: Record<string, string[]>;
|
|
195
198
|
/** The command DiffCI would have run. Present even in observe mode - it is the claim being tested. */
|
|
196
199
|
proposedCommands: string[];
|
|
197
200
|
/** Workspace execution can widen affected files to whole state-sharing suites. */
|
|
@@ -52,6 +52,8 @@ export interface VerificationReport {
|
|
|
52
52
|
written_during_verification?: string[];
|
|
53
53
|
/** Files that existed before the run and changed during it, at most 20. Their presence blocks the verdict. */
|
|
54
54
|
changed_during_verification?: SnapshotChange[];
|
|
55
|
+
/** Commit-range only: checked-out files that differ from HEAD only by CRLF line endings, at most 20. */
|
|
56
|
+
line_ending_only_changes?: string[];
|
|
55
57
|
};
|
|
56
58
|
analysis: {
|
|
57
59
|
status: "not_needed" | ObservationReport["status"];
|
|
@@ -86,6 +88,8 @@ export interface VerificationReport {
|
|
|
86
88
|
total: number;
|
|
87
89
|
timings: "file" | "equal";
|
|
88
90
|
};
|
|
91
|
+
/** Tests the coverage map added to the selection (coverage-map.ts), when it added any. */
|
|
92
|
+
coverage_added?: string[];
|
|
89
93
|
}
|
|
90
94
|
interface VerifyOptions {
|
|
91
95
|
repoPath: string;
|
|
@@ -108,6 +112,8 @@ interface VerifyOptions {
|
|
|
108
112
|
/** Run only this job's share of the selection (`--shard i/N`), balanced by `timings` when given. */
|
|
109
113
|
shard?: ShardSpec;
|
|
110
114
|
timings?: TimingsFile;
|
|
115
|
+
/** False ignores the coverage map (`--no-coverage`). */
|
|
116
|
+
coverage?: boolean;
|
|
111
117
|
}
|
|
112
118
|
export interface VerifyChangedOptions extends VerifyOptions {
|
|
113
119
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
2
|
import { tmpdir } from "node:os";
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
|
-
import { batchCommand, measureCommands, orderCommand, splitCommand, subsetCommand } from "./command-batches.js";
|
|
4
|
+
import { appendToCommand, batchCommand, measureCommands, orderCommand, splitCommand, subsetCommand } from "./command-batches.js";
|
|
5
|
+
import { coverageAdditions, readCoverageMap } from "./coverage-map.js";
|
|
5
6
|
import { checkAtBaseline, compareWithBaseline } from "./failure-baseline.js";
|
|
6
7
|
import { collectEnforcementContext, evaluateEnforcement } from "./enforce-policy.js";
|
|
7
8
|
import { inferFullCommand, inferSelectedCommand, inferSelectedCommands } from "./full-command.js";
|
|
@@ -12,7 +13,7 @@ import { outcomeLogPath, readOutcomes, reusablePass } from "./outcome-log.js";
|
|
|
12
13
|
import { likelyFailures, rankTests, testHistory } from "./test-ranking.js";
|
|
13
14
|
import { assignShards } from "./test-shards.js";
|
|
14
15
|
import { mergeTestFileResults } from "./test-results.js";
|
|
15
|
-
import { captureWorkingTreeSnapshot, snapshotChanges } from "./working-tree.js";
|
|
16
|
+
import { captureWorkingTreeSnapshot, lineEndingOnlyChanges, snapshotChanges } from "./working-tree.js";
|
|
16
17
|
export const VERIFICATION_SCHEMA = "diffci.verification.v1";
|
|
17
18
|
function receiptRange(range) {
|
|
18
19
|
if (!range)
|
|
@@ -35,6 +36,7 @@ function baseReport(snapshot, scope, range) {
|
|
|
35
36
|
base_sha: snapshot.baseSha,
|
|
36
37
|
before_tree_sha: snapshot.treeSha,
|
|
37
38
|
unchanged: false,
|
|
39
|
+
...(snapshot.lineEndingOnly ? { line_ending_only_changes: snapshot.lineEndingOnly.slice(0, 20) } : {}),
|
|
38
40
|
},
|
|
39
41
|
};
|
|
40
42
|
}
|
|
@@ -110,6 +112,29 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
|
|
|
110
112
|
report.snapshot.after_tree_sha = afterAnalysis.treeSha;
|
|
111
113
|
return report;
|
|
112
114
|
}
|
|
115
|
+
// Coverage edges, phase A (coverage-map.ts, 2026-11-06): tests the coverage map connects to a changed
|
|
116
|
+
// file and the graph did not select are added. Only ever adds; a selected command that cannot take them
|
|
117
|
+
// runs the full suite instead. Never under enforce or path redaction.
|
|
118
|
+
const coverageAdded = [];
|
|
119
|
+
if (result && result.mode === "SELECTIVE" && !enforcement && !options.redactPaths && options.coverage !== false) {
|
|
120
|
+
const map = readCoverageMap(options.repoPath);
|
|
121
|
+
const additions = map ? coverageAdditions(map, result.changedFiles, result.selectedTests) : [];
|
|
122
|
+
if (additions.length) {
|
|
123
|
+
const tests = additions.map((addition) => addition.test);
|
|
124
|
+
const extended = result.proposedCommands.length === 1 ? appendToCommand(result.proposedCommands[0], result.selectedTests, tests) : undefined;
|
|
125
|
+
coverageAdded.push(...tests);
|
|
126
|
+
result = extended
|
|
127
|
+
? {
|
|
128
|
+
...result,
|
|
129
|
+
selectedTests: [...result.selectedTests, ...tests],
|
|
130
|
+
proposedCommands: [extended],
|
|
131
|
+
selectionReasons: { ...result.selectionReasons, ...Object.fromEntries(additions.map((addition) => [addition.test, { reason: "COVERAGE", changed_file: addition.changed_file }])) },
|
|
132
|
+
}
|
|
133
|
+
: { ...result, mode: "FULL", fallbackReasons: [...result.fallbackReasons, `the coverage map adds ${tests.length} test file(s) the selected command cannot include, such as ${tests[0]}`] };
|
|
134
|
+
counts.testsSelected = result.selectedTests.length;
|
|
135
|
+
analysis.fallback_reasons = result.fallbackReasons;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
113
138
|
// --shard i/N (test-shards.ts): this job's share of the selection, split the same way in every job.
|
|
114
139
|
const shard = options.shard;
|
|
115
140
|
const shardTests = shard && result && !enforcedFull && result.mode === "SELECTIVE"
|
|
@@ -118,7 +143,11 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
|
|
|
118
143
|
const executable = enforcedFull || !result
|
|
119
144
|
? fullSelection(options.repoPath, `enforce fallback (${enforcement?.fired_fallback}): ${enforcement?.detail}`)
|
|
120
145
|
: executableSelection(options.repoPath, result, rankedOrdering(options, result), shard && shardTests ? { tests: new Set(shardTests), first: shard.index === 1 } : undefined);
|
|
121
|
-
const { selection, command, commands,
|
|
146
|
+
const { selection, command, commands, outsideSuite } = executable;
|
|
147
|
+
const reason = coverageAdded.length && selection === "selected"
|
|
148
|
+
? `${executable.reason}; the coverage map added ${coverageAdded.length} test file(s) the dependency graph did not select (${coverageAdded.slice(0, 3).join(", ")})`
|
|
149
|
+
: executable.reason;
|
|
150
|
+
const coverageField = coverageAdded.length && selection === "selected" ? { coverage_added: coverageAdded } : {};
|
|
122
151
|
const unshardable = "unshardable" in executable && executable.unshardable;
|
|
123
152
|
const shardField = shard ? { shard: { index: shard.index, total: shard.total, timings: options.timings ? "file" : "equal" } } : {};
|
|
124
153
|
if (shard) {
|
|
@@ -184,6 +213,7 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
|
|
|
184
213
|
required_actions: [],
|
|
185
214
|
reused_from,
|
|
186
215
|
...shardField,
|
|
216
|
+
...coverageField,
|
|
187
217
|
};
|
|
188
218
|
}
|
|
189
219
|
const checkBaseline = options.baselineOnFailure && checkBase && checkHead
|
|
@@ -312,6 +342,7 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
|
|
|
312
342
|
required_actions: verification === "passed" ? [] : [finalReason + baselineNote],
|
|
313
343
|
...(failureBaseline ? { failure_baseline: failureBaseline } : {}),
|
|
314
344
|
...shardField,
|
|
345
|
+
...coverageField,
|
|
315
346
|
};
|
|
316
347
|
}
|
|
317
348
|
function stamped(report, version) {
|
|
@@ -386,7 +417,11 @@ async function verifyCommitRange(options) {
|
|
|
386
417
|
return blocked(unknownSnapshot(), "commit-range", message, { status: "ERROR", stage: "context", fallback_reasons: [], error: message });
|
|
387
418
|
}
|
|
388
419
|
if (before.changed) {
|
|
389
|
-
|
|
420
|
+
const lineEndingOnly = lineEndingOnlyChanges(repoPath, before);
|
|
421
|
+
if (!lineEndingOnly) {
|
|
422
|
+
return blocked(before, "commit-range", "commit-range verification requires a clean checkout; use verify --changed for uncommitted changes", { status: "not_needed", fallback_reasons: [] });
|
|
423
|
+
}
|
|
424
|
+
before = { ...before, lineEndingOnly };
|
|
390
425
|
}
|
|
391
426
|
const temporaryDirectory = mkdtempSync(join(tmpdir(), "diffci-verify-"));
|
|
392
427
|
try {
|
|
@@ -431,6 +466,10 @@ export function formatVerificationSummary(report) {
|
|
|
431
466
|
];
|
|
432
467
|
if (report.commit_range)
|
|
433
468
|
lines.splice(2, 0, ` range: ${report.commit_range.base_sha.slice(0, 12)}..${report.commit_range.head_sha.slice(0, 12)}`);
|
|
469
|
+
const lineEndings = report.snapshot.line_ending_only_changes;
|
|
470
|
+
if (lineEndings?.length) {
|
|
471
|
+
lines.push(` line endings only: ${lineEndings.length}${lineEndings.length === 20 ? "+" : ""} checked-out file(s) differ from HEAD only by CRLF (${lineEndings.slice(0, 3).join(", ")}${lineEndings.length > 3 ? ", ..." : ""}); verified as checked out`);
|
|
472
|
+
}
|
|
434
473
|
const written = report.snapshot.written_during_verification;
|
|
435
474
|
if (written?.length)
|
|
436
475
|
lines.push(` written by the run (not in .gitignore): ${written.slice(0, 5).join(", ")}${written.length > 5 ? ", ..." : ""}`);
|
|
@@ -6,7 +6,20 @@ export interface WorkingTreeSnapshot {
|
|
|
6
6
|
/** Unreachable commit used only so the existing commit-range analyzer can inspect the tree. */
|
|
7
7
|
commitSha: string;
|
|
8
8
|
changed: boolean;
|
|
9
|
+
/** Set when every difference from HEAD is a CRLF checkout of an LF-committed file (see lineEndingOnlyChanges). */
|
|
10
|
+
lineEndingOnly?: string[];
|
|
9
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* The paths, when every difference between HEAD and the snapshot is only CRLF line endings on files
|
|
14
|
+
* committed with LF; otherwise undefined.
|
|
15
|
+
*
|
|
16
|
+
* WHY (2026-11-06). On DentalPresence the pre-push hook could not verify any push: 268 files had been
|
|
17
|
+
* checked out with CRLF under Git for Windows' system-wide `core.autocrlf=true` before the repository
|
|
18
|
+
* set it to false. `git status` called the checkout clean because its stat cache still matched, while
|
|
19
|
+
* the snapshot re-reads every file and saw 268 changes. Git's own view decides "clean" for the user, so
|
|
20
|
+
* a CRLF-only checkout is verified rather than blocked, and the receipt names the files.
|
|
21
|
+
*/
|
|
22
|
+
export declare function lineEndingOnlyChanges(repoPathInput: string, snapshot: WorkingTreeSnapshot): string[] | undefined;
|
|
10
23
|
/** One path that differs between two snapshots. A rename is a deletion plus an addition. */
|
|
11
24
|
export interface SnapshotChange {
|
|
12
25
|
path: string;
|
|
@@ -1,7 +1,46 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
-
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join, resolve } from "node:path";
|
|
5
|
+
/**
|
|
6
|
+
* The paths, when every difference between HEAD and the snapshot is only CRLF line endings on files
|
|
7
|
+
* committed with LF; otherwise undefined.
|
|
8
|
+
*
|
|
9
|
+
* WHY (2026-11-06). On DentalPresence the pre-push hook could not verify any push: 268 files had been
|
|
10
|
+
* checked out with CRLF under Git for Windows' system-wide `core.autocrlf=true` before the repository
|
|
11
|
+
* set it to false. `git status` called the checkout clean because its stat cache still matched, while
|
|
12
|
+
* the snapshot re-reads every file and saw 268 changes. Git's own view decides "clean" for the user, so
|
|
13
|
+
* a CRLF-only checkout is verified rather than blocked, and the receipt names the files.
|
|
14
|
+
*/
|
|
15
|
+
export function lineEndingOnlyChanges(repoPathInput, snapshot) {
|
|
16
|
+
const repoPath = resolve(repoPathInput);
|
|
17
|
+
const baseTreeSha = requireGit(repoPath, ["rev-parse", "--verify", `${snapshot.baseSha}^{tree}`], "could not resolve the snapshot base tree");
|
|
18
|
+
const changes = snapshotChanges(repoPath, baseTreeSha, snapshot.treeSha);
|
|
19
|
+
if (changes.length === 0 || changes.some((change) => change.status !== "modified"))
|
|
20
|
+
return undefined;
|
|
21
|
+
for (const change of changes) {
|
|
22
|
+
const committed = spawnSync("git", ["cat-file", "blob", `${baseTreeSha}:${change.path}`], {
|
|
23
|
+
cwd: repoPath,
|
|
24
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
25
|
+
windowsHide: true,
|
|
26
|
+
});
|
|
27
|
+
if (committed.status !== 0 || committed.stdout.includes(13))
|
|
28
|
+
return undefined;
|
|
29
|
+
let checkedOut;
|
|
30
|
+
try {
|
|
31
|
+
checkedOut = readFileSync(join(repoPath, change.path));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
if (!checkedOut.includes(13))
|
|
37
|
+
return undefined;
|
|
38
|
+
const normalized = Buffer.from(checkedOut.toString("latin1").replace(/\r\n/g, "\n"), "latin1");
|
|
39
|
+
if (!normalized.equals(committed.stdout))
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
return changes.map((change) => change.path);
|
|
43
|
+
}
|
|
5
44
|
function runGit(repoPath, args, env, input) {
|
|
6
45
|
const result = spawnSync("git", args, {
|
|
7
46
|
cwd: repoPath,
|
|
@@ -284,6 +284,7 @@ export function testListEdit(oldBody, newBody) {
|
|
|
284
284
|
return { added, removed };
|
|
285
285
|
}
|
|
286
286
|
const DEPENDENCY_FIELDS = new Set(["dependencies", "devDependencies", "optionalDependencies"]);
|
|
287
|
+
const PACKAGE_LOCKFILES = ["package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml", "bun.lock", "bun.lockb"];
|
|
287
288
|
/** Exact root requests for the supported Classic layout. Unlike scriptRecord, never discard an
|
|
288
289
|
* invalid dependency value: an omitted root would make the lockfile attribution incomplete. */
|
|
289
290
|
function yarnDirectDependencies(content) {
|
|
@@ -716,6 +717,64 @@ export async function analyzeGitDelta(options = {}) {
|
|
|
716
717
|
}
|
|
717
718
|
}
|
|
718
719
|
}
|
|
720
|
+
// 2026-11-05: without a committed lockfile every install resolves each request afresh, so an edit
|
|
721
|
+
// limited to dependency requests reaches only the packages whose request changed and what they
|
|
722
|
+
// install; importers of those packages are selected like a lockfile-attributed change. LobeHub ignores
|
|
723
|
+
// pnpm-lock.yaml, and each of its workspace dependency bumps ran the full suite. A lockfile that governs
|
|
724
|
+
// any changed manifest, a local (`workspace:`, `link:`, `file:`) request, a scripts edit, any other
|
|
725
|
+
// behavioral field, or a package-manager configuration change keeps the global signal.
|
|
726
|
+
const manifests = filesWithBinary.filter((f) => f.changeType === "modified" && posix.basename(f.path) === "package.json" && !f.path.split("/").includes("node_modules"));
|
|
727
|
+
const managerConfiguration = allPaths.some((path) => posix.basename(path) !== "package.json"
|
|
728
|
+
&& (LOCKFILE.test(posix.basename(path)) || /^(?:\.npmrc|\.yarnrc(?:\.yml)?|pnpm-workspace\.yaml|\.pnpmfile\.cjs|bunfig\.toml)$/.test(posix.basename(path))));
|
|
729
|
+
if (manifests.length > 0 && !manifests.some((f) => narrowed.has(f)) && !analysis.lockfileChanged && !managerConfiguration) {
|
|
730
|
+
const lockfileGoverns = (path) => {
|
|
731
|
+
for (let dir = posix.dirname(path);; dir = posix.dirname(dir)) {
|
|
732
|
+
const prefix = dir === "." ? "" : `${dir}/`;
|
|
733
|
+
if (PACKAGE_LOCKFILES.some((name) => [baseSha, headSha].some((sha) => readFileAtSha(sha, prefix + name, repoPath) !== undefined)))
|
|
734
|
+
return true;
|
|
735
|
+
if (dir === ".")
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
};
|
|
739
|
+
const edits = manifests.map((file) => {
|
|
740
|
+
const before = readFileAtSha(baseSha, file.path, repoPath);
|
|
741
|
+
const after = readFileAtSha(headSha, file.path, repoPath);
|
|
742
|
+
const change = packageJsonChange(before, after);
|
|
743
|
+
const localChanged = change.changedDependencies.some((name) => [before, after].some((content) => {
|
|
744
|
+
try {
|
|
745
|
+
const json = JSON.parse(content ?? "");
|
|
746
|
+
return [...DEPENDENCY_FIELDS].some((field) => /^(?:workspace|link|file|portal):/.test(scriptRecord(json[field])?.[name] ?? ""));
|
|
747
|
+
}
|
|
748
|
+
catch {
|
|
749
|
+
return true;
|
|
750
|
+
}
|
|
751
|
+
}));
|
|
752
|
+
const eligible = change.kind !== "behavioral" && !localChanged
|
|
753
|
+
&& JSON.stringify(parsePackageScripts(before)) === JSON.stringify(parsePackageScripts(after));
|
|
754
|
+
return { file, change, eligible };
|
|
755
|
+
});
|
|
756
|
+
if (edits.some((edit) => edit.change.kind === "dependencies") && edits.every((edit) => edit.eligible) && !manifests.some((f) => lockfileGoverns(f.path))) {
|
|
757
|
+
const names = new Set(analysis.changedDependencies ?? []);
|
|
758
|
+
const specifiersOnly = [];
|
|
759
|
+
for (const { file, change } of edits) {
|
|
760
|
+
for (const name of change.changedDependencies)
|
|
761
|
+
names.add(name);
|
|
762
|
+
narrowed.add(file);
|
|
763
|
+
if (change.kind !== "metadata" && !referenceResolvedPaths.includes(file.path))
|
|
764
|
+
referenceResolvedPaths.push(file.path);
|
|
765
|
+
if (change.kind === "dependencies" && change.specifiersOnly)
|
|
766
|
+
specifiersOnly.push(file.path);
|
|
767
|
+
if (file.path === "package.json" && change.testScriptAddedPaths.length > 0)
|
|
768
|
+
analysis.testScriptAddedPaths = change.testScriptAddedPaths;
|
|
769
|
+
}
|
|
770
|
+
analysis.dependencyManifestChanged = false;
|
|
771
|
+
analysis.changedDependencies = [...names].sort();
|
|
772
|
+
if (specifiersOnly.includes("package.json"))
|
|
773
|
+
analysis.packageJsonSpecifiersOnly = true;
|
|
774
|
+
if (specifiersOnly.length > 0)
|
|
775
|
+
analysis.specifiersOnlyManifests = specifiersOnly.sort();
|
|
776
|
+
}
|
|
777
|
+
}
|
|
719
778
|
// 2026-11-03: a workspace package's package.json used to be an unknown file and a full run. One whose
|
|
720
779
|
// edit is limited to metadata and data fields (a release bumping `version`) cannot change how tests
|
|
721
780
|
// run, so its readers are resolved like the root's. A script edit stays unknown: the root's test
|