@diffci.com/diffci 0.3.22 → 0.3.23
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/cli.js +7 -1
- package/dist-client/src/client/command-batches.d.ts +1 -0
- package/dist-client/src/client/command-batches.js +3 -2
- package/dist-client/src/client/selected-coverage.d.ts +21 -1
- package/dist-client/src/client/selected-coverage.js +83 -10
- package/dist-client/src/client/verify-savings.d.ts +3 -1
- package/dist-client/src/client/verify-savings.js +1 -0
- package/dist-client/src/client/verify.js +32 -16
- package/dist-client/src/client/workflow-guard.js +14 -0
- package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +3 -0
- package/node_modules/@diffci.com/core/dist/git/git-diff.js +93 -8
- 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 +6 -2
- package/node_modules/@diffci.com/core/dist/planner/test-command.js +13 -6
- package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +1 -0
- package/node_modules/@diffci.com/core/dist/repo/impact.js +17 -1
- package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/pnpm-lockfile.d.ts +6 -0
- package/node_modules/@diffci.com/core/dist/repo/pnpm-lockfile.js +161 -0
- package/node_modules/@diffci.com/core/dist/repo/pnpm-lockfile.js.map +1 -0
- package/node_modules/@diffci.com/core/package.json +1 -1
- package/node_modules/@diffci.com/core/src/git/git-diff.ts +78 -7
- package/node_modules/@diffci.com/core/src/git/types.ts +6 -2
- package/node_modules/@diffci.com/core/src/planner/test-command.ts +13 -6
- package/node_modules/@diffci.com/core/src/repo/impact.ts +16 -1
- package/node_modules/@diffci.com/core/src/repo/pnpm-lockfile.ts +147 -0
- package/package.json +2 -2
|
@@ -502,7 +502,13 @@ function summarise(report, executionFollows = false) {
|
|
|
502
502
|
}
|
|
503
503
|
lines.push(` non-interference${executionFollows ? " (analysis phase)" : ""}: worktree ${report.nonInterference.worktreeUnchanged ? "unchanged" : "CHANGED - report this"}, report written ${report.nonInterference.reportWrittenOutsideRepository ? "outside" : "INSIDE"} the checkout`);
|
|
504
504
|
const blocking = report.nonInterference.workflowFindings.filter((f) => f.severity === "BLOCKING");
|
|
505
|
-
|
|
505
|
+
// `check` is a local trial, not an installation, so it names the count and where to look; `observe`
|
|
506
|
+
// runs inside the installation being judged and keeps every finding in its log.
|
|
507
|
+
if (blocking.length > 0 && executionFollows) {
|
|
508
|
+
const jobs = new Set(blocking.map((finding) => `${finding.workflow}#${finding.job ?? ""}`));
|
|
509
|
+
lines.push(` workflow: ${blocking.length} blocking finding(s) in ${jobs.size} DiffCI job(s) could let an observer affect CI; run \`diffci verify-workflow\` for details`);
|
|
510
|
+
}
|
|
511
|
+
else if (blocking.length > 0) {
|
|
506
512
|
lines.push(` workflow: ${blocking.length} blocking finding(s) - this installation CAN affect other jobs:`);
|
|
507
513
|
for (const finding of blocking)
|
|
508
514
|
lines.push(formatFinding(finding));
|
|
@@ -20,9 +20,10 @@ export function batchCommand(command, paths, limit = COMMAND_LINE_LIMIT) {
|
|
|
20
20
|
return [command];
|
|
21
21
|
const tokens = command.split(" ");
|
|
22
22
|
const selected = new Set(paths);
|
|
23
|
-
// A `node --test` path with brackets arrives quoted and class-escaped: "src/app
|
|
23
|
+
// A `node --test` path with brackets arrives quoted and class-escaped: "src/app/@([[])id@([]])/x.test.ts"
|
|
24
|
+
// (Core before 2026-11-02 emitted the bare class, "src/app/[[]id[]]/x.test.ts").
|
|
24
25
|
const isSelected = (token) => selected.has(token)
|
|
25
|
-
|| selected.has((commandArguments(token)[0] ?? "").replace(
|
|
26
|
+
|| selected.has((commandArguments(token)[0] ?? "").replace(/@\(\[(.)\]\)|\[(.)\]/g, (_, wrapped, bare) => wrapped ?? bare ?? ""));
|
|
26
27
|
let start = tokens.length;
|
|
27
28
|
while (start > 0 && isSelected(tokens[start - 1]))
|
|
28
29
|
start--;
|
|
@@ -10,10 +10,30 @@
|
|
|
10
10
|
* `node --test`, the way Node's own glob matches them; a file no pattern claims means the selection is
|
|
11
11
|
* not executable as written. After running, the runner's own count is checked: a summary reporting
|
|
12
12
|
* fewer tests (node:test) or test files (vitest, jest) than files were selected means some never ran.
|
|
13
|
+
*
|
|
14
|
+
* 2026-11-02. Both checks passed under CLI 0.3.22 while the file still never ran on Linux. The command
|
|
15
|
+
* was `npx --no-install tsx --test "...[[]...path[]]..."`, and npx hands its arguments to a second
|
|
16
|
+
* `sh -c`, quoting only those with characters such as `(`, `*` or a space; that shell expanded the
|
|
17
|
+
* unquoted class back to the real `[...path]` directory. The pre-run check now models that second
|
|
18
|
+
* shell. The count check could not see one missing file among 120 tests, so a `node --test` selection
|
|
19
|
+
* also runs with a probe that records the file each test process started for (`traceNodeTestFiles`),
|
|
20
|
+
* and a selected file that never started blocks the verification.
|
|
13
21
|
*/
|
|
14
22
|
/** The arguments `sh` (or `cmd.exe` on Windows) would hand the program, for the quoting DiffCI emits. */
|
|
15
23
|
export declare function commandArguments(command: string, windows?: boolean): string[];
|
|
16
24
|
/** Selected files no `node --test` pattern in `command` matches. Empty when `command` runs no `node --test`. */
|
|
17
|
-
export declare function unmatchedNodeTests(command: string, selectedTests: readonly string[]): string[];
|
|
25
|
+
export declare function unmatchedNodeTests(command: string, selectedTests: readonly string[], windows?: boolean): string[];
|
|
26
|
+
/** Selected files `command` hands `node --test`, which the trace from `traceNodeTestFiles` must show. */
|
|
27
|
+
export declare function selectedNodeTests(command: string, selectedTests: readonly string[], windows?: boolean): string[];
|
|
28
|
+
export interface NodeTestTrace {
|
|
29
|
+
/** Environment for the command: NODE_OPTIONS extended with the probe. */
|
|
30
|
+
env: Record<string, string>;
|
|
31
|
+
/** Repository-relative paths of the files that started, or undefined when none did. */
|
|
32
|
+
read(): string[] | undefined;
|
|
33
|
+
dispose(): void;
|
|
34
|
+
}
|
|
35
|
+
export declare function traceNodeTestFiles(cwd: string, nodeOptions?: string | undefined): NodeTestTrace;
|
|
36
|
+
/** Selected `node --test` files the trace does not show starting. Empty when the trace proves nothing. */
|
|
37
|
+
export declare function unstartedNodeTests(expected: readonly string[], started: readonly string[] | undefined, windows?: boolean): string[];
|
|
18
38
|
/** The test count node:test's summary reports, or the test-file total vitest or jest reports. */
|
|
19
39
|
export declare function runnerTestCount(output: string): number | undefined;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join, matchesGlob, relative, sep } from "node:path";
|
|
2
4
|
/**
|
|
3
5
|
* Selected tests the runner would never execute (2026-11-01).
|
|
4
6
|
*
|
|
@@ -11,6 +13,14 @@ import { matchesGlob } from "node:path";
|
|
|
11
13
|
* `node --test`, the way Node's own glob matches them; a file no pattern claims means the selection is
|
|
12
14
|
* not executable as written. After running, the runner's own count is checked: a summary reporting
|
|
13
15
|
* fewer tests (node:test) or test files (vitest, jest) than files were selected means some never ran.
|
|
16
|
+
*
|
|
17
|
+
* 2026-11-02. Both checks passed under CLI 0.3.22 while the file still never ran on Linux. The command
|
|
18
|
+
* was `npx --no-install tsx --test "...[[]...path[]]..."`, and npx hands its arguments to a second
|
|
19
|
+
* `sh -c`, quoting only those with characters such as `(`, `*` or a space; that shell expanded the
|
|
20
|
+
* unquoted class back to the real `[...path]` directory. The pre-run check now models that second
|
|
21
|
+
* shell. The count check could not see one missing file among 120 tests, so a `node --test` selection
|
|
22
|
+
* also runs with a probe that records the file each test process started for (`traceNodeTestFiles`),
|
|
23
|
+
* and a selected file that never started blocks the verification.
|
|
14
24
|
*/
|
|
15
25
|
/** The arguments `sh` (or `cmd.exe` on Windows) would hand the program, for the quoting DiffCI emits. */
|
|
16
26
|
export function commandArguments(command, windows = process.platform === "win32") {
|
|
@@ -47,29 +57,92 @@ export function commandArguments(command, windows = process.platform === "win32"
|
|
|
47
57
|
args.push(current);
|
|
48
58
|
return args;
|
|
49
59
|
}
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
|
|
60
|
+
/** Arguments npm's `sh` escaping leaves unquoted when npx re-runs a bin through `sh -c`
|
|
61
|
+
* (@npmcli/promise-spawn): those without whitespace or any of ``"#$&'()*;<>?\`|~``. */
|
|
62
|
+
const NPM_UNQUOTED = /^[^\s"#$&'()*;<>?\\`|~]+$/;
|
|
63
|
+
/** The file patterns of each `node --test` invocation in `command` (directly, or through tsx). Paths
|
|
64
|
+
* npx passes to a second `sh` unquoted are marked: that shell expands a pattern that matches files. */
|
|
65
|
+
function nodeTestPatterns(command, windows) {
|
|
66
|
+
const patterns = [];
|
|
53
67
|
let segment = [];
|
|
54
|
-
for (const arg of [...commandArguments(command), "&&"]) {
|
|
68
|
+
for (const arg of [...commandArguments(command, windows), "&&"]) {
|
|
55
69
|
if (arg !== "&&") {
|
|
56
70
|
segment.push(arg);
|
|
57
71
|
continue;
|
|
58
72
|
}
|
|
59
73
|
const testFlag = segment.indexOf("--test");
|
|
60
74
|
if (testFlag > 0 && (segment[0] === "node" || segment.slice(0, testFlag).includes("tsx"))) {
|
|
61
|
-
|
|
75
|
+
const viaNpx = !windows && (segment[0] === "npx" || (segment[0] === "npm" && segment[1] === "exec"));
|
|
76
|
+
for (const pattern of segment.slice(testFlag + 1).filter((value) => !value.startsWith("-"))) {
|
|
77
|
+
patterns.push({ pattern, reglobbed: viaNpx && NPM_UNQUOTED.test(pattern) });
|
|
78
|
+
}
|
|
62
79
|
}
|
|
63
80
|
segment = [];
|
|
64
81
|
}
|
|
65
|
-
return
|
|
82
|
+
return patterns;
|
|
83
|
+
}
|
|
84
|
+
/** Whether node --test, handed `pattern` by `command`, would run `path`. A pattern the second shell
|
|
85
|
+
* expands reaches node as the literal path it matched, which node then reads as a glob again. */
|
|
86
|
+
function claims({ pattern, reglobbed }, path) {
|
|
87
|
+
return matchesGlob(path, pattern) && (!reglobbed || matchesGlob(path, path));
|
|
66
88
|
}
|
|
67
89
|
/** Selected files no `node --test` pattern in `command` matches. Empty when `command` runs no `node --test`. */
|
|
68
|
-
export function unmatchedNodeTests(command, selectedTests) {
|
|
69
|
-
const patterns = nodeTestPatterns(command)
|
|
90
|
+
export function unmatchedNodeTests(command, selectedTests, windows = process.platform === "win32") {
|
|
91
|
+
const patterns = nodeTestPatterns(command, windows);
|
|
70
92
|
if (patterns.length === 0)
|
|
71
93
|
return [];
|
|
72
|
-
return selectedTests.filter((path) => !patterns.some((pattern) =>
|
|
94
|
+
return selectedTests.filter((path) => !patterns.some((pattern) => claims(pattern, path)));
|
|
95
|
+
}
|
|
96
|
+
/** Selected files `command` hands `node --test`, which the trace from `traceNodeTestFiles` must show. */
|
|
97
|
+
export function selectedNodeTests(command, selectedTests, windows = process.platform === "win32") {
|
|
98
|
+
const patterns = nodeTestPatterns(command, windows);
|
|
99
|
+
return selectedTests.filter((path) => patterns.some(({ pattern }) => pattern === path || matchesGlob(path, pattern)));
|
|
100
|
+
}
|
|
101
|
+
/** Records the file each node:test process starts for. node --test runs every file in a child process
|
|
102
|
+
* with NODE_TEST_CONTEXT set and the file as argv[1]; NODE_OPTIONS reaches it through npx and tsx.
|
|
103
|
+
* Under `--test-isolation=none` no child starts and the trace stays empty, which proves nothing. */
|
|
104
|
+
const PROBE = `"use strict";
|
|
105
|
+
if (process.env.NODE_TEST_CONTEXT && process.argv[1] && process.env.DIFFCI_NODE_TEST_TRACE) {
|
|
106
|
+
try { require("node:fs").appendFileSync(process.env.DIFFCI_NODE_TEST_TRACE, process.argv[1] + "\\n"); } catch {}
|
|
107
|
+
}
|
|
108
|
+
`;
|
|
109
|
+
export function traceNodeTestFiles(cwd, nodeOptions = process.env.NODE_OPTIONS) {
|
|
110
|
+
const dir = mkdtempSync(join(tmpdir(), "diffci-node-test-trace-"));
|
|
111
|
+
const probe = join(dir, "probe.cjs");
|
|
112
|
+
const log = join(dir, "started.txt");
|
|
113
|
+
writeFileSync(probe, PROBE);
|
|
114
|
+
// NODE_OPTIONS reads a backslash inside double quotes as an escape; forward slashes work on Windows.
|
|
115
|
+
const required = `--require "${probe.split(sep).join("/")}"`;
|
|
116
|
+
const real = (path) => { try {
|
|
117
|
+
return realpathSync.native(path);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return path;
|
|
121
|
+
} };
|
|
122
|
+
return {
|
|
123
|
+
env: { NODE_OPTIONS: nodeOptions?.trim() ? `${nodeOptions} ${required}` : required, DIFFCI_NODE_TEST_TRACE: log },
|
|
124
|
+
read() {
|
|
125
|
+
let lines;
|
|
126
|
+
try {
|
|
127
|
+
lines = readFileSync(log, "utf8").split("\n").filter(Boolean);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
const root = real(cwd);
|
|
133
|
+
const files = lines.map((file) => relative(root, real(file)).split(sep).join("/"));
|
|
134
|
+
return files.length ? [...new Set(files)].sort() : undefined;
|
|
135
|
+
},
|
|
136
|
+
dispose() { rmSync(dir, { recursive: true, force: true }); },
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/** Selected `node --test` files the trace does not show starting. Empty when the trace proves nothing. */
|
|
140
|
+
export function unstartedNodeTests(expected, started, windows = process.platform === "win32") {
|
|
141
|
+
if (!started?.length)
|
|
142
|
+
return [];
|
|
143
|
+
const key = (path) => windows ? path.toLowerCase() : path;
|
|
144
|
+
const seen = new Set(started.map(key));
|
|
145
|
+
return expected.filter((path) => !seen.has(key(path)));
|
|
73
146
|
}
|
|
74
147
|
/** The test count node:test's summary reports, or the test-file total vitest or jest reports. */
|
|
75
148
|
export function runnerTestCount(output) {
|
|
@@ -159,7 +159,9 @@ interface ResolvedSelection {
|
|
|
159
159
|
observationSha256?: string;
|
|
160
160
|
observerVersion?: string;
|
|
161
161
|
}
|
|
162
|
-
export declare function measureCommand(command: string, options: Pick<VerifySavingsOptions, "cwd" | "timeoutMs" | "tailBytes">
|
|
162
|
+
export declare function measureCommand(command: string, options: Pick<VerifySavingsOptions, "cwd" | "timeoutMs" | "tailBytes"> & {
|
|
163
|
+
env?: Record<string, string>;
|
|
164
|
+
}): CommandMeasurement;
|
|
163
165
|
export declare function buildVerifySavingsReport(input: {
|
|
164
166
|
producedAt?: string;
|
|
165
167
|
label?: string;
|
|
@@ -262,6 +262,7 @@ export function measureCommand(command, options) {
|
|
|
262
262
|
windowsVerbatimArguments: process.platform === "win32",
|
|
263
263
|
env: {
|
|
264
264
|
...withoutTestRunnerContext(process.env),
|
|
265
|
+
...options.env,
|
|
265
266
|
CI: "1",
|
|
266
267
|
FORCE_COLOR: "0",
|
|
267
268
|
COREPACK_ENABLE_DOWNLOAD_PROMPT: "0",
|
|
@@ -7,7 +7,7 @@ import { collectEnforcementContext, evaluateEnforcement } from "./enforce-policy
|
|
|
7
7
|
import { inferFullCommand, inferSelectedCommand } from "./full-command.js";
|
|
8
8
|
import { plannedChecks, runChecks } from "./gate-checks.js";
|
|
9
9
|
import { makeGitRunner, observe } from "./observe.js";
|
|
10
|
-
import { unmatchedNodeTests } from "./selected-coverage.js";
|
|
10
|
+
import { selectedNodeTests, traceNodeTestFiles, unmatchedNodeTests, unstartedNodeTests } from "./selected-coverage.js";
|
|
11
11
|
import { captureWorkingTreeSnapshot, snapshotChanges } from "./working-tree.js";
|
|
12
12
|
export const VERIFICATION_SCHEMA = "diffci.verification.v1";
|
|
13
13
|
function receiptRange(range) {
|
|
@@ -129,9 +129,20 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
|
|
|
129
129
|
const preexistingNote = preexistingChecks.length
|
|
130
130
|
? `; gate check(s) ${preexistingChecks.map((check) => check.id).join(", ")} also fail at the base commit (already broken before this change)`
|
|
131
131
|
: "";
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
132
|
+
// Selected `node --test` files run under a probe that records which of them actually started.
|
|
133
|
+
const expectedNodeTests = selection === "selected" && result ? selectedNodeTests(command, result.selectedTests) : [];
|
|
134
|
+
const trace = expectedNodeTests.length && !checkRun?.failure ? traceNodeTestFiles(options.repoPath) : undefined;
|
|
135
|
+
let startedNodeTests;
|
|
136
|
+
let execution;
|
|
137
|
+
try {
|
|
138
|
+
execution = checkRun?.failure
|
|
139
|
+
? checkRun.failure.measurement
|
|
140
|
+
: measureCommands(commands, { cwd: options.repoPath, timeoutMs: Math.max(options.timeoutMs - (checkRun?.wallMs ?? 0), 0), tailBytes: options.tailBytes, env: trace?.env });
|
|
141
|
+
startedNodeTests = trace?.read();
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
trace?.dispose();
|
|
145
|
+
}
|
|
135
146
|
let after;
|
|
136
147
|
try {
|
|
137
148
|
after = captureWorkingTreeSnapshot(options.repoPath);
|
|
@@ -167,23 +178,28 @@ async function executeWithPolicy(options, scope, before, observation, enforcemen
|
|
|
167
178
|
// Every selected file contributes at least one test (node:test) or test file (vitest, jest) to the
|
|
168
179
|
// runner's summary; a smaller count means some selected tests never ran, which is not a pass.
|
|
169
180
|
const selectedCount = selection === "selected" && result ? result.selectedTests.length : 0;
|
|
170
|
-
|
|
181
|
+
// A count of 120 cannot show one missing file (2026-11-02); the probe's record of started files can.
|
|
182
|
+
const unstarted = succeeded ? unstartedNodeTests(expectedNodeTests, startedNodeTests) : [];
|
|
183
|
+
const undercounted = succeeded && execution.runnerTestCount !== undefined && execution.runnerTestCount < selectedCount;
|
|
184
|
+
const unexecuted = unstarted.length > 0 || undercounted;
|
|
171
185
|
const verification = !unchanged || unexecuted ? "blocked" : succeeded ? "passed" : "failed";
|
|
172
186
|
const finalReason = !unchanged
|
|
173
187
|
? before.baseSha !== after.baseSha
|
|
174
188
|
? "HEAD moved while verification was running; rerun DiffCI for the new snapshot"
|
|
175
189
|
: `the working tree changed while verification was running (${altered.slice(0, 5).map((change) => `${change.status} ${change.path}`).join(", ")}${altered.length > 5 ? `, ${altered.length - 5} more` : ""}); rerun DiffCI for the new snapshot`
|
|
176
|
-
:
|
|
177
|
-
? `
|
|
178
|
-
:
|
|
179
|
-
?
|
|
180
|
-
:
|
|
181
|
-
?
|
|
182
|
-
:
|
|
183
|
-
? `
|
|
184
|
-
:
|
|
185
|
-
?
|
|
186
|
-
:
|
|
190
|
+
: unstarted.length
|
|
191
|
+
? `node --test never started ${unstarted.length} selected test file(s), such as ${unstarted[0]}, so the selection did not run as written; run the full test command instead`
|
|
192
|
+
: unexecuted
|
|
193
|
+
? `the runner reported ${String(execution.runnerTestCount)} test(s) for ${selectedCount} selected test file(s), so some selected tests did not run; run the full test command instead`
|
|
194
|
+
: succeeded
|
|
195
|
+
? checks ? `${reason}; ${checkSummary(checks)}` : reason
|
|
196
|
+
: failedCheck
|
|
197
|
+
? `gate check ${failedCheck.id} ${failedCheck.status === "timed_out" ? "timed out" : `failed with exit code ${String(failedCheck.exit_code)}`}; tests were not run (${failedCheck.command})`
|
|
198
|
+
: execution.timedOut
|
|
199
|
+
? `verification timed out after ${options.timeoutMs}ms${preexistingNote}`
|
|
200
|
+
: testsPassed
|
|
201
|
+
? `${preexistingChecks.length} gate check(s) failed that also fail at the base commit; nothing this change introduced failed (${preexistingChecks.map((check) => check.id).join(", ")})`
|
|
202
|
+
: `verification command failed with exit code ${String(execution.exitCode)}${preexistingNote}`;
|
|
187
203
|
const baselineSha = scope === "commit-range" ? range?.baseSha : before.baseSha;
|
|
188
204
|
const failureBaseline = verification === "failed" && !failedCheck && !execution.timedOut && options.baselineOnFailure && baselineSha
|
|
189
205
|
? compareWithBaseline({ repoPath: options.repoPath, baseSha: baselineSha, headSha: scope === "commit-range" ? before.baseSha : before.commitSha, commands, headFailures: execution.failingTests ?? [], timeoutMs: options.timeoutMs })
|
|
@@ -103,11 +103,25 @@ function runInvokesDiffCiVerification(run) {
|
|
|
103
103
|
* product generates keeps matching: `npm install … @diffci/observer@1.4.2`,
|
|
104
104
|
* `"${RUNNER_TEMP}/diffci/node_modules/.bin/diffci" observe`, `docker run … <image>@sha256:… observe`,
|
|
105
105
|
* `npx @diffci/observer observe` all name DiffCI outside any URL.
|
|
106
|
+
*
|
|
107
|
+
* The same holds for four other kinds of data (2026-11-02): plain `echo`/`printf` messages, `gh api`
|
|
108
|
+
* fields and `repos/...` paths, SCREAMING_SNAKE environment variable names, and `.json` paths, which
|
|
109
|
+
* are read rather than run. Core's own release workflow mentions `DIFFCI_PRODUCT_DISPATCH_TOKEN` in an
|
|
110
|
+
* error message, dispatches `-f event_type=diffci-core-release` to `repos/DiffCI/DiffCI.com`, and reads
|
|
111
|
+
* `./packages/diffci-cli/package.json`, and `check` reported both of those jobs as badly installed
|
|
112
|
+
* observers. An echo line with a substitution, pipe or command separator is kept, because it can run
|
|
113
|
+
* something.
|
|
106
114
|
*/
|
|
107
115
|
function commandText(run) {
|
|
108
116
|
return run
|
|
109
117
|
.split("\n")
|
|
110
118
|
.map((line) => line.replace(/(^|\s)#.*$/, "$1").replace(/[a-z][a-z0-9+.-]*:\/\/\S+/gi, " "))
|
|
119
|
+
.map((line) => (/^\s*(?:echo|printf)\s/.test(line) && !/\$\(|`|\||&&|;/.test(line) ? "" : line))
|
|
120
|
+
.map((line) => line
|
|
121
|
+
.replace(/(^|\s)(?:-[fF]|--(?:raw-)?field)\s+(?:"[^"]*"|'[^']*'|\S+)/g, "$1")
|
|
122
|
+
.replace(/(^|[\s"'])repos\/[^\s"']+/g, "$1")
|
|
123
|
+
.replace(/\$?\{?\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b\}?/g, " ")
|
|
124
|
+
.replace(/[^\s"'()]*\.json\b/g, " "))
|
|
111
125
|
// A literal npm registry tag removal neither installs nor invokes the observer. Match the
|
|
112
126
|
// entire line, with only a literal `|| true` allowed, so appended observer commands and shell
|
|
113
127
|
// substitutions still take the conservative inspection path. Other script lines remain intact.
|
|
@@ -42,6 +42,9 @@ export interface PackageJsonChange {
|
|
|
42
42
|
testScriptAddedPaths: string[];
|
|
43
43
|
/** Dependency names whose entry changed, when `kind` is `dependencies`. */
|
|
44
44
|
changedDependencies: string[];
|
|
45
|
+
/** `kind` is `dependencies` and the edit only changed the request of a dependency that stays in
|
|
46
|
+
* the same field (no addition, removal or move between fields, and nothing but metadata besides). */
|
|
47
|
+
specifiersOnly: boolean;
|
|
45
48
|
}
|
|
46
49
|
/**
|
|
47
50
|
* How a modified package.json changed:
|
|
@@ -3,6 +3,7 @@ import { dirname, posix } from "node:path";
|
|
|
3
3
|
import { infrastructureRole, isImplicitlyLoadedFile, testScriptClosure } from "../repo/file-references.js";
|
|
4
4
|
import { workflowMayRunTests } from "../repo/workflow-test-steps.js";
|
|
5
5
|
import { npmLockAffectedDependencies } from "../repo/npm-lockfile.js";
|
|
6
|
+
import { pnpmLockAffectedDependencies } from "../repo/pnpm-lockfile.js";
|
|
6
7
|
import { yarnLockAffectedDependencies } from "../repo/yarn-lockfile.js";
|
|
7
8
|
import { LOCKFILE } from "../repo/lockfiles.js";
|
|
8
9
|
export const EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
|
|
@@ -326,7 +327,7 @@ function yarnDirectDependencies(content) {
|
|
|
326
327
|
* workspaces and unparseable JSON.
|
|
327
328
|
*/
|
|
328
329
|
export function packageJsonChange(oldContent, newContent) {
|
|
329
|
-
const result = (kind, testScriptAddedPaths = [], changedDependencies = []) => ({ kind, testScriptAddedPaths, changedDependencies });
|
|
330
|
+
const result = (kind, testScriptAddedPaths = [], changedDependencies = [], specifiersOnly = false) => ({ kind, testScriptAddedPaths, changedDependencies, specifiersOnly });
|
|
330
331
|
if (!hasRelevantPackageJsonChange(oldContent, newContent))
|
|
331
332
|
return result("metadata");
|
|
332
333
|
let oldJson;
|
|
@@ -345,23 +346,33 @@ export function packageJsonChange(oldContent, newContent) {
|
|
|
345
346
|
const closure = new Set([...testScriptClosure(oldScripts), ...testScriptClosure(newScripts)]);
|
|
346
347
|
const added = new Set();
|
|
347
348
|
const dependencies = new Set();
|
|
349
|
+
let specifiersOnly = true;
|
|
348
350
|
for (const field of new Set([...Object.keys(oldJson), ...Object.keys(newJson)])) {
|
|
349
|
-
if (PACKAGE_JSON_METADATA_FIELDS.has(field)
|
|
351
|
+
if (PACKAGE_JSON_METADATA_FIELDS.has(field))
|
|
350
352
|
continue;
|
|
351
353
|
if (JSON.stringify(oldJson[field]) === JSON.stringify(newJson[field]))
|
|
352
354
|
continue;
|
|
355
|
+
if (PACKAGE_JSON_DATA_FIELDS.has(field)) {
|
|
356
|
+
specifiersOnly = false;
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
353
359
|
if (DEPENDENCY_FIELDS.has(field)) {
|
|
354
360
|
const before = scriptRecord(oldJson[field]);
|
|
355
361
|
const after = scriptRecord(newJson[field]);
|
|
356
362
|
if (!before || !after)
|
|
357
363
|
return result("behavioral");
|
|
358
|
-
for (const name of new Set([...Object.keys(before), ...Object.keys(after)]))
|
|
359
|
-
if (before[name]
|
|
360
|
-
|
|
364
|
+
for (const name of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
|
365
|
+
if (before[name] === after[name])
|
|
366
|
+
continue;
|
|
367
|
+
dependencies.add(name);
|
|
368
|
+
if (before[name] === undefined || after[name] === undefined)
|
|
369
|
+
specifiersOnly = false;
|
|
370
|
+
}
|
|
361
371
|
continue;
|
|
362
372
|
}
|
|
363
373
|
if (field !== "scripts")
|
|
364
374
|
return result("behavioral");
|
|
375
|
+
specifiersOnly = false;
|
|
365
376
|
for (const name of new Set([...Object.keys(oldScripts), ...Object.keys(newScripts)])) {
|
|
366
377
|
if (oldScripts[name] === newScripts[name] || !closure.has(name))
|
|
367
378
|
continue;
|
|
@@ -372,7 +383,9 @@ export function packageJsonChange(oldContent, newContent) {
|
|
|
372
383
|
added.add(path);
|
|
373
384
|
}
|
|
374
385
|
}
|
|
375
|
-
return
|
|
386
|
+
return dependencies.size > 0
|
|
387
|
+
? result("dependencies", [...added].sort(), [...dependencies].sort(), specifiersOnly)
|
|
388
|
+
: result("data", [...added].sort());
|
|
376
389
|
}
|
|
377
390
|
/** packageJsonChange's kind, with a dependency change reported as behavioral. */
|
|
378
391
|
export function packageJsonChangeKind(oldContent, newContent) {
|
|
@@ -389,6 +402,18 @@ function readFileAtSha(sha, path, repoPath) {
|
|
|
389
402
|
return undefined;
|
|
390
403
|
return result.stdout;
|
|
391
404
|
}
|
|
405
|
+
/** Root entries include directories and gitlinks, which recursive file inventories can omit. */
|
|
406
|
+
function readRootPathsAtSha(sha, repoPath) {
|
|
407
|
+
const result = runGit(["ls-tree", "--full-tree", "--name-only", "-z", sha], repoPath);
|
|
408
|
+
if (result.status !== 0 || !result.stdout.endsWith("\0"))
|
|
409
|
+
return undefined;
|
|
410
|
+
const paths = result.stdout.slice(0, -1).split("\0");
|
|
411
|
+
// An absence decision needs a complete listing. Keep whitespace and backslashes literal.
|
|
412
|
+
if (paths.some((path) => !path || path === "." || path === ".." || path.includes("/")))
|
|
413
|
+
return undefined;
|
|
414
|
+
const roots = new Set(paths);
|
|
415
|
+
return roots.size === paths.length ? roots : undefined;
|
|
416
|
+
}
|
|
392
417
|
export function computeAnalysis(files) {
|
|
393
418
|
const paths = files.flatMap((f) => f.oldPath ? [f.path, f.oldPath] : [f.path]);
|
|
394
419
|
const matching = (test) => [...new Set(paths.filter(test))].sort();
|
|
@@ -581,6 +606,8 @@ export async function analyzeGitDelta(options = {}) {
|
|
|
581
606
|
referenceResolvedPaths.push("package.json");
|
|
582
607
|
if (packageChange.testScriptAddedPaths.length > 0)
|
|
583
608
|
analysis.testScriptAddedPaths = packageChange.testScriptAddedPaths;
|
|
609
|
+
if (packageChange.specifiersOnly)
|
|
610
|
+
analysis.packageJsonSpecifiersOnly = true;
|
|
584
611
|
}
|
|
585
612
|
}
|
|
586
613
|
}
|
|
@@ -598,8 +625,13 @@ export async function analyzeGitDelta(options = {}) {
|
|
|
598
625
|
const afterDirect = yarnDirectDependencies(newPackageJson);
|
|
599
626
|
// A second package manager or alternate Yarn install layout is outside this model, even when
|
|
600
627
|
// its configuration did not change in this delta.
|
|
601
|
-
const
|
|
602
|
-
|
|
628
|
+
const alternateLayouts = ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "bun.lock", "bun.lockb", ".yarnrc", ".yarnrc.yml", ".pnp.js", ".pnp.cjs"];
|
|
629
|
+
const unsupportedLayout = [baseSha, headSha].some((sha) => {
|
|
630
|
+
const roots = readRootPathsAtSha(sha, repoPath);
|
|
631
|
+
// Either revision can rule out narrowing, including a layout deleted before HEAD.
|
|
632
|
+
// An unavailable or malformed listing cannot prove that these paths are absent.
|
|
633
|
+
return !roots || alternateLayouts.some((path) => roots.has(path));
|
|
634
|
+
});
|
|
603
635
|
const affected = beforeDirect && afterDirect && !unsupportedLayout
|
|
604
636
|
? yarnLockAffectedDependencies(readFileAtSha(baseSha, "yarn.lock", repoPath), readFileAtSha(headSha, "yarn.lock", repoPath), beforeDirect, afterDirect)
|
|
605
637
|
: undefined;
|
|
@@ -615,6 +647,59 @@ export async function analyzeGitDelta(options = {}) {
|
|
|
615
647
|
referenceResolvedPaths.push("package.json");
|
|
616
648
|
if (packageChange.testScriptAddedPaths.length > 0)
|
|
617
649
|
analysis.testScriptAddedPaths = packageChange.testScriptAddedPaths;
|
|
650
|
+
if (packageChange.specifiersOnly)
|
|
651
|
+
analysis.packageJsonSpecifiersOnly = true;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
// 2026-11-02: pnpm records each snapshot's resolved edges, peers included, so attribution follows
|
|
656
|
+
// the npm model (src/repo/pnpm-lockfile.ts). Single-project lockfiles only; pnpm's own
|
|
657
|
+
// configuration files can change resolution or hoisting without a lockfile difference.
|
|
658
|
+
const changedPnpmLock = filesWithBinary.find((f) => f.path === "pnpm-lock.yaml" && f.changeType === "modified");
|
|
659
|
+
const otherPnpmConfiguration = allPaths.some((path) => path !== "pnpm-lock.yaml" && path !== "package.json" && (LOCKFILE.test(posix.basename(path))
|
|
660
|
+
|| /^(?:\.npmrc|pnpm-workspace\.yaml|\.pnpmfile\.cjs)$/.test(path)
|
|
661
|
+
|| CONFIG_PATTERNS.some((pattern) => pattern.test(path) || pattern.test(posix.basename(path)))
|
|
662
|
+
|| isImplicitlyLoadedFile(path)));
|
|
663
|
+
if (dependencyEdit && changedPnpmLock && !otherPnpmConfiguration && (!analysis.dependencyManifestChanged || changedPackageJson)) {
|
|
664
|
+
const manifests = [oldPackageJson, newPackageJson].map((content) => { try {
|
|
665
|
+
return JSON.parse(content ?? "");
|
|
666
|
+
}
|
|
667
|
+
catch {
|
|
668
|
+
return undefined;
|
|
669
|
+
} });
|
|
670
|
+
const direct = new Set();
|
|
671
|
+
let modelled = manifests.every((manifest) => manifest && manifest.workspaces === undefined
|
|
672
|
+
&& (manifest.packageManager === undefined || (typeof manifest.packageManager === "string" && manifest.packageManager.startsWith("pnpm@"))));
|
|
673
|
+
for (const manifest of manifests) {
|
|
674
|
+
for (const field of DEPENDENCY_FIELDS) {
|
|
675
|
+
const record = scriptRecord(manifest?.[field]);
|
|
676
|
+
if (!record) {
|
|
677
|
+
modelled = false;
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
for (const name of Object.keys(record))
|
|
681
|
+
direct.add(name);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
const unsupportedLayout = ["package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "bun.lock", "bun.lockb"]
|
|
685
|
+
.some((path) => [baseSha, headSha].some((sha) => readFileAtSha(sha, path, repoPath) !== undefined));
|
|
686
|
+
const affected = modelled && !unsupportedLayout
|
|
687
|
+
? pnpmLockAffectedDependencies(readFileAtSha(baseSha, "pnpm-lock.yaml", repoPath), readFileAtSha(headSha, "pnpm-lock.yaml", repoPath), [...direct])
|
|
688
|
+
: undefined;
|
|
689
|
+
if (affected && (packageChange?.changedDependencies ?? []).every((name) => affected.includes(name))) {
|
|
690
|
+
analysis.dependencyManifestChanged = false;
|
|
691
|
+
analysis.lockfileChanged = false;
|
|
692
|
+
analysis.changedDependencies = affected;
|
|
693
|
+
analysis.dependencyLockfile = "pnpm-lock.yaml";
|
|
694
|
+
narrowed.add(changedPnpmLock);
|
|
695
|
+
if (changedPackageJson) {
|
|
696
|
+
narrowed.add(changedPackageJson);
|
|
697
|
+
if (packageChange.kind !== "metadata" && !referenceResolvedPaths.includes("package.json"))
|
|
698
|
+
referenceResolvedPaths.push("package.json");
|
|
699
|
+
if (packageChange.testScriptAddedPaths.length > 0)
|
|
700
|
+
analysis.testScriptAddedPaths = packageChange.testScriptAddedPaths;
|
|
701
|
+
if (packageChange.specifiersOnly)
|
|
702
|
+
analysis.packageJsonSpecifiersOnly = true;
|
|
618
703
|
}
|
|
619
704
|
}
|
|
620
705
|
}
|