@diffci.com/diffci 0.3.32 → 0.3.34
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/README.md +23 -0
- package/dist-client/src/client/check-plan-junit.d.ts +25 -0
- package/dist-client/src/client/check-plan-junit.js +215 -0
- package/dist-client/src/client/check-plan.d.ts +42 -0
- package/dist-client/src/client/check-plan.js +143 -0
- package/dist-client/src/client/cli.js +212 -7
- package/dist-client/src/client/command-batches.d.ts +1 -0
- package/dist-client/src/client/command-batches.js +3 -1
- package/dist-client/src/client/enforce-misses-collect.js +6 -1
- package/dist-client/src/client/enforce-misses.d.ts +3 -2
- package/dist-client/src/client/enforce-misses.js +19 -59
- package/dist-client/src/client/failure-baseline.js +0 -0
- package/dist-client/src/client/full-command.d.ts +8 -0
- package/dist-client/src/client/full-command.js +31 -0
- package/dist-client/src/client/job-summary.js +1 -1
- package/dist-client/src/client/observe.d.ts +4 -0
- package/dist-client/src/client/observe.js +31 -2
- package/dist-client/src/client/report.d.ts +4 -0
- package/dist-client/src/client/test-results.js +7 -0
- package/dist-client/src/client/verify.d.ts +18 -0
- package/dist-client/src/client/verify.js +39 -10
- package/dist-client/src/client/watch.d.ts +36 -0
- package/dist-client/src/client/watch.js +76 -0
- package/node_modules/@diffci.com/core/README.md +36 -5
- package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
- package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +3 -1
- package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +12 -0
- package/node_modules/@diffci.com/core/dist/git/git-diff.js +86 -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 +8 -0
- package/node_modules/@diffci.com/core/dist/planner/test-command.js +16 -0
- package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/adapters/index.js +2 -1
- package/node_modules/@diffci.com/core/dist/repo/adapters/index.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/adapters/python.d.ts +32 -0
- package/node_modules/@diffci.com/core/dist/repo/adapters/python.js +273 -0
- package/node_modules/@diffci.com/core/dist/repo/adapters/python.js.map +1 -0
- package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +2 -0
- package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +15 -0
- package/node_modules/@diffci.com/core/dist/repo/file-references.js +45 -0
- package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/graph.d.ts +4 -0
- package/node_modules/@diffci.com/core/dist/repo/graph.js +182 -21
- package/node_modules/@diffci.com/core/dist/repo/graph.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 +37 -9
- package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/types.d.ts +5 -0
- package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +3 -1
- package/node_modules/@diffci.com/core/src/git/git-diff.ts +72 -0
- package/node_modules/@diffci.com/core/src/git/types.ts +5 -0
- package/node_modules/@diffci.com/core/src/planner/test-command.ts +14 -0
- package/node_modules/@diffci.com/core/src/repo/adapters/index.ts +2 -1
- package/node_modules/@diffci.com/core/src/repo/adapters/python.ts +252 -0
- package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +2 -0
- package/node_modules/@diffci.com/core/src/repo/file-references.ts +43 -0
- package/node_modules/@diffci.com/core/src/repo/graph.ts +154 -20
- package/node_modules/@diffci.com/core/src/repo/impact.ts +34 -9
- package/node_modules/@diffci.com/core/src/repo/types.ts +5 -0
- package/package.json +3 -2
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { join, posix } from "node:path";
|
|
5
|
+
import { contribution, type AdapterContext, type AdapterContribution, type RepositoryAdapter } from "./types.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Python repositories tested with pytest (2026-11-06).
|
|
9
|
+
*
|
|
10
|
+
* WHY. The ML-pipelines expansion and most outside design-partner candidates run Python; until now a
|
|
11
|
+
* Python change was an unknown file and every run was the full suite.
|
|
12
|
+
*
|
|
13
|
+
* WHAT. The import graph comes from Python's own `ast` module, run once over every `.py` file (a short
|
|
14
|
+
* script on stdin; no repository code is imported or executed, unlike `pytest --collect-only`, which runs
|
|
15
|
+
* conftest.py). DiffCI resolves each import against the repository root, `src/`, pytest's `pythonpath`
|
|
16
|
+
* and, for a file in a directory without `__init__.py`, that directory (pytest's default `prepend`
|
|
17
|
+
* import mode puts it on sys.path). Importing `a.b.c` also reaches `a/__init__.py` and `a/b/__init__.py`,
|
|
18
|
+
* which run on import. Tests follow pytest's `python_files` and `testpaths`; each test also depends on
|
|
19
|
+
* every `conftest.py` from its directory up to the root, which pytest loads before it.
|
|
20
|
+
*
|
|
21
|
+
* Full validation instead, as global blockers: no Python interpreter, a file that does not parse, an
|
|
22
|
+
* `importlib.import_module` / `__import__` / `pytest_plugins` entry whose name is computed, a first-party
|
|
23
|
+
* module that cannot be resolved, and pytest configuration this reader cannot follow. Ruff's or Tach's
|
|
24
|
+
* import maps could replace the `ast` script later; neither is needed for correctness.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const PARSE_SCRIPT = String.raw`
|
|
28
|
+
import ast, json, sys
|
|
29
|
+
out = {}
|
|
30
|
+
for path in json.load(sys.stdin):
|
|
31
|
+
try:
|
|
32
|
+
with open(path, "rb") as handle:
|
|
33
|
+
tree = ast.parse(handle.read(), filename=path)
|
|
34
|
+
except Exception as error:
|
|
35
|
+
out[path] = {"error": type(error).__name__}
|
|
36
|
+
continue
|
|
37
|
+
imports, dynamic = [], False
|
|
38
|
+
for node in ast.walk(tree):
|
|
39
|
+
if isinstance(node, ast.Import):
|
|
40
|
+
imports.extend([alias.name, 0, []] for alias in node.names)
|
|
41
|
+
elif isinstance(node, ast.ImportFrom):
|
|
42
|
+
imports.append([node.module or "", node.level, [alias.name for alias in node.names]])
|
|
43
|
+
elif isinstance(node, ast.Call):
|
|
44
|
+
func = node.func
|
|
45
|
+
name = func.attr if isinstance(func, ast.Attribute) else func.id if isinstance(func, ast.Name) else None
|
|
46
|
+
if name in ("import_module", "__import__"):
|
|
47
|
+
first = node.args[0] if node.args else None
|
|
48
|
+
if isinstance(first, ast.Constant) and isinstance(first.value, str) and not first.value.startswith("."):
|
|
49
|
+
imports.append([first.value, 0, []])
|
|
50
|
+
else:
|
|
51
|
+
dynamic = True
|
|
52
|
+
elif isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "pytest_plugins" for t in node.targets):
|
|
53
|
+
values = node.value.elts if isinstance(node.value, (ast.List, ast.Tuple)) else [node.value]
|
|
54
|
+
for value in values:
|
|
55
|
+
if isinstance(value, ast.Constant) and isinstance(value.value, str):
|
|
56
|
+
imports.append([value.value, 0, []])
|
|
57
|
+
else:
|
|
58
|
+
dynamic = True
|
|
59
|
+
out[path] = {"imports": imports, "dynamic": dynamic}
|
|
60
|
+
json.dump(out, sys.stdout)
|
|
61
|
+
`;
|
|
62
|
+
|
|
63
|
+
export type PythonImport = [module: string, level: number, names: string[]];
|
|
64
|
+
export interface PythonFileImports { imports?: PythonImport[]; dynamic?: boolean; error?: string }
|
|
65
|
+
|
|
66
|
+
const EXCLUDED_DIRS = new Set([".venv", "venv", "env", ".env", ".tox", ".nox", "site-packages", "__pycache__", ".eggs", ".mypy_cache", ".pytest_cache", ".ruff_cache"]);
|
|
67
|
+
const PROJECT_FILES = ["pyproject.toml", "setup.py", "setup.cfg", "pytest.ini", "tox.ini", "conftest.py"];
|
|
68
|
+
|
|
69
|
+
export function isPythonSource(path: string): boolean {
|
|
70
|
+
return path.endsWith(".py") && !path.split("/").some((part) => EXCLUDED_DIRS.has(part) || part.endsWith(".egg-info"));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The first interpreter that runs: `python3`, `python`, then the Windows launcher `py -3`. */
|
|
74
|
+
export function pythonInterpreter(cwd: string): string[] | undefined {
|
|
75
|
+
for (const candidate of [["python3"], ["python"], ["py", "-3"]]) {
|
|
76
|
+
const result = spawnSync(candidate[0]!, [...candidate.slice(1), "-c", "import sys; print(sys.version_info[0])"], { cwd, encoding: "utf8", timeout: 10_000, windowsHide: true });
|
|
77
|
+
if (result.status === 0 && result.stdout.trim() === "3") return candidate;
|
|
78
|
+
}
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface PytestSettings {
|
|
83
|
+
pythonFiles: string[];
|
|
84
|
+
testpaths: string[];
|
|
85
|
+
pythonpath: string[];
|
|
86
|
+
/** A key that is present but could not be read; its file makes the analysis fall back. */
|
|
87
|
+
unreadable?: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function splitList(value: string): string[] {
|
|
91
|
+
return value.split(/[\s,]+/).map((entry) => entry.replace(/^["']|["']$/g, "")).filter(Boolean);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** pytest's own configuration, from the first file pytest would use. Only the keys selection depends on. */
|
|
95
|
+
export function readPytestSettings(read: (path: string) => string | undefined): PytestSettings {
|
|
96
|
+
const settings: PytestSettings = { pythonFiles: ["test_*.py", "*_test.py"], testpaths: [], pythonpath: [] };
|
|
97
|
+
const keys = ["python_files", "testpaths", "pythonpath"] as const;
|
|
98
|
+
const apply = (key: (typeof keys)[number], values: string[]) => {
|
|
99
|
+
if (key === "python_files") settings.pythonFiles = values;
|
|
100
|
+
else settings[key] = values;
|
|
101
|
+
};
|
|
102
|
+
for (const [file, header] of [["pytest.ini", "pytest"], ["pyproject.toml", "tool.pytest.ini_options"], ["tox.ini", "pytest"], ["setup.cfg", "tool:pytest"]] as const) {
|
|
103
|
+
const text = read(file);
|
|
104
|
+
if (text === undefined) continue;
|
|
105
|
+
const section = new RegExp(`^\\[${header.replace(/[.:]/g, "\\$&")}\\]\\s*$([\\s\\S]*?)(?=^\\[|(?![\\s\\S]))`, "m").exec(text);
|
|
106
|
+
if (!section) continue;
|
|
107
|
+
const body = section[1]!;
|
|
108
|
+
for (const key of keys) {
|
|
109
|
+
if (file === "pyproject.toml") {
|
|
110
|
+
const match = new RegExp(`^${key}\\s*=\\s*(\\[[\\s\\S]*?\\]|"[^"]*"|'[^']*')`, "m").exec(body);
|
|
111
|
+
if (match) apply(key, splitList(match[1]!.replace(/^\[|\]$/g, "")));
|
|
112
|
+
else if (new RegExp(`^${key}\\s*=`, "m").test(body)) settings.unreadable = `${file} ${key}`;
|
|
113
|
+
} else {
|
|
114
|
+
// INI values continue on indented lines.
|
|
115
|
+
const match = new RegExp(`^${key}\\s*=\\s*(.*(?:\\r?\\n[ \\t]+.*)*)`, "m").exec(body);
|
|
116
|
+
if (match) apply(key, splitList(match[1]!));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return settings;
|
|
120
|
+
}
|
|
121
|
+
return settings;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function globToRegExp(glob: string): RegExp {
|
|
125
|
+
return new RegExp(`^${glob.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]")}$`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function isPytestFile(path: string, settings: PytestSettings): boolean {
|
|
129
|
+
const base = posix.basename(path);
|
|
130
|
+
if (!settings.pythonFiles.some((glob) => globToRegExp(glob).test(base))) return false;
|
|
131
|
+
if (!settings.testpaths.length) return true;
|
|
132
|
+
return settings.testpaths.some((root) => {
|
|
133
|
+
const clean = root.replace(/^\.\//, "").replace(/\/$/, "");
|
|
134
|
+
return clean === "." || clean === "" || path === clean || path.startsWith(`${clean}/`);
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Turns the `ast` imports into repository edges. Pure, so it is tested without an interpreter.
|
|
140
|
+
*/
|
|
141
|
+
export function resolvePythonGraph(files: readonly string[], parsed: Record<string, PythonFileImports>, settings: PytestSettings, tests: ReadonlySet<string>): { edges: Array<{ from: string; to: string }>; blockers: string[] } {
|
|
142
|
+
const known = new Set(files);
|
|
143
|
+
const edges: Array<{ from: string; to: string }> = [];
|
|
144
|
+
const seen = new Set<string>();
|
|
145
|
+
const edge = (from: string, to: string) => {
|
|
146
|
+
const key = `${from}\n${to}`;
|
|
147
|
+
if (from === to || seen.has(key)) return;
|
|
148
|
+
seen.add(key);
|
|
149
|
+
edges.push({ from, to });
|
|
150
|
+
};
|
|
151
|
+
const blockers: string[] = [];
|
|
152
|
+
const roots = [...new Set(["", "src", ...settings.pythonpath.map((path) => path.replace(/^\.\//, "").replace(/\/$/, "").replace(/^\.$/, ""))])];
|
|
153
|
+
const firstParty = new Set<string>();
|
|
154
|
+
for (const file of files) {
|
|
155
|
+
for (const root of roots) {
|
|
156
|
+
const prefix = root ? `${root}/` : "";
|
|
157
|
+
if (!file.startsWith(prefix)) continue;
|
|
158
|
+
const top = file.slice(prefix.length).split("/")[0]!;
|
|
159
|
+
firstParty.add(top.replace(/\.py$/, ""));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const moduleFiles = (base: string, parts: string[]): string[] | undefined => {
|
|
163
|
+
const dir = [base, ...parts].filter(Boolean).join("/");
|
|
164
|
+
const candidate = [`${dir}.py`, `${dir}/__init__.py`].find((path) => known.has(path));
|
|
165
|
+
if (!candidate) return undefined;
|
|
166
|
+
// Parent packages run their __init__.py on import.
|
|
167
|
+
const inits: string[] = [];
|
|
168
|
+
for (let depth = 1; depth < parts.length; depth += 1) {
|
|
169
|
+
const init = [base, ...parts.slice(0, depth), "__init__.py"].filter(Boolean).join("/");
|
|
170
|
+
if (known.has(init)) inits.push(init);
|
|
171
|
+
}
|
|
172
|
+
return [candidate, ...inits];
|
|
173
|
+
};
|
|
174
|
+
const isPackageDir = (dir: string) => known.has(dir ? `${dir}/__init__.py` : "__init__.py");
|
|
175
|
+
for (const file of files) {
|
|
176
|
+
const entry = parsed[file];
|
|
177
|
+
if (!entry || entry.error) { blockers.push(`Python file could not be parsed (${entry?.error ?? "no result"}): ${file}`); continue; }
|
|
178
|
+
if (entry.dynamic) blockers.push(`Python computed import in ${file}; full validation required`);
|
|
179
|
+
const dir = posix.dirname(file) === "." ? "" : posix.dirname(file);
|
|
180
|
+
const fileRoots = isPackageDir(dir) ? roots : [...roots, dir];
|
|
181
|
+
const add = (targets: string[] | undefined) => { for (const to of targets ?? []) edge(file, to); };
|
|
182
|
+
for (const [module, level, names] of entry.imports ?? []) {
|
|
183
|
+
if (level > 0) {
|
|
184
|
+
let base = dir;
|
|
185
|
+
for (let up = 1; up < level; up += 1) base = posix.dirname(base) === "." ? "" : posix.dirname(base);
|
|
186
|
+
const parts = module ? module.split(".") : [];
|
|
187
|
+
const target = parts.length ? moduleFiles(base, parts) : [base ? `${base}/__init__.py` : "__init__.py"].filter((path) => known.has(path));
|
|
188
|
+
const submodules = names.map((name) => moduleFiles(base, [...parts, name])).filter((found): found is string[] => Boolean(found));
|
|
189
|
+
// `from . import x` in a namespace package has no __init__.py, only the submodule.
|
|
190
|
+
if (!target?.length && !submodules.length) { blockers.push(`Unresolved relative import in ${file}: ${".".repeat(level)}${module}`); continue; }
|
|
191
|
+
add(target);
|
|
192
|
+
for (const found of submodules) add(found);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const parts = module.split(".");
|
|
196
|
+
const target = fileRoots.map((root) => moduleFiles(root, parts)).find(Boolean);
|
|
197
|
+
if (!target) {
|
|
198
|
+
if (firstParty.has(parts[0]!) && parts.length > 1) blockers.push(`Unresolved first-party Python import in ${file}: ${module}`);
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
add(target);
|
|
202
|
+
for (const name of names) add(fileRoots.map((root) => moduleFiles(root, [...parts, name])).find(Boolean));
|
|
203
|
+
}
|
|
204
|
+
// pytest loads every conftest.py from the rootdir down to the test's directory first.
|
|
205
|
+
if (tests.has(file)) {
|
|
206
|
+
const segments = dir ? dir.split("/") : [];
|
|
207
|
+
for (let depth = 0; depth <= segments.length; depth += 1) {
|
|
208
|
+
const conftest = [...segments.slice(0, depth), "conftest.py"].join("/");
|
|
209
|
+
if (known.has(conftest)) edge(file, conftest);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return { edges, blockers };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function analyzePythonRepository(context: AdapterContext, parse: (files: string[]) => Record<string, PythonFileImports> | string): AdapterContribution {
|
|
217
|
+
const result = contribution(pythonAdapter);
|
|
218
|
+
const read = (path: string) => { const full = join(context.repoPath, path); return existsSync(full) ? readFileSync(full, "utf8") : undefined; };
|
|
219
|
+
const settings = readPytestSettings(read);
|
|
220
|
+
if (settings.unreadable) { result.blockers.push(`pytest configuration DiffCI cannot read: ${settings.unreadable}`); return result; }
|
|
221
|
+
const files = context.files.filter(isPythonSource);
|
|
222
|
+
const parsed = parse(files);
|
|
223
|
+
if (typeof parsed === "string") { result.blockers.push(parsed); return result; }
|
|
224
|
+
const tests = new Set(files.filter((file) => isPytestFile(file, settings)));
|
|
225
|
+
const graph = resolvePythonGraph(files, parsed, settings, tests);
|
|
226
|
+
result.sourcePaths.push(...files);
|
|
227
|
+
result.testFiles.push(...tests);
|
|
228
|
+
for (const test of tests) result.testPackages[test] = ".";
|
|
229
|
+
result.edges.push(...graph.edges.map((edge) => ({ ...edge, kind: "import" as const })));
|
|
230
|
+
result.blockers.push(...graph.blockers);
|
|
231
|
+
if (!files.length) result.blockers.push("Python analysis found no Python files");
|
|
232
|
+
return result;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export const pythonAdapter: RepositoryAdapter = {
|
|
236
|
+
id: "python", version: "1", kind: "language",
|
|
237
|
+
detect: ({ files }) => PROJECT_FILES.some((file) => files.includes(file)) && files.some(isPythonSource),
|
|
238
|
+
analyze(context) {
|
|
239
|
+
const interpreter = pythonInterpreter(context.repoPath);
|
|
240
|
+
const result = analyzePythonRepository(context, (files) => {
|
|
241
|
+
if (!interpreter) return "Python analysis needs a Python 3 interpreter (python3, python or py -3) on PATH";
|
|
242
|
+
const run = spawnSync(interpreter[0]!, [...interpreter.slice(1), "-c", PARSE_SCRIPT], {
|
|
243
|
+
cwd: context.repoPath, input: JSON.stringify(files), encoding: "utf8", timeout: 120_000, maxBuffer: 256 * 1024 * 1024, windowsHide: true,
|
|
244
|
+
});
|
|
245
|
+
if (run.status !== 0) return `Python import analysis failed: ${(run.stderr || run.error?.message || "").trim().split(/\r?\n/).pop() ?? "unknown error"}`;
|
|
246
|
+
try { return JSON.parse(run.stdout) as Record<string, PythonFileImports>; }
|
|
247
|
+
catch { return "Python import analysis produced unreadable output"; }
|
|
248
|
+
});
|
|
249
|
+
if (interpreter) result.interpreter = interpreter;
|
|
250
|
+
return result;
|
|
251
|
+
},
|
|
252
|
+
};
|
|
@@ -21,6 +21,8 @@ export interface AdapterContribution {
|
|
|
21
21
|
testFiles: string[];
|
|
22
22
|
testPackages: Record<string, string>;
|
|
23
23
|
executionEnv?: Record<string, string>;
|
|
24
|
+
/** The interpreter the adapter analysed with and its runner should use, such as ["python3"]. */
|
|
25
|
+
interpreter?: string[];
|
|
24
26
|
/** Global blockers: missing edges cannot be dismissed using graph reachability. */
|
|
25
27
|
blockers: string[];
|
|
26
28
|
fileBlockers?: Array<{ path: string; reason: string }>;
|
|
@@ -66,6 +66,30 @@ const IMPLICIT_BASENAMES = new Set([
|
|
|
66
66
|
const IMPLICIT_PREFIXES = ["tsconfig", "jsconfig", "wrangler.", "dockerfile", "docker-compose", ".dockerignore", ".mocharc.", ".c8rc.", ".nycrc.", "babel.config", ".babelrc."];
|
|
67
67
|
const ENV_TEMPLATE_SUFFIX = /\.(?:example|sample|template|dist)$/;
|
|
68
68
|
|
|
69
|
+
/**
|
|
70
|
+
* Coding-agent configuration (2026-11-07): MCP server lists, agent hooks, rules and skills. Only coding
|
|
71
|
+
* agents read these; no build, test runner or CI job does, so a change to one, or a package it names,
|
|
72
|
+
* cannot change a test result. `diffci init` writes several of them, and on DentalPresence the first
|
|
73
|
+
* commit carrying them ran all 624 tests ("Unknown changed file: .mcp.json") and kept a DiffCI bump
|
|
74
|
+
* from narrowing.
|
|
75
|
+
*/
|
|
76
|
+
export function isAgentConfigurationPath(filePath: string): boolean {
|
|
77
|
+
const normalized = filePath.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
78
|
+
if (normalized === ".mcp.json") return true;
|
|
79
|
+
return /^\.(?:claude|codex)\//.test(normalized) || /^\.cursor\/(?:mcp\.json$|hooks\.json$|rules\/)/.test(normalized);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Whether `content` of a tsconfig/jsconfig names something outside `include`, `exclude` and `files`
|
|
84
|
+
* (2026-11-07). Those list paths, not packages: DentalPresence's `"exclude": ["diffci"]`, a directory,
|
|
85
|
+
* read as tsconfig loading the `diffci` CLI and blocked every bump of it. `extends`, `types`, `plugins`
|
|
86
|
+
* and `paths` still count.
|
|
87
|
+
*/
|
|
88
|
+
export function compilerConfigNames(filePath: string, content: string, named: RegExp): boolean {
|
|
89
|
+
if (!/^[jt]sconfig[^/]*\.json$/i.test(posix.basename(filePath))) return named.test(content);
|
|
90
|
+
return named.test(content.replace(/"(?:include|exclude|files)"\s*:\s*\[[^\]]*\]/g, ""));
|
|
91
|
+
}
|
|
92
|
+
|
|
69
93
|
/** True when tooling may load `filePath` implicitly, so no reference to it would ever be written. */
|
|
70
94
|
export function isImplicitlyLoadedFile(filePath: string): boolean {
|
|
71
95
|
const base = posix.basename(filePath).toLowerCase();
|
|
@@ -290,6 +314,24 @@ function inExclusionList(content: string, index: number): boolean {
|
|
|
290
314
|
return false;
|
|
291
315
|
}
|
|
292
316
|
|
|
317
|
+
/**
|
|
318
|
+
* Whether code in `readerPath` could be naming `target` by its bare file name: it sits in the target's
|
|
319
|
+
* directory, or its text names one of the target's directories as a word (`"hotfixWorkflow"`,
|
|
320
|
+
* `scripts/`), which is how code elsewhere would reach that directory to run or read a file there. Only
|
|
321
|
+
* applied to a reader of a reader (`ancestors` false): 2026-11-06, a LobeHub root package.json edit
|
|
322
|
+
* reached scripts/hotfixWorkflow/index.ts, and every code file in the repository containing the word
|
|
323
|
+
* `index.ts` became a further reader until the 50-reader limit forced the full suite. Non-code readers
|
|
324
|
+
* (shell scripts, workflow and tool configuration) set their working directory in ways not modelled
|
|
325
|
+
* here, so they still count on the bare name.
|
|
326
|
+
*/
|
|
327
|
+
function namesDirectoryOf(content: string, readerPath: string, target: string): boolean {
|
|
328
|
+
if (!/\.[cm]?[jt]sx?$/.test(readerPath)) return true;
|
|
329
|
+
const dir = posix.dirname(target);
|
|
330
|
+
if (dir === "." || posix.dirname(readerPath) === dir) return true;
|
|
331
|
+
const names = dir.split("/").filter(Boolean);
|
|
332
|
+
return names.some((name) => new RegExp(`(?:^|["'\`/\s(])${escape(name)}(?=$|["'\`/\s),])`, "m").test(content));
|
|
333
|
+
}
|
|
334
|
+
|
|
293
335
|
/**
|
|
294
336
|
* Whether `content`, read from `readerPath`, names `target` (or, with `ancestors`, one of its
|
|
295
337
|
* directories), once each matching word is read as a whole path (2026-10-28). The reference pattern
|
|
@@ -320,6 +362,7 @@ export function contentNamesPath(content: string, readerPath: string, target: st
|
|
|
320
362
|
if (names.some((name) => name === rest || name.endsWith(`/${rest}`) || rest.endsWith(`/${name}`))) return true;
|
|
321
363
|
continue;
|
|
322
364
|
}
|
|
365
|
+
if (!word.includes("/") && !/[!$]/.test(word) && !ancestors && !namesDirectoryOf(content, readerPath, target)) continue;
|
|
323
366
|
if (!word.includes("/") || /[!$]/.test(word)) return true;
|
|
324
367
|
if (/[*?{}[\]]/.test(word)) {
|
|
325
368
|
if (!readGlobs) continue;
|
|
@@ -4,6 +4,7 @@ import { isBuiltin } from "node:module";
|
|
|
4
4
|
import { dirname, extname, join, normalize, relative, resolve, sep } from "node:path";
|
|
5
5
|
import ts from "typescript";
|
|
6
6
|
import { adapterFiles, REPOSITORY_ADAPTERS } from "./adapters/index.js";
|
|
7
|
+
import { pythonAdapter } from "./adapters/python.js";
|
|
7
8
|
import { analyzeRepository, type AnalyzeRepositoryOptions } from "./analyzer.js";
|
|
8
9
|
import { applyVueScope, inVuePackage } from "./vue-scope.js";
|
|
9
10
|
import type {
|
|
@@ -30,7 +31,7 @@ interface ImportRef {
|
|
|
30
31
|
/** For a computed load whose target set is still bounded by literal text: `` import(`./x/${a}.json`) ``
|
|
31
32
|
* or `import.meta.glob("./x/*.json")`. `base` is the literal directory prefix (a specifier ending in
|
|
32
33
|
* "/"); `regex` matches paths relative to it. Unresolvable patterns keep the load computed. */
|
|
33
|
-
patterns?: { base: string; regex: string; negated: boolean }[];
|
|
34
|
+
patterns?: { base: string; regex: string; negated: boolean; viteRoot?: boolean }[];
|
|
34
35
|
/** `import { type A, type B }` or `export { type A } from`: every specifier is inline `type`, so the
|
|
35
36
|
* statement is erased unless the importer's tsconfig preserves imports (see `keepsTypeOnlyImports`). */
|
|
36
37
|
inlineTypeOnly?: boolean;
|
|
@@ -59,16 +60,94 @@ const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"
|
|
|
59
60
|
// A specifier may omit the extension or name a directory's index module.
|
|
60
61
|
const OPTIONAL_MODULE_SUFFIX = "(?:\\.[A-Za-z0-9]+|/index\\.[A-Za-z0-9]+)?";
|
|
61
62
|
|
|
62
|
-
/**
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
63
|
+
/** A specifier expression folded into literal text and unknown holes (`undefined`), adjacent text joined. */
|
|
64
|
+
type SpecifierParts = (string | undefined)[];
|
|
65
|
+
|
|
66
|
+
/** `const` bindings with an initializer, by name, for names the file binds exactly once. A name bound
|
|
67
|
+
* twice anywhere (a parameter, a `let`, a second `const` in another scope) could mean either binding at
|
|
68
|
+
* a given use, so it is left out and its uses stay unknown. */
|
|
69
|
+
function singleConstBindings(sourceFile: ts.SourceFile): Map<string, ts.Expression> {
|
|
70
|
+
const counts = new Map<string, number>();
|
|
71
|
+
const consts = new Map<string, ts.Expression>();
|
|
72
|
+
const count = (name: ts.BindingName | undefined) => {
|
|
73
|
+
if (!name) return;
|
|
74
|
+
if (ts.isIdentifier(name)) { counts.set(name.text, (counts.get(name.text) ?? 0) + 1); return; }
|
|
75
|
+
for (const element of name.elements) if (!ts.isOmittedExpression(element)) count(element.name);
|
|
76
|
+
};
|
|
77
|
+
// Source files parsed by the Program have no parent pointers, so `const` is read from the list.
|
|
78
|
+
const visit = (node: ts.Node) => {
|
|
79
|
+
if (ts.isVariableDeclarationList(node)) {
|
|
80
|
+
const isConst = (node.flags & ts.NodeFlags.Const) !== 0;
|
|
81
|
+
for (const declaration of node.declarations) {
|
|
82
|
+
if (isConst && ts.isIdentifier(declaration.name) && declaration.initializer) consts.set(declaration.name.text, declaration.initializer);
|
|
83
|
+
}
|
|
84
|
+
} else if (ts.isVariableDeclaration(node)) count(node.name);
|
|
85
|
+
else if (ts.isParameter(node) || ts.isBindingElement(node)) count(node.name);
|
|
86
|
+
else if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isFunctionExpression(node)) && node.name) count(node.name);
|
|
87
|
+
else if (ts.isImportClause(node) && node.name) count(node.name);
|
|
88
|
+
else if (ts.isImportSpecifier(node) || ts.isNamespaceImport(node)) count(node.name);
|
|
89
|
+
else if (ts.isImportEqualsDeclaration(node)) count(node.name);
|
|
90
|
+
ts.forEachChild(node, visit);
|
|
91
|
+
};
|
|
92
|
+
visit(sourceFile);
|
|
93
|
+
for (const name of [...consts.keys()]) if (counts.get(name) !== 1) consts.delete(name);
|
|
94
|
+
return consts;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Folds string concatenation, templates and single `const` bindings (2026-11-06: LobeHub's
|
|
98
|
+
* `import('./genServerAiProviderConfig?v=' + Date.now())` and `const modulePath = '../x' + '.mts'`
|
|
99
|
+
* made both tests COMPUTED_IMPORT selections on every commit). Anything else is an unknown hole. */
|
|
100
|
+
function specifierParts(expression: ts.Expression, consts: ReadonlyMap<string, ts.Expression>, depth = 0): SpecifierParts {
|
|
101
|
+
const join = (parts: SpecifierParts): SpecifierParts => {
|
|
102
|
+
const joined: SpecifierParts = [];
|
|
103
|
+
for (const part of parts) {
|
|
104
|
+
const last = joined.length - 1;
|
|
105
|
+
if (typeof part === "string" && typeof joined[last] === "string") joined[last] += part;
|
|
106
|
+
else if (part !== undefined || joined[last] !== undefined || last < 0) joined.push(part);
|
|
107
|
+
}
|
|
108
|
+
return joined;
|
|
109
|
+
};
|
|
110
|
+
if (depth > 8) return [undefined];
|
|
111
|
+
if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) return [expression.text];
|
|
112
|
+
if (ts.isParenthesizedExpression(expression)) return specifierParts(expression.expression, consts, depth + 1);
|
|
113
|
+
if (ts.isTemplateExpression(expression)) {
|
|
114
|
+
return join([expression.head.text, ...expression.templateSpans.flatMap((span) => [...specifierParts(span.expression, consts, depth + 1), span.literal.text])]);
|
|
115
|
+
}
|
|
116
|
+
if (ts.isBinaryExpression(expression) && expression.operatorToken.kind === ts.SyntaxKind.PlusToken) {
|
|
117
|
+
const left = specifierParts(expression.left, consts, depth + 1);
|
|
118
|
+
// `+` concatenates only when one side is a string; two unknowns could be a numeric sum.
|
|
119
|
+
if (!left.some((part) => typeof part === "string")) {
|
|
120
|
+
const right = specifierParts(expression.right, consts, depth + 1);
|
|
121
|
+
return right.some((part) => typeof part === "string") ? join([...left, ...right]) : [undefined];
|
|
122
|
+
}
|
|
123
|
+
return join([...left, ...specifierParts(expression.right, consts, depth + 1)]);
|
|
124
|
+
}
|
|
125
|
+
if (ts.isIdentifier(expression)) {
|
|
126
|
+
const initializer = consts.get(expression.text);
|
|
127
|
+
if (initializer) return specifierParts(initializer, consts, depth + 1);
|
|
128
|
+
}
|
|
129
|
+
return [undefined];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** A folded specifier: its literal text, or the patterns bounding it. A query (`?v=...`) selects no file
|
|
133
|
+
* of its own: Vite and Node strip it before resolving, so text after the first `?` is dropped. */
|
|
134
|
+
function foldedSpecifier(parts: SpecifierParts): { literal: string } | { patterns: ImportRef["patterns"] } {
|
|
135
|
+
const cut: SpecifierParts = [];
|
|
136
|
+
for (const part of parts) {
|
|
137
|
+
if (typeof part === "string" && part.includes("?")) { cut.push(part.slice(0, part.indexOf("?"))); break; }
|
|
138
|
+
cut.push(part);
|
|
139
|
+
}
|
|
140
|
+
if (cut.every((part) => typeof part === "string")) return { literal: cut.join("") };
|
|
141
|
+
const head = typeof cut[0] === "string" ? cut[0] : "";
|
|
142
|
+
const slash = head.lastIndexOf("/");
|
|
143
|
+
if (slash < 0) return { patterns: undefined };
|
|
144
|
+
// A hole can hold "/" so it matches across directories, which can only over-select.
|
|
145
|
+
const regex = escapeRegex(head.slice(slash + 1)) + cut.slice(1).map((part) => part === undefined ? ".*" : escapeRegex(part)).join("");
|
|
146
|
+
return { patterns: [{ base: head.slice(0, slash + 1), regex: `${regex}${OPTIONAL_MODULE_SUFFIX}`, negated: false }] };
|
|
70
147
|
}
|
|
71
148
|
|
|
149
|
+
const VITE_CONFIG_NAMES = ["vite", "vitest"].flatMap((tool) => ["ts", "mts", "cts", "js", "mjs", "cjs"].map((ext) => `${tool}.config.${ext}`));
|
|
150
|
+
|
|
72
151
|
/** One Vite `import.meta.glob` pattern; `[...]` classes are not translated and keep the load computed. */
|
|
73
152
|
function globPattern(glob: string): NonNullable<ImportRef["patterns"]>[number] | undefined {
|
|
74
153
|
const negated = glob.startsWith("!");
|
|
@@ -91,7 +170,8 @@ function globPattern(glob: string): NonNullable<ImportRef["patterns"]>[number] |
|
|
|
91
170
|
i = close;
|
|
92
171
|
} else regex += escapeRegex(char);
|
|
93
172
|
}
|
|
94
|
-
|
|
173
|
+
// Vite resolves a glob starting with "/" from its project root, not the filesystem root.
|
|
174
|
+
return { base: body.slice(0, cut + 1), regex, negated, ...(body.startsWith("/") ? { viteRoot: true } : {}) };
|
|
95
175
|
}
|
|
96
176
|
|
|
97
177
|
function isImportMetaGlob(expression: ts.Expression): boolean {
|
|
@@ -190,6 +270,7 @@ function scopeShadowsRequire(scope: ts.Node): boolean {
|
|
|
190
270
|
function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
|
|
191
271
|
const refs: ImportRef[] = [];
|
|
192
272
|
let shadowDepth = 0;
|
|
273
|
+
let consts: Map<string, ts.Expression> | undefined;
|
|
193
274
|
|
|
194
275
|
function visit(node: ts.Node) {
|
|
195
276
|
const shadows = scopeShadowsRequire(node);
|
|
@@ -221,12 +302,14 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
|
|
|
221
302
|
const isImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
|
|
222
303
|
const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require" && shadowDepth === 0;
|
|
223
304
|
if ((isImport || isRequire) && firstArg) {
|
|
224
|
-
const
|
|
225
|
-
const
|
|
305
|
+
const syntaxLiteral = ts.isStringLiteral(firstArg) || ts.isNoSubstitutionTemplateLiteral(firstArg);
|
|
306
|
+
const folded = foldedSpecifier(specifierParts(firstArg, consts ??= singleConstBindings(sourceFile)));
|
|
307
|
+
const literal = "literal" in folded;
|
|
308
|
+
const patterns = "patterns" in folded ? folded.patterns : undefined;
|
|
226
309
|
refs.push({
|
|
227
|
-
specifier:
|
|
310
|
+
specifier: syntaxLiteral ? firstArg.text : literal ? folded.literal : firstArg.getText(sourceFile).slice(0, 200),
|
|
228
311
|
kind: isImport ? "dynamic-import" : "require",
|
|
229
|
-
dynamic: isImport || !
|
|
312
|
+
dynamic: isImport || !syntaxLiteral,
|
|
230
313
|
computed: !literal,
|
|
231
314
|
...(patterns ? { patterns } : {}),
|
|
232
315
|
});
|
|
@@ -793,7 +876,8 @@ export async function buildDependencyGraph(
|
|
|
793
876
|
if (contributions.some((item) => item.id === "go") && files.some((file) => /\.(?:[cm]?[jt]sx?|vue)$/.test(file))) {
|
|
794
877
|
adapterBlockers.push("Mixed Go/JavaScript repositories require explicit cross-language dependencies; full validation required");
|
|
795
878
|
}
|
|
796
|
-
|
|
879
|
+
const pythonModeled = contributions.some((item) => item.id === "python");
|
|
880
|
+
if (contributions.length && files.some((file) => (!pythonModeled && /\.py$/.test(file)) || /\.(?:rs|cs|svelte|astro)$/.test(file) || !contributions.some((item) => item.id === "maven") && /\.(?:java|kt)$/.test(file))) {
|
|
797
881
|
adapterBlockers.push("Unmodeled languages alongside an adapter require full validation");
|
|
798
882
|
}
|
|
799
883
|
profile.adapters = contributions.map(({ id, version, blockers }) => ({ id, version, blockers }));
|
|
@@ -805,11 +889,17 @@ export async function buildDependencyGraph(
|
|
|
805
889
|
embeds: [...new Set(goContribution.assetPaths)].sort(),
|
|
806
890
|
} : undefined;
|
|
807
891
|
profile.mavenTestModules = Object.assign({}, ...contributions.filter((item) => item.id === "maven").map((item) => item.testPackages));
|
|
892
|
+
const pythonContribution = contributions.find((item) => item.id === "python");
|
|
893
|
+
if (pythonContribution) {
|
|
894
|
+
profile.pythonSources = [...new Set(pythonContribution.sourcePaths)].sort();
|
|
895
|
+
profile.pythonTests = [...new Set(pythonContribution.testFiles)].sort();
|
|
896
|
+
if (pythonContribution.interpreter) profile.pythonInterpreter = pythonContribution.interpreter;
|
|
897
|
+
}
|
|
808
898
|
const adapterTests = contributions.flatMap((item) => item.testFiles);
|
|
809
899
|
profile.testFilePaths = [...new Set([...profile.testFilePaths, ...adapterTests])].sort();
|
|
810
900
|
if (profile.testUniverse) {
|
|
811
901
|
profile.testUniverse.discoveredTestFiles = profile.testFilePaths.length;
|
|
812
|
-
profile.testUniverse.blindSpot = (profile.testUniverse.declaredFrameworks.length > 0 || contributions.some((item) => item.id === "go" || item.id === "maven")) && profile.testFilePaths.length === 0;
|
|
902
|
+
profile.testUniverse.blindSpot = (profile.testUniverse.declaredFrameworks.length > 0 || contributions.some((item) => item.id === "go" || item.id === "maven" || item.id === "python")) && profile.testFilePaths.length === 0;
|
|
813
903
|
}
|
|
814
904
|
const entryPointPaths = new Set(profile.entryPoints.map((e) => e.path));
|
|
815
905
|
|
|
@@ -895,6 +985,22 @@ export async function buildDependencyGraph(
|
|
|
895
985
|
addEdge(importerRel, assetRel, "asset");
|
|
896
986
|
}
|
|
897
987
|
|
|
988
|
+
let fileSet: Set<string> | undefined;
|
|
989
|
+
/** Where Vite may resolve a root-absolute glob for this importer: each enclosing directory holding a
|
|
990
|
+
* Vite or Vitest configuration, and the repository root (Vite's default root when run from there).
|
|
991
|
+
* Matches in every candidate are unioned, which can only over-select (2026-11-06: LobeHub's
|
|
992
|
+
* `import.meta.glob('/locales/*\/ui.json')` kept two desktop tests selected on every commit). */
|
|
993
|
+
function viteRoots(importerAbs: string): string[] {
|
|
994
|
+
const roots = new Set<string>([repoPath]);
|
|
995
|
+
for (let directory = dirname(importerAbs); toRelativeInternal(repoPath, directory) !== undefined; directory = dirname(directory)) {
|
|
996
|
+
const rel = toRelativeInternal(repoPath, directory)!;
|
|
997
|
+
const prefix = rel === "." ? "" : `${rel}/`;
|
|
998
|
+
if (VITE_CONFIG_NAMES.some((name) => (fileSet ??= new Set(files)).has(prefix + name))) roots.add(directory);
|
|
999
|
+
if (rel === "." || dirname(directory) === directory) break;
|
|
1000
|
+
}
|
|
1001
|
+
return [...roots];
|
|
1002
|
+
}
|
|
1003
|
+
|
|
898
1004
|
/** Every repository file a bounded computed load can name, or undefined to keep it computed: the
|
|
899
1005
|
* base directory does not resolve, nothing matches, or a match is neither analyzed source nor an
|
|
900
1006
|
* asset. Alias directories resolve as in findAssetCandidate, and all candidates are unioned. */
|
|
@@ -905,8 +1011,9 @@ export async function buildDependencyGraph(
|
|
|
905
1011
|
const excluded = new Set<string>();
|
|
906
1012
|
for (const pattern of patterns) {
|
|
907
1013
|
const base = pattern.base.replace(/\/+$/, "") || ".";
|
|
908
|
-
if (base.startsWith("/")) return undefined;
|
|
909
|
-
const directories =
|
|
1014
|
+
if (base.startsWith("/") && !pattern.viteRoot) return undefined;
|
|
1015
|
+
const directories = pattern.viteRoot ? viteRoots(importerAbs).map((root) => join(root, base))
|
|
1016
|
+
: base.startsWith(".") ? [resolve(dirname(importerAbs), base)]
|
|
910
1017
|
: [...expandAliasCandidates(base, compilerAliases, aliasRoot), ...expandAliasCandidates(base, profile.pathAliases, repoPath)];
|
|
911
1018
|
const matcher = new RegExp(`^${pattern.regex}$`);
|
|
912
1019
|
for (const directory of directories) {
|
|
@@ -926,6 +1033,12 @@ export async function buildDependencyGraph(
|
|
|
926
1033
|
|
|
927
1034
|
let filesParsed = sourceFiles.length;
|
|
928
1035
|
let followedImplementationFiles = 0;
|
|
1036
|
+
// Implementation files outside the tsconfig inventory that an import may still pull in before the graph
|
|
1037
|
+
// fails closed. A fixed 500 was too small for monorepos whose tests and their helpers sit outside every
|
|
1038
|
+
// tsconfig: 2026-11-06, payloadcms/payload's solution tsconfig covers packages/*/src only, while test/,
|
|
1039
|
+
// templates/ and tools/ hold about 2,700 imported source files, so every commit was UNSAFE with about
|
|
1040
|
+
// 220 blockers. Scale with the repository instead, keeping a floor for small inventories.
|
|
1041
|
+
const followBudget = Math.max(5000, sourceFiles.length);
|
|
929
1042
|
|
|
930
1043
|
// Resolve each importer with its own nearest project, never another package's
|
|
931
1044
|
// aliases. Invalid project configuration remains a hard safety blocker.
|
|
@@ -1104,7 +1217,7 @@ export async function buildDependencyGraph(
|
|
|
1104
1217
|
// initial walk. Parse it (and its imports) rather than silently dropping
|
|
1105
1218
|
// the edge or loading every TypeScript declaration library again.
|
|
1106
1219
|
try {
|
|
1107
|
-
if (isExcludedPath(targetRel, options.excludeDirs ?? []) || followedImplementationFiles >=
|
|
1220
|
+
if (isExcludedPath(targetRel, options.excludeDirs ?? []) || followedImplementationFiles >= followBudget || statSync(resolved).size > 5 * 1024 * 1024) throw new Error("excluded or exceeds parse budget");
|
|
1108
1221
|
const followed = ts.createSourceFile(resolved, readFileSync(resolved, "utf8"), ts.ScriptTarget.Latest, true);
|
|
1109
1222
|
if ((followed as unknown as { parseDiagnostics?: unknown[] }).parseDiagnostics?.length) throw new Error("invalid implementation syntax");
|
|
1110
1223
|
sourceFiles.push(followed);
|
|
@@ -1290,7 +1403,8 @@ export function classifyRepositoryProject(repoPath: string): { capable: boolean;
|
|
|
1290
1403
|
if (files.includes("go.mod")) return { capable: true, reason: "Go module (package-level analysis)" };
|
|
1291
1404
|
if (files.some((file) => file.endsWith(".vue"))) return { capable: true, reason: "Vue single-file components" };
|
|
1292
1405
|
if (files.includes("pom.xml") && files.some((file) => file.endsWith(".java") || file.endsWith(".kt"))) return { capable: true, reason: "Maven reactor (module-level Java analysis)" };
|
|
1293
|
-
return { capable:
|
|
1406
|
+
if (pythonAdapter.detect({ repoPath, files, profile: {} as RepositoryProfile })) return { capable: true, reason: "Python project tested with pytest (file-level import analysis)" };
|
|
1407
|
+
return { capable: false, reason: "No TypeScript project, Vue components, root Go module, Maven reactor, or Python project found" };
|
|
1294
1408
|
}
|
|
1295
1409
|
|
|
1296
1410
|
export interface TypeScriptProjectCapability {
|
|
@@ -1580,6 +1694,26 @@ export function refineConfidenceForDelta(result: DependencyGraphResult, changedF
|
|
|
1580
1694
|
return result.resolvedViaProjectReferences ? "PARTIAL" : "COMPLETE";
|
|
1581
1695
|
}
|
|
1582
1696
|
|
|
1697
|
+
/** Why the graph's own confidence is below COMPLETE, in counts only (no paths), so a report can say why a
|
|
1698
|
+
* repository-wide UNSAFE did not decide this change's verdict. 2026-11-06: every LobeHub receipt read
|
|
1699
|
+
* "UNSAFE" beside "safe to propose" with nothing connecting the two. Empty when the graph is COMPLETE. */
|
|
1700
|
+
export function explainGraphConfidence(result: DependencyGraphResult): string[] {
|
|
1701
|
+
const reasons: string[] = [];
|
|
1702
|
+
const plural = (count: number, one: string, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
|
|
1703
|
+
if (result.graph.nodes.every((node) => !node.isSource)) reasons.push("no source files were analysed");
|
|
1704
|
+
if (result.integrity.criticalCount > 0) reasons.push(`${plural(result.integrity.criticalCount, "graph integrity problem")}; every change falls back to full validation`);
|
|
1705
|
+
if (result.adapterBlockers?.length) reasons.push(`${plural(result.adapterBlockers.length, "unsupported framework or language relationship")}; every change falls back to full validation`);
|
|
1706
|
+
const computed = result.unresolved.filter((ref) => ref.computed);
|
|
1707
|
+
const staticRefs = result.unresolved.filter((ref) => !ref.computed);
|
|
1708
|
+
if (computed.length) {
|
|
1709
|
+
const importers = new Set(computed.map((ref) => ref.importer)).size;
|
|
1710
|
+
reasons.push(`${plural(computed.length, "computed module load")} in ${plural(importers, "file")}; the tests that run them are selected for every code change`);
|
|
1711
|
+
}
|
|
1712
|
+
if (staticRefs.length) reasons.push(`${plural(staticRefs.length, "unresolved import")}; a change that reaches one falls back to full validation`);
|
|
1713
|
+
if (result.resolvedViaProjectReferences) reasons.push("compiler options are merged across TypeScript project references, which caps confidence at PARTIAL");
|
|
1714
|
+
return reasons;
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1583
1717
|
export function graphToJson(result: DependencyGraphResult): string {
|
|
1584
1718
|
const { graph, profile, unresolved, references, counts, externalReferences, platformBuiltinReferences, internalAssetEdges, performance, confidence, integrity } = result;
|
|
1585
1719
|
return JSON.stringify(
|