@diffci.com/diffci 0.3.16 → 0.3.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist-client/src/client/agent-selection.js +14 -4
  2. package/dist-client/src/client/cli.js +6 -1
  3. package/dist-client/src/client/gate-checks.js +120 -0
  4. package/dist-client/src/client/hook.js +9 -0
  5. package/dist-client/src/client/verify.js +30 -7
  6. package/node_modules/@diffci.com/core/dist/git/git-diff.js +6 -2
  7. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  8. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.d.ts +45 -0
  9. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js +252 -0
  10. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js.map +1 -0
  11. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.d.ts +60 -0
  12. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js +241 -0
  13. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js.map +1 -0
  14. package/node_modules/@diffci.com/core/dist/planner/script-reads.d.ts +31 -0
  15. package/node_modules/@diffci.com/core/dist/planner/script-reads.js +197 -0
  16. package/node_modules/@diffci.com/core/dist/planner/script-reads.js.map +1 -0
  17. package/node_modules/@diffci.com/core/dist/planner/type-program.d.ts +33 -0
  18. package/node_modules/@diffci.com/core/dist/planner/type-program.js +106 -0
  19. package/node_modules/@diffci.com/core/dist/planner/type-program.js.map +1 -0
  20. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +14 -2
  21. package/node_modules/@diffci.com/core/dist/repo/file-references.js +42 -1
  22. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +4 -0
  24. package/node_modules/@diffci.com/core/dist/repo/impact.js +34 -3
  25. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  26. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +23 -1
  27. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -1
  28. package/node_modules/@diffci.com/core/src/git/git-diff.ts +5 -2
  29. package/node_modules/@diffci.com/core/src/planner/check-narrowing.ts +269 -0
  30. package/node_modules/@diffci.com/core/src/planner/pipeline-steps.ts +243 -0
  31. package/node_modules/@diffci.com/core/src/planner/script-reads.ts +174 -0
  32. package/node_modules/@diffci.com/core/src/planner/type-program.ts +103 -0
  33. package/node_modules/@diffci.com/core/src/repo/file-references.ts +44 -2
  34. package/node_modules/@diffci.com/core/src/repo/impact.ts +31 -3
  35. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +22 -1
  36. package/package.json +2 -2
@@ -0,0 +1,174 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * Which paths does a repository check script read? (2026-10-29, docs/design/pipeline-impact.md, phase 1
4
+ * slice 3.)
5
+ *
6
+ * This is the inverse of the reference resolver (`src/repo/file-references.ts`): there the question is
7
+ * "which files name the changed path", here it is "which paths does this check name". Dogfood check
8
+ * scripts name what they walk: `sourceFiles(path.join(root, "src"))`, `join(root,
9
+ * "ops/cloudflare/d1-migrations")`, `readFileSync(join(root, "package.json"))`. A script that names `src`
10
+ * reads everything under `src/`; a change elsewhere cannot change its result.
11
+ *
12
+ * THE RULE. The script's closure is the script file plus every relative module it imports, transitively.
13
+ * Its reads are every string literal in the closure, and every argument on its command line, that is a
14
+ * tracked file or directory (relative to the repository root or to the module's directory), plus the
15
+ * static prefix of each template literal. The check runs when a changed path:
16
+ *
17
+ * - is in the closure (the check's own code changed);
18
+ * - is, or is under, a path the closure names; or has a basename the closure names (`"index.ts"`);
19
+ * - is package.json or a lockfile and the closure imports a package or names package.json.
20
+ *
21
+ * FAILING CLOSED. The check runs as written, for any change, when its reads cannot be bounded: it runs
22
+ * another program (child_process), walks the repository root or the working directory, uses a glob that
23
+ * starts at the root, reads a path from the environment, its closure cannot be read or is too large, or the
24
+ * command is not `node`/`tsx`/`bun` running one JavaScript or TypeScript file.
25
+ *
26
+ * RESIDUAL RISK. A path assembled from parts that never appear as literals (`["s", "rc"].join("")`) is not
27
+ * seen, as in the reference resolver. Required CI stays authoritative.
28
+ */
29
+
30
+ import { posix } from "node:path";
31
+ import ts from "typescript";
32
+ import type { NarrowingInput } from "./check-narrowing.js";
33
+ import type { GateCheck } from "./pipeline-steps.js";
34
+
35
+ const MAX_CLOSURE = 400;
36
+ const LOCKFILE = /^(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/;
37
+ const SCRIPT_FILE = /\.(?:[cm]?js|[cm]?ts|tsx|jsx)$/;
38
+ const RESOLVE_EXTENSIONS = ["", ".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", "/index.js", "/index.mjs", "/index.ts", "/index.tsx"];
39
+ const VALUE_FLAGS = new Set(["--import", "-r", "--require", "--loader", "--experimental-loader", "--conditions", "-C", "--env-file", "--tsconfig"]);
40
+
41
+ const SPAWNS = /\bchild_process\b|\bexeca\b|\bzx\b|\bBun\.spawn|\bDeno\.Command/;
42
+ const ROOT_NAME = String.raw`(?:root|ROOT|repoRoot|REPO_ROOT|rootDir|ROOT_DIR|projectRoot|PROJECT_ROOT|repositoryRoot|REPOSITORY_ROOT|cwd|process\.cwd\(\)|["'\`]\.{0,2}\/?["'\`])`;
43
+ /** A directory walk, glob or listing that starts at the repository root or the working directory. */
44
+ const WALKS_ROOT = new RegExp(String.raw`\b(?:readdirSync|readdir|opendirSync|opendir|globSync|glob|globby|fg|fastGlob|walk\w*|list\w*|\w*[Ff]iles|scan\w*|collect\w*)\s*\(\s*${ROOT_NAME}\s*[,)]|\bcwd\s*:\s*${ROOT_NAME}|["'\`](?:\.\/)?\*\*`);
45
+ const ENV_PATH = /process\.env\.\w*(?:PATH|DIR|ROOT|FILE)\b|process\.env\[/;
46
+
47
+ /**
48
+ * String literals (and each template's static head) and module specifiers, read with the TypeScript
49
+ * parser: regular expressions, comments and templates with substitutions defeat a regex scan (one
50
+ * swallowed `path.join(root, "src")` across lines). Undefined when a `require` or `import()` takes a
51
+ * computed specifier.
52
+ */
53
+ function scanModule(path: string, text: string): { literals: string[]; imports: string[] } | undefined {
54
+ const kind = /\.tsx$/.test(path) ? ts.ScriptKind.TSX : /\.[cm]?ts$/.test(path) ? ts.ScriptKind.TS : /\.jsx$/.test(path) ? ts.ScriptKind.JSX : ts.ScriptKind.JS;
55
+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, false, kind);
56
+ const literals: string[] = [];
57
+ const imports: string[] = [];
58
+ let computed = false;
59
+ const visit = (node: ts.Node): void => {
60
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
61
+ imports.push(node.moduleSpecifier.text);
62
+ } else if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(node.expression) && node.expression.text === "require"))) {
63
+ const [argument] = node.arguments;
64
+ if (argument && ts.isStringLiteralLike(argument)) imports.push(argument.text);
65
+ else computed = true;
66
+ }
67
+ if (ts.isStringLiteralLike(node)) literals.push(node.text);
68
+ else if (ts.isTemplateExpression(node)) literals.push(node.head.text);
69
+ ts.forEachChild(node, visit);
70
+ };
71
+ visit(source);
72
+ return computed ? undefined : { literals, imports };
73
+ }
74
+
75
+ interface Reads {
76
+ closure: Set<string>;
77
+ paths: Set<string>;
78
+ basenames: Set<string>;
79
+ importsPackages: boolean;
80
+ }
81
+
82
+ /** The file a `node`/`tsx`/`bun` leaf runs, and its remaining arguments. */
83
+ function scriptOf(command: string): { file: string; args: string[] } | undefined {
84
+ const words = command.trim().split(/\s+/);
85
+ let index = 0;
86
+ if (words[index] === "npx") { index++; if (words[index] === "--no-install") index++; }
87
+ if (!["node", "tsx", "bun", "ts-node"].includes(words[index] ?? "")) return undefined;
88
+ if (words[index] === "bun" && words[index + 1] === "run") index++;
89
+ for (index++; index < words.length && words[index]!.startsWith("-"); index++) {
90
+ if (VALUE_FLAGS.has(words[index]!) ) index++;
91
+ }
92
+ const file = words[index];
93
+ if (!file || !SCRIPT_FILE.test(file) || /["'$`]/.test(command)) return undefined;
94
+ return { file: posix.normalize(file), args: words.slice(index + 1) };
95
+ }
96
+
97
+ function directories(files: readonly string[]): Set<string> {
98
+ const dirs = new Set<string>();
99
+ for (const file of files) for (let dir = posix.dirname(file); dir !== "." && !dirs.has(dir); dir = posix.dirname(dir)) dirs.add(dir);
100
+ return dirs;
101
+ }
102
+
103
+ /** Reads of the script's closure, or a reason they cannot be bounded. */
104
+ function collectReads(entry: string, args: readonly string[], input: NarrowingInput, files: readonly string[]): Reads | string {
105
+ const tracked = new Set(files);
106
+ const dirs = directories(files);
107
+ const reads: Reads = { closure: new Set(), paths: new Set(), basenames: new Set(), importsPackages: false };
108
+ const addLiteral = (literal: string, from: string): void => {
109
+ const value = literal.replace(/\\\\/g, "/").trim();
110
+ if (!value || value.length > 300 || /[\s*?{}<>|]/.test(value.replace(/\/$/, ""))) return;
111
+ for (const base of [".", posix.dirname(from)]) {
112
+ const path = posix.normalize(posix.join(base, value)).replace(/\/$/, "");
113
+ if (path.startsWith("..") || path === ".") continue;
114
+ if (tracked.has(path) || dirs.has(path)) reads.paths.add(path);
115
+ }
116
+ if (/^[\w@+-][\w.@+-]*\.\w+$/.test(value)) reads.basenames.add(value);
117
+ };
118
+ for (const arg of args) addLiteral(arg, ".");
119
+
120
+ const queue = [entry];
121
+ while (queue.length) {
122
+ const module = queue.shift()!;
123
+ if (reads.closure.has(module)) continue;
124
+ if (reads.closure.size >= MAX_CLOSURE) return `its import closure exceeds ${MAX_CLOSURE} files`;
125
+ const text = input.read(module);
126
+ if (text === undefined) return `${module} could not be read`;
127
+ reads.closure.add(module);
128
+ if (SPAWNS.test(text)) return `${module} runs another program`;
129
+ if (WALKS_ROOT.test(text)) return `${module} walks the repository root`;
130
+ if (ENV_PATH.test(text)) return `${module} reads a path from the environment`;
131
+ const scanned = scanModule(module, text);
132
+ if (!scanned) return `${module} loads a module by a computed name`;
133
+ for (const specifier of scanned.imports) {
134
+ // Path aliases (`@/lib/x`, `~/x`, `#x`) reach repository code this module cannot follow.
135
+ if (/^(?:@\/|~\/|#)/.test(specifier)) return `${module} imports ${specifier} through a path alias`;
136
+ if (specifier.startsWith(".")) {
137
+ const base = posix.normalize(posix.join(posix.dirname(module), specifier));
138
+ const resolved = RESOLVE_EXTENSIONS.map((ext) => base + ext).find((candidate) => tracked.has(candidate))
139
+ ?? (tracked.has(base.replace(/\.js$/, ".ts")) ? base.replace(/\.js$/, ".ts") : undefined);
140
+ if (resolved) queue.push(resolved);
141
+ else return `${module} imports ${specifier}, which is not a tracked file`;
142
+ } else if (!specifier.startsWith("node:") && !/^(?:fs|path|os|url|util|assert|crypto|child_process|stream|events|zlib|readline|process|module|worker_threads|http|https|net|buffer|timers)(?:\/|$)/.test(specifier)) {
143
+ reads.importsPackages = true;
144
+ }
145
+ }
146
+ for (const literal of scanned.literals) addLiteral(literal, module);
147
+ if (/__dirname|import\.meta\.(?:dirname|url)/.test(text) && posix.dirname(module) !== ".") reads.paths.add(posix.dirname(module));
148
+ }
149
+ return reads;
150
+ }
151
+
152
+ /** RUN or SKIP for a check that runs one repository script; other checks are returned unchanged. */
153
+ export function decideScriptCheck(check: GateCheck, input: NarrowingInput): GateCheck {
154
+ if (check.kind !== "script" || !input.files) return check;
155
+ if (check.runsScript && input.lifecycleHooks !== false
156
+ && (input.scripts[`pre${check.script}`] !== undefined || input.scripts[`post${check.script}`] !== undefined)) return check;
157
+ const script = scriptOf(check.command);
158
+ if (!script) return check;
159
+ const run = (reason: string): GateCheck => ({ ...check, decision: "RUN", reason });
160
+ const reads = collectReads(script.file, script.args, input, input.files);
161
+ if (typeof reads === "string") return run(`${reads}: runs for any change`);
162
+
163
+ for (const { path } of input.changes) {
164
+ if (reads.closure.has(path)) return run(`${path} changed, and the check runs it`);
165
+ const named = [...reads.paths].find((read) => path === read || path.startsWith(`${read}/`));
166
+ if (named) return run(`reads ${named}, which contains ${path}`);
167
+ if (reads.basenames.has(posix.basename(path))) return run(`names ${posix.basename(path)}`);
168
+ const base = posix.basename(path);
169
+ if ((path === "package.json" || LOCKFILE.test(base)) && (reads.importsPackages || reads.paths.has("package.json"))) return run(`${path} changed and the check imports packages`);
170
+ }
171
+ const shown = [...reads.paths].sort().slice(0, 4);
172
+ const more = reads.paths.size > shown.length ? ` and ${reads.paths.size - shown.length} more` : "";
173
+ return { ...check, decision: "SKIP", reason: `reads ${shown.length ? shown.join(", ") + more : "only its own code"}; no changed file there` };
174
+ }
@@ -0,0 +1,103 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * Is a change inside a TypeScript program? (2026-10-29, docs/design/pipeline-impact.md, phase 1 slice 4.)
4
+ *
5
+ * `tsc --noEmit` and type-aware lint check a whole program, so a change anywhere in it can break a file
6
+ * that did not change, and they are never narrowed to files. But a change outside the program (docs, SQL,
7
+ * site HTML, a script no TypeScript imports) cannot change their result, and they can be skipped.
8
+ *
9
+ * THE RULE. The program is the tsconfig's root files (`files`, `include`, `exclude`, inherited through
10
+ * relative `extends`; `projectRoots` in compiled-projects.ts) plus whatever those roots import. A change is
11
+ * in the program when:
12
+ *
13
+ * - it is a root (added and deleted paths count: they enter or leave the program);
14
+ * - it is a tsconfig/jsconfig, package.json, a lockfile or any `.d.ts` (they change every file's types);
15
+ * - it is a file TypeScript can load (TypeScript, JavaScript, JSON) and some root's text names it in an
16
+ * import-like string (`"./x"`, `"@/lib/x"`, `"../data/x.json"`). TypeScript can only reach a non-root
17
+ * file through an import that names it.
18
+ *
19
+ * FAILING CLOSED. A tsconfig that cannot be read, or one that extends a package (whose `include` and
20
+ * `allowJs` are unknown) when a JavaScript file changed, counts as in the program.
21
+ */
22
+
23
+ import { posix } from "node:path";
24
+ import { projectRoots } from "../repo/compiled-projects.js";
25
+ import type { NarrowingInput } from "./check-narrowing.js";
26
+
27
+ const CONFIG = /(?:^|\/)(?:tsconfig|jsconfig)[^/]*\.json$/;
28
+ const LOCKFILE = /^(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/;
29
+ const LOADABLE = /\.(?:[cm]?tsx?|[cm]?jsx?|json)$/;
30
+ const JAVASCRIPT = /\.[cm]?jsx?$/;
31
+
32
+ export type ProgramMembership =
33
+ | { inProgram: true; reason: string }
34
+ | { inProgram: false; reason: string };
35
+
36
+ /** Root file texts, read once per narrowing pass. */
37
+ export type RootTextCache = Map<string, string | undefined>;
38
+
39
+ function escape(text: string): string {
40
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
41
+ }
42
+
43
+ /** The name an import of `path` would end with: its stem, or its directory for an index file. */
44
+ function importName(path: string): string {
45
+ const stem = posix.basename(path).replace(/\.(?:d\.)?[^.]+$/, "");
46
+ return stem === "index" && posix.dirname(path) !== "." ? posix.basename(posix.dirname(path)) : stem;
47
+ }
48
+
49
+ export function programMembership(config: string, input: NarrowingInput, cache: RootTextCache = new Map()): ProgramMembership {
50
+ const configText = input.read(config);
51
+ if (configText === undefined) return { inProgram: true, reason: `${config} could not be read` };
52
+ const global = input.changes.find(({ path }) => CONFIG.test(path) || path === "package.json" || LOCKFILE.test(posix.basename(path)) || path.endsWith(".d.ts"));
53
+ if (global) return { inProgram: true, reason: `${global.path} changed, which affects every file's types` };
54
+
55
+ // Added and deleted paths are matched too: they enter or leave the program.
56
+ const files = [...new Set([...(input.files ?? []), ...input.changes.map(({ path }) => path)])];
57
+ const roots = projectRoots(config, { files, read: input.read });
58
+ if (!roots) return { inProgram: true, reason: `${config} could not be parsed` };
59
+ const rootSet = new Set(roots);
60
+ const root = input.changes.find(({ path }) => rootSet.has(path));
61
+ if (root) return { inProgram: true, reason: `${root.path} is in the ${config} program` };
62
+
63
+ const packageBase = /"extends"\s*:\s*(?:\[[^\]]*)?"[^.]/.test(configText);
64
+ const loadable = input.changes.filter(({ path }) => LOADABLE.test(path));
65
+ if (packageBase) {
66
+ const script = loadable.find(({ path }) => JAVASCRIPT.test(path));
67
+ if (script) return { inProgram: true, reason: `${config} extends a package, so ${script.path} may be compiled` };
68
+ }
69
+ for (const { path } of loadable) {
70
+ const pattern = new RegExp(`["'\`/]${escape(importName(path))}(?:\\.[\\w.]+)?["'\`]`);
71
+ for (const candidate of roots) {
72
+ if (!cache.has(candidate)) cache.set(candidate, input.read(candidate));
73
+ if (pattern.test(cache.get(candidate) ?? "")) return { inProgram: true, reason: `${path} may be imported by ${candidate}` };
74
+ }
75
+ }
76
+ return { inProgram: false, reason: `no changed file is in the ${config} program` };
77
+ }
78
+
79
+ const TSC_VALUE_FLAGS = new Set(["-p", "--project", "--tsBuildInfoFile", "--pretty"]);
80
+ const TSC_BOOLEAN_FLAGS = new Set(["--noEmit", "--incremental", "--skipLibCheck", "--extendedDiagnostics", "--diagnostics", "--noErrorTruncation"]);
81
+
82
+ /** The tsconfig a `tsc` leaf checks, or undefined when the command is not a plain project check. */
83
+ export function tscProject(command: string): string | undefined {
84
+ const words = command.trim().split(/\s+/);
85
+ let index = 0;
86
+ if (words[index] === "npx") { index++; if (words[index] === "--no-install") index++; }
87
+ if (words[index] !== "tsc") return undefined;
88
+ let project = "tsconfig.json";
89
+ for (index++; index < words.length; index++) {
90
+ const word = words[index]!;
91
+ if (TSC_BOOLEAN_FLAGS.has(word)) continue;
92
+ if (!TSC_VALUE_FLAGS.has(word)) return undefined;
93
+ const value = words[++index];
94
+ if (value === undefined) return undefined;
95
+ if (word === "--pretty" && !/^(?:true|false)$/.test(value)) { index--; continue; }
96
+ if (word === "-p" || word === "--project") {
97
+ if (/["'$`]/.test(value)) return undefined;
98
+ const normalized = posix.normalize(value).replace(/\/$/, "");
99
+ project = normalized.endsWith(".json") ? normalized : posix.join(normalized, "tsconfig.json");
100
+ }
101
+ }
102
+ return project;
103
+ }
@@ -39,13 +39,17 @@ const MAX_READ_BYTES = 1_048_576;
39
39
 
40
40
  /** Reads repo-relative text files from a checkout at HEAD, the same tree the dependency graph reads.
41
41
  * Binary content (a NUL byte in the first 8 KiB) and files over 1 MiB are unreadable. */
42
+ const TEXT_EXTENSIONS = /\.(?:[cm]?[jt]sx?|vue|go|java|kt|py|rb|sh|json|jsonc|ya?ml|toml|md|mdx|html?|css|sql|txt)$/i;
43
+
42
44
  export function repositoryFileReader(repoPath: string): (path: string) => string | undefined {
43
45
  return (path) => {
44
46
  try {
45
47
  const full = join(repoPath, path);
46
48
  if (statSync(full).size > MAX_READ_BYTES) return undefined;
47
49
  const bytes = readFileSync(full);
48
- if (bytes.subarray(0, 8192).includes(0)) return undefined;
50
+ // Source and text files are text even when they contain a stray NUL (a separator literal): treating
51
+ // one as binary hid it as a reader and made suiteMayRunWorkers fail closed (2026-10-29).
52
+ if (!TEXT_EXTENSIONS.test(path) && bytes.subarray(0, 8192).includes(0)) return undefined;
49
53
  return bytes.toString("utf8");
50
54
  } catch {
51
55
  return undefined;
@@ -142,6 +146,9 @@ export interface ReferenceResolutionInput {
142
146
  /** Changed files whose content analyzeGitDelta proved cannot change how tests run
143
147
  * (GitDeltaAnalysis.referenceResolvedPaths); a workflow reading them does not block. */
144
148
  contentCleared?: ReadonlySet<string>;
149
+ /** No code in the repository runs a Worker (suiteMayRunWorkers is false), so a wrangler config with
150
+ * no reader is outside the suite. */
151
+ workerConfigsOutsideSuite?: boolean;
145
152
  /** Treat a reader that tooling loads implicitly (wrangler config, Dockerfile, `*.config.*`) as
146
153
  * unresolvable. Used for code: such a reader can run the file without anything naming it. */
147
154
  implicitReadersUnresolvable?: boolean;
@@ -277,7 +284,41 @@ function loadsWithoutNaming(path: string): boolean {
277
284
  return RUNS_FILES_WITHOUT_NAMING.test(posix.basename(path));
278
285
  }
279
286
 
280
- const ENV_TEMPLATE = /^\.env(?:\.[^.]+)*\.(?:example|sample|template|dist)$|^env\.(?:example|sample|template)$/i;
287
+ /** A Cloudflare Workers deployment config (`wrangler.toml`, `wrangler.product.jsonc`). */
288
+ export function isWorkerConfig(filePath: string): boolean {
289
+ return /^wrangler(?:\.[^./]+)?\.(?:toml|json|jsonc)$/i.test(posix.basename(filePath));
290
+ }
291
+
292
+ const RUNS_WORKER = /unstable_dev|unstable_startWorker|\bminiflare\b|getPlatformProxy|vitest-pool-workers|\b(?:spawn|exec|execFile|execa|fork)(?:Sync)?\([^)]{0,80}["'`](?:npx\s+)?wrangler\b|["'`]wrangler["'`]\s*,\s*\[/i;
293
+
294
+ /**
295
+ * Whether anything in the repository may run a Worker during tests (2026-10-29). Tooling loads a
296
+ * wrangler config without code naming it, but only when wrangler, Miniflare or the Workers test pool
297
+ * runs. If no code file and no test-closure script does, a test can only observe the config by reading
298
+ * it by name - which the reference resolver handles - so the config need not force full validation.
299
+ * Deliberately repository-wide rather than limited to tests' imports: a test helper may spawn wrangler.
300
+ * Missing contents or an unparseable manifest answer true.
301
+ */
302
+ export function suiteMayRunWorkers(files: readonly string[], read: (path: string) => string | undefined, isCodeFile: (path: string) => boolean): boolean {
303
+ const manifest = read("package.json");
304
+ if (manifest === undefined) return true;
305
+ let scripts: Record<string, string>;
306
+ try {
307
+ const parsed = (JSON.parse(manifest) as { scripts?: unknown }).scripts ?? {};
308
+ if (!parsed || typeof parsed !== "object") return true;
309
+ scripts = Object.fromEntries(Object.entries(parsed).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
310
+ } catch {
311
+ return true;
312
+ }
313
+ if ([...testScriptClosure(scripts)].some((name) => /\b(?:wrangler|miniflare)\b/i.test(scripts[name] ?? ""))) return true;
314
+ return files.some((path) => {
315
+ if (!isCodeFile(path) && !/\.config\.[cm]?[jt]s$/.test(path)) return false;
316
+ const content = read(path);
317
+ return content === undefined || RUNS_WORKER.test(content);
318
+ });
319
+ }
320
+
321
+ const ENV_TEMPLATE =/^\.env(?:\.[^.]+)*\.(?:example|sample|template|dist)$|^env\.(?:example|sample|template)$/i;
281
322
  /** Packages that load `.env.example` without being told its name. */
282
323
  const IMPLICIT_ENV_TEMPLATE_LOADERS = /["'](?:dotenv-safe|dotenv-extended|dotenv-mono)["']/;
283
324
 
@@ -292,6 +333,7 @@ const IMPLICIT_ENV_TEMPLATE_LOADERS = /["'](?:dotenv-safe|dotenv-extended|dotenv
292
333
  */
293
334
  function loadedOnlyOutsideTests(filePath: string, input: ReferenceResolutionInput, read: (path: string) => string | undefined): boolean {
294
335
  if (/^\.github\/workflows\/[^/]+\.ya?ml$/.test(filePath)) return input.contentCleared?.has(filePath) === true;
336
+ if (isWorkerConfig(filePath)) return input.workerConfigsOutsideSuite === true;
295
337
  if (!ENV_TEMPLATE.test(posix.basename(filePath))) return false;
296
338
  const manifest = read("package.json");
297
339
  return manifest !== undefined && !IMPLICIT_ENV_TEMPLATE_LOADERS.test(manifest);
@@ -8,7 +8,7 @@ import { refineConfidenceForDelta } from "./graph.js";
8
8
  import { repositoryLayout, UNKNOWN_REPOSITORY_LAYOUT, type RepositoryLayout } from "./layout.js";
9
9
  import { DEFAULT_TEST_FILE_MATCHER, matchesGlob as matchesTestGlob, testDiscoveryErrors, testFileMatcherForProfile } from "./test-discovery.js";
10
10
  import { resolveTestFixtureOwners } from "./test-fixture-ownership.js";
11
- import { infrastructureRole, isImplicitlyLoadedFile, resolveFileReferences, testScriptClosure } from "./file-references.js";
11
+ import { infrastructureRole, isImplicitlyLoadedFile, isWorkerConfig, resolveFileReferences, suiteMayRunWorkers, testScriptClosure } from "./file-references.js";
12
12
  import { workflowFeedsTests } from "./workflow-test-steps.js";
13
13
  import { modelTestScriptUniverse, type ScriptUniverse } from "./script-universe.js";
14
14
  import { compiledProjects, type CompiledProject } from "./compiled-projects.js";
@@ -257,6 +257,17 @@ export class ImpactAnalyzer {
257
257
  private goEmbedPaths = new Set<string>();
258
258
  private selectTestPhases = false;
259
259
  private testPhases = new Set<string>();
260
+ private workersOutsideSuite: boolean | undefined;
261
+
262
+ /** True when nothing in the repository runs a Worker (file-references.ts, suiteMayRunWorkers); false,
263
+ * which keeps wrangler configs global, whenever repository contents are unavailable. */
264
+ private workerConfigsOutsideSuite(): boolean {
265
+ if (this.workersOutsideSuite === undefined) {
266
+ this.workersOutsideSuite = Boolean(this.repositoryFiles && this.readRepositoryFile)
267
+ && !suiteMayRunWorkers(this.sortedRepositoryFiles, this.readRepositoryFile!, isSourceFilePath);
268
+ }
269
+ return this.workersOutsideSuite;
270
+ }
260
271
  constructor(alwaysRunChecks: AlwaysRunCheck[] = DEFAULT_ALWAYS_RUN_CHECKS) { this.alwaysRunChecks = alwaysRunChecks; }
261
272
 
262
273
  analyze(delta: GitDelta, graphResult: DependencyGraphResult, profile: RepositoryProfile, options: ImpactAnalyzeOptions = {}): ImpactResult {
@@ -267,6 +278,7 @@ export class ImpactAnalyzer {
267
278
  this.repositoryFiles = options.repositoryFiles;
268
279
  this.selectTestPhases = options.selectTestPhases === true;
269
280
  this.testPhases = new Set();
281
+ this.workersOutsideSuite = undefined;
270
282
  this.sortedRepositoryFiles = options.repositoryFiles ? [...options.repositoryFiles].sort() : [];
271
283
  this.compiledProjectCache = undefined;
272
284
  // One read per file per analysis, however many changed files ask who reads them.
@@ -432,7 +444,13 @@ export class ImpactAnalyzer {
432
444
  if (rule.check(delta.analysis)) {
433
445
  // The stable sentence stays a prefix, so consumers that categorise by it keep working; the
434
446
  // files that triggered it follow (2026-10-21).
435
- const paths = delta.analysis.signalPaths?.[rule.signal] ?? [];
447
+ let paths = delta.analysis.signalPaths?.[rule.signal] ?? [];
448
+ if (rule.signal === "infrastructure" && paths.length > 0 && this.workerConfigsOutsideSuite()) {
449
+ // A wrangler config cannot reach a suite that never runs a Worker; processChangedPath resolves
450
+ // its readers instead (2026-10-29).
451
+ paths = paths.filter((path) => !isWorkerConfig(path));
452
+ if (paths.length === 0) continue;
453
+ }
436
454
  const message = paths.length === 0 ? rule.message
437
455
  : `${rule.message}: ${paths.slice(0, 5).join(", ")}${paths.length > 5 ? ` (+${paths.length - 5} more)` : ""}`;
438
456
  riskSignals.push({ level: "critical", reason: rule.reason, message, ...(paths.length ? { paths: [...paths] } : {}) });
@@ -596,6 +614,14 @@ export class ImpactAnalyzer {
596
614
  this.processAssetChange(changedPath, graph, profile, affectedAssets, affectedEntryPoints, affectedTests, affectedSources, evidence);
597
615
  return;
598
616
  }
617
+ if (category === "infrastructure" && isWorkerConfig(changedPath) && this.workerConfigsOutsideSuite()) {
618
+ if (this.resolveByReference(changedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence)) return;
619
+ const message = `Unknown changed file: ${changedPath}`;
620
+ evidence.push(makeEvidence("UNKNOWN_FILE", changedPath, message));
621
+ riskSignals.push({ level: "critical", reason: "UNKNOWN_FILE", message, paths: [changedPath] });
622
+ if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
623
+ return;
624
+ }
599
625
  if (category === "config" || category === "workflow" || category === "infrastructure" || category === "database") {
600
626
  evidence.push(makeEvidence("CONFIG_GLOBAL", changedPath, `Global ${category} change at ${changedPath}`));
601
627
  return;
@@ -675,7 +701,8 @@ export class ImpactAnalyzer {
675
701
  evidence: ImpactEvidence[],
676
702
  { implicitReadersUnresolvable = false }: { implicitReadersUnresolvable?: boolean } = {},
677
703
  ): boolean {
678
- if (!this.repositoryFiles || !this.readRepositoryFile || isImplicitlyLoadedFile(changedPath)) return false;
704
+ if (!this.repositoryFiles || !this.readRepositoryFile) return false;
705
+ if (isImplicitlyLoadedFile(changedPath) && !(isWorkerConfig(changedPath) && this.workerConfigsOutsideSuite())) return false;
679
706
  const layout = this.layout;
680
707
  const scripts = profile.packageJson.scripts;
681
708
  const resolution = resolveFileReferences(changedPath, {
@@ -689,6 +716,7 @@ export class ImpactAnalyzer {
689
716
  contentCleared: this.contentCleared,
690
717
  implicitReadersUnresolvable,
691
718
  testPhases: this.selectTestPhases,
719
+ workerConfigsOutsideSuite: this.workerConfigsOutsideSuite(),
692
720
  });
693
721
  if (resolution.unresolvable.length > 0) {
694
722
  evidence.push(makeEvidence("UNKNOWN_FILE", changedPath, `References to ${changedPath} could not be resolved: ${resolution.unresolvable[0]}`));
@@ -26,8 +26,23 @@ const NON_TEST_ACTIONS = [
26
26
  "pnpm/action-setup", "oven-sh/setup-bun", "softprops/action-gh-release", "peter-evans/create-pull-request",
27
27
  "peter-evans/create-or-update-comment", "aws-actions/configure-aws-credentials", "google-github-actions/auth",
28
28
  "google-github-actions/setup-gcloud", "azure/login", "dependabot/fetch-metadata", "cloudflare/wrangler-action",
29
+ // DiffCI's own observer Action only analyses; it runs no repository command (action.yml).
30
+ "diffci/core",
29
31
  ];
30
- const TEST_RUNNERS = /(?:^|[\s/"'`(;&|])(?:vitest|jest|mocha|ava|tap|playwright|cypress|karma|jasmine|pytest|tox|nox|phpunit|rspec|diffci|ctest)(?=$|[\s"'`);&|])|(?:node|tsx|bun|deno)(?:\s+--?[\w-]+(?:=\S+)?)*\s+--?test\b|\b(?:go|cargo|dotnet|swift|mix|zig)\s+test\b|\b(?:mvn|mvnw|gradle|gradlew|sbt|bazel|make|just)\b/;
32
+ /** DiffCI subcommands that run no tests. `verify`, `check`, `pilot` and `enforce-misses` do, so `diffci`
33
+ * followed by anything else stays a test runner (2026-10-29: DiffCI's own observation workflows were
34
+ * 60 of 65 workflow-triggered fallbacks in one dogfood repository's telemetry). */
35
+ const DIFFCI_NON_TEST_COMMAND = /\bdiffci["']?(?:\s+--?[\w-]+(?:=\S+)?)*\s+(?:observe|init|version|telemetry|pilot-packet|verify-workflow|validate-specs|mcp)\b/g;
36
+
37
+ /** `diffci` invoked with a subcommand still present after removing the non-test ones. */
38
+ const DIFFCI_COMMAND = /\bdiffci["']?(?:\s+--?[\w-]+(?:=\S+)?)*\s+[a-z][\w-]*/;
39
+
40
+ /** A job whose `if` is the literal false never runs (a retired workflow kept for its history). */
41
+ function jobDisabled(job: object): boolean {
42
+ const condition = (job as { if?: unknown }).if;
43
+ return condition === false || (typeof condition === "string" && /^\s*(?:\$\{\{\s*)?false(?:\s*\}\})?\s*$/.test(condition));
44
+ }
45
+ const TEST_RUNNERS = /(?:^|[\s/"'`(;&|])(?:vitest|jest|mocha|ava|tap|playwright|cypress|karma|jasmine|pytest|tox|nox|phpunit|rspec|ctest)(?=$|[\s"'`);&|])|(?:node|tsx|bun|deno)(?:\s+--?[\w-]+(?:=\S+)?)*\s+--?test\b|\b(?:go|cargo|dotnet|swift|mix|zig)\s+test\b|\b(?:mvn|mvnw|gradle|gradlew|sbt|bazel|make|just)\b/;
31
46
  const PACKAGE_SCRIPT = /\b(?:npm|pnpm|yarn|bun)\s+(?:(?:run|run-script|-w\s+\S+|--workspace[= ]\S+|--prefix[= ]\S+|--if-present|-r|--recursive|--silent|-s)\s+)*([\w:.-]+)/g;
32
47
  const INTERPRETER_FILE = /\b(?:node|tsx|ts-node|bash|sh|zsh|pwsh|powershell|python3?|ruby|perl|deno\s+run|bun(?:\s+run)?|npx\s+(?:--\S+\s+)*tsx)\s+(?:-{1,2}[\w-]+(?:=\S+)?\s+)*\.{0,2}\/?[\w./-]+\.(?:m?[jt]s|c[jt]s|sh|ps1|py|rb|pl)\b|(?:^|[\s;&|])\.{1,2}\/[\w./-]+/;
33
48
  const PACKAGE_MANAGER_BUILTINS = new Set(["ci", "install", "i", "add", "remove", "uninstall", "publish", "pack", "version", "view", "info", "whoami", "login", "config", "cache", "audit", "outdated", "ls", "list", "exec", "dlx", "init", "create", "link", "prune", "dedupe", "rebuild", "set-script", "pkg", "fund", "doctor", "help", "--version", "-v"]);
@@ -35,6 +50,10 @@ const PACKAGE_MANAGER_BUILTINS = new Set(["ci", "install", "i", "add", "remove",
35
50
  /** `strict` asks only whether the command runs a test runner or the test script; otherwise running any
36
51
  * repository file also counts, because that file may run tests itself. */
37
52
  function commandRunsTests(text: string, scripts: Readonly<Record<string, string>>, seen: Set<string> = new Set(), strict = false): boolean {
53
+ text = text.replace(DIFFCI_NON_TEST_COMMAND, " ");
54
+ // `diffci` runs tests only as a command with a remaining subcommand (verify, check, pilot, ...); as a
55
+ // path segment (`--prefix "$RUNNER_TEMP/diffci"`) it runs nothing.
56
+ if (DIFFCI_COMMAND.test(text)) return true;
38
57
  if (TEST_RUNNERS.test(text) || (!strict && INTERPRETER_FILE.test(text))) return true;
39
58
  for (const match of text.matchAll(PACKAGE_SCRIPT)) {
40
59
  const name = match[1] ?? "";
@@ -78,6 +97,7 @@ export function workflowFeedsTests(workflowText: string, names: RegExp, scripts:
78
97
  };
79
98
  for (const job of Object.values(jobs as Record<string, unknown>)) {
80
99
  if (!job || typeof job !== "object") return true;
100
+ if (jobDisabled(job)) continue;
81
101
  const { steps, uses, ...configuration } = job as { steps?: unknown; uses?: unknown };
82
102
  if (uses !== undefined) { if (names.test(JSON.stringify(job))) return true; continue; }
83
103
  if (!Array.isArray(steps)) return true;
@@ -99,6 +119,7 @@ export function workflowMayRunTests(workflowText: string | undefined, scripts: R
99
119
  if (!jobs || typeof jobs !== "object") return true;
100
120
  for (const job of Object.values(jobs as Record<string, unknown>)) {
101
121
  if (!job || typeof job !== "object") return true;
122
+ if (jobDisabled(job)) continue;
102
123
  const record = job as { uses?: unknown; steps?: unknown; container?: unknown; services?: unknown };
103
124
  if (record.uses !== undefined) return true;
104
125
  if (!Array.isArray(record.steps)) return true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diffci.com/diffci",
3
- "version": "0.3.16",
3
+ "version": "0.3.18",
4
4
  "description": "Fail-closed, change-aware verification for AI coding agents with conservative affected-test selection",
5
5
  "keywords": [
6
6
  "ci",
@@ -59,7 +59,7 @@
59
59
  "test": "node scripts/run-tests.mjs"
60
60
  },
61
61
  "dependencies": {
62
- "@diffci.com/core": "git+https://github.com/DiffCI/core.git#8d832eb5a0a56bf57847e6425bc313ea9e575f59",
62
+ "@diffci.com/core": "git+https://github.com/DiffCI/core.git#6c386206479ebe1b22f5b698a0e2c9cea8df4d51",
63
63
  "yaml": "^2.9.0"
64
64
  },
65
65
  "devDependencies": {