@nodii/dev 0.6.130 → 0.6.132
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 +34 -2
- package/dist/cli.js +22 -5
- package/dist/core.js +1 -1
- package/dist/flags.js +1 -0
- package/dist/heavy-slot.sh +206 -32
- package/dist/heavy.js +36 -8
- package/dist/impact.js +470 -0
- package/dist/lanes.js +3 -0
- package/dist/repo-policy.js +5 -2
- package/dist/review.js +54 -4
- package/dist/surface.js +207 -32
- package/package.json +1 -1
package/dist/impact.js
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
// hub-401 (MW2-20, K01-27, MW2-51): tests run only on what changed.
|
|
2
|
+
//
|
|
3
|
+
// `nodii-dev test affected [--base REF] [--run] [--json]` reads the change
|
|
4
|
+
// (the worktree against its merge base with origin/main, uncommitted and
|
|
5
|
+
// untracked files included), walks the import graph backwards from each
|
|
6
|
+
// changed file to the test files that reach it, and prints the command that
|
|
7
|
+
// runs exactly those tests, one per package. With --run it runs them, each
|
|
8
|
+
// under a slot sized to the change: a small change takes a light slot, a large
|
|
9
|
+
// one a heavy slot (heavy-slot.sh v27).
|
|
10
|
+
//
|
|
11
|
+
// The graph is the repository's own source, read without a bundler: static
|
|
12
|
+
// and dynamic imports, require, re-exports, vi/jest/bun module mocks, and
|
|
13
|
+
// `new URL("./x", import.meta.url)` file references. Specifiers resolve as
|
|
14
|
+
// relative paths, through the nearest tsconfig's `paths`, or to a workspace
|
|
15
|
+
// package by name. A changed file the graph cannot place (a manifest, a
|
|
16
|
+
// lockfile, a test or build config, or an unreferenced data file) selects the
|
|
17
|
+
// full suite: the selection fails closed, never open.
|
|
18
|
+
import { execFile, spawn } from "node:child_process";
|
|
19
|
+
import { readFile } from "node:fs/promises";
|
|
20
|
+
import { join, posix } from "node:path";
|
|
21
|
+
import { promisify } from "node:util";
|
|
22
|
+
import { CliError } from "./core.js";
|
|
23
|
+
import { heavySlotArgv } from "./heavy.js";
|
|
24
|
+
|
|
25
|
+
const execFileAsync = promisify(execFile);
|
|
26
|
+
|
|
27
|
+
export const TEST_USAGE = "nodii-dev test affected [--base REF] [--max-light N] [--run] [--json]";
|
|
28
|
+
export const DEFAULT_BASE = "origin/main";
|
|
29
|
+
/** A change whose affected tests number at most this runs in a light slot (heavy-slot.sh LIGHT_MAX_TEST_FILES). */
|
|
30
|
+
export const DEFAULT_MAX_LIGHT = 20;
|
|
31
|
+
|
|
32
|
+
const CODE = /\.(?:[cm]?[jt]sx?)$/;
|
|
33
|
+
const TEST_FILE = /(?:^|\/)(?:__tests__\/.+|[^/]+\.(?:test|spec)\.[cm]?[jt]sx?)$/;
|
|
34
|
+
const EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
|
|
35
|
+
|
|
36
|
+
// A change to one of these can change every test's outcome: it selects the full suite.
|
|
37
|
+
const GLOBAL_FILE = [
|
|
38
|
+
/(?:^|\/)package\.json$/,
|
|
39
|
+
/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|bun\.lockb?|npm-shrinkwrap\.json)$/,
|
|
40
|
+
/(?:^|\/)tsconfig(?:\.[^/]*)?\.json$/,
|
|
41
|
+
/(?:^|\/)(?:vitest|vite|jest|babel|playwright|turbo)\.(?:config|workspace)(?:\.[^/]*)?\.[cm]?[jt]s$/,
|
|
42
|
+
/(?:^|\/)(?:jest\.config|turbo|nx|babel\.config)\.json$/,
|
|
43
|
+
/(?:^|\/)\.babelrc(?:\.json)?$/,
|
|
44
|
+
/(?:^|\/)(?:bunfig\.toml|\.nvmrc|\.node-version|\.tool-versions)$/,
|
|
45
|
+
];
|
|
46
|
+
// A change to one of these changes no test's outcome.
|
|
47
|
+
const NO_TEST_FILE = [
|
|
48
|
+
/\.(?:md|mdx|txt|png|jpe?g|gif|svg|webp|ico)$/i,
|
|
49
|
+
/(?:^|\/)(?:LICENSE|CODEOWNERS|\.gitignore|\.gitattributes|\.editorconfig|\.prettierignore|\.eslintignore)$/,
|
|
50
|
+
/^\.github\//,
|
|
51
|
+
/^\.claude\//,
|
|
52
|
+
/^docs\//,
|
|
53
|
+
/^nodii\.repo\.yaml$/,
|
|
54
|
+
/^lefthook\.ya?ml$/,
|
|
55
|
+
/^scratchpad\//,
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
const IMPORT_PATTERNS = [
|
|
59
|
+
/\b(?:import|export)\s+(?:type\s+)?(?:[\w*{}\s,$]+?\s+from\s+)?["']([^"'\n]+)["']/g,
|
|
60
|
+
/\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/g,
|
|
61
|
+
/\brequire\s*\(\s*["']([^"'\n]+)["']\s*\)/g,
|
|
62
|
+
/\b(?:vi|jest)\.(?:mock|doMock|requireActual|importActual)\s*\(\s*["']([^"'\n]+)["']/g,
|
|
63
|
+
/\bmock\.module\s*\(\s*["']([^"'\n]+)["']/g,
|
|
64
|
+
];
|
|
65
|
+
const URL_PATTERN = /\bnew\s+URL\s*\(\s*["'](\.{1,2}\/[^"'\n]+)["']\s*,\s*import\.meta\.url\s*\)/g;
|
|
66
|
+
|
|
67
|
+
/** Every module specifier SOURCE names, and the files it reaches with `new URL(…, import.meta.url)`. */
|
|
68
|
+
export function specifiers(source) {
|
|
69
|
+
const text = String(source ?? "");
|
|
70
|
+
const found = new Set();
|
|
71
|
+
for (const pattern of IMPORT_PATTERNS) for (const match of text.matchAll(pattern)) found.add(match[1]);
|
|
72
|
+
const urls = new Set();
|
|
73
|
+
for (const match of text.matchAll(URL_PATTERN)) urls.add(match[1]);
|
|
74
|
+
return { modules: [...found], urls: [...urls] };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const stripJsonComments = (text) => text
|
|
78
|
+
.replace(/("(?:\\.|[^"\\])*")|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (all, string) => string ?? "")
|
|
79
|
+
.replace(/,(\s*[}\]])/g, "$1");
|
|
80
|
+
|
|
81
|
+
/** The key a file is known by in the graph: its path without a code extension or a trailing /index. */
|
|
82
|
+
export const moduleKey = (path) => path.replace(CODE, "").replace(/\/index$/, "");
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The repository's import graph from FILES (repo-relative paths) and READ
|
|
86
|
+
* (path -> text). Returns `importers`: a map from each module key to the set
|
|
87
|
+
* of files that import it, and `unresolved` bare specifiers that name no
|
|
88
|
+
* workspace package (third-party; ignored).
|
|
89
|
+
*/
|
|
90
|
+
export async function importGraph(files, read) {
|
|
91
|
+
const all = new Set(files);
|
|
92
|
+
const code = files.filter((file) => CODE.test(file));
|
|
93
|
+
const keys = new Set(code.map(moduleKey));
|
|
94
|
+
const importers = new Map();
|
|
95
|
+
const edge = (key, from) => { if (!importers.has(key)) importers.set(key, new Set()); importers.get(key).add(from); };
|
|
96
|
+
|
|
97
|
+
// Workspace packages by name: a bare import of one is an edge into its source.
|
|
98
|
+
const packages = new Map();
|
|
99
|
+
for (const manifest of files.filter((file) => /(?:^|\/)package\.json$/.test(file))) {
|
|
100
|
+
try {
|
|
101
|
+
const json = JSON.parse(await read(manifest));
|
|
102
|
+
if (json?.name) packages.set(json.name, { dir: posix.dirname(manifest) === "." ? "" : posix.dirname(manifest), json });
|
|
103
|
+
} catch { /* an unreadable manifest names no package */ }
|
|
104
|
+
}
|
|
105
|
+
// The nearest tsconfig's baseUrl and paths, per directory, `extends` followed within the repository.
|
|
106
|
+
const tsconfigs = new Map();
|
|
107
|
+
const loadTsconfig = async (path, depth = 0) => {
|
|
108
|
+
if (depth > 5 || !all.has(path)) return null;
|
|
109
|
+
try {
|
|
110
|
+
const json = JSON.parse(stripJsonComments(await read(path)));
|
|
111
|
+
const dir = posix.dirname(path) === "." ? "" : posix.dirname(path);
|
|
112
|
+
let base = null;
|
|
113
|
+
if (typeof json.extends === "string" && json.extends.startsWith(".")) base = await loadTsconfig(posix.normalize(posix.join(dir, json.extends.endsWith(".json") ? json.extends : `${json.extends}.json`)), depth + 1);
|
|
114
|
+
const options = json.compilerOptions ?? {};
|
|
115
|
+
const own = options.paths ? { paths: options.paths, base: posix.normalize(posix.join(dir, options.baseUrl ?? ".")) } : null;
|
|
116
|
+
return own ?? base;
|
|
117
|
+
} catch { return null; }
|
|
118
|
+
};
|
|
119
|
+
const tsconfigFor = async (file) => {
|
|
120
|
+
let dir = posix.dirname(file);
|
|
121
|
+
const chain = [];
|
|
122
|
+
for (;;) {
|
|
123
|
+
if (tsconfigs.has(dir)) break;
|
|
124
|
+
chain.push(dir);
|
|
125
|
+
const candidate = dir === "." ? "tsconfig.json" : `${dir}/tsconfig.json`;
|
|
126
|
+
if (all.has(candidate)) { tsconfigs.set(dir, await loadTsconfig(candidate)); break; }
|
|
127
|
+
if (dir === "." || dir === "") { tsconfigs.set(dir, null); break; }
|
|
128
|
+
dir = posix.dirname(dir);
|
|
129
|
+
}
|
|
130
|
+
const found = tsconfigs.get(dir) ?? null;
|
|
131
|
+
for (const visited of chain) tsconfigs.set(visited, found);
|
|
132
|
+
return found;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const resolvePath = (target) => {
|
|
136
|
+
const normal = posix.normalize(target).replace(/^\.\//, "");
|
|
137
|
+
if (all.has(normal)) return CODE.test(normal) ? moduleKey(normal) : normal;
|
|
138
|
+
// `./x.js` written for a `x.ts` source (NodeNext), or no extension at all.
|
|
139
|
+
const bare = normal.replace(CODE, "");
|
|
140
|
+
if (keys.has(bare)) return bare;
|
|
141
|
+
return null;
|
|
142
|
+
};
|
|
143
|
+
const resolvePackage = (specifier) => {
|
|
144
|
+
const name = specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0];
|
|
145
|
+
const found = packages.get(name);
|
|
146
|
+
if (!found) return null;
|
|
147
|
+
const sub = specifier.slice(name.length).replace(/^\//, "");
|
|
148
|
+
const roots = [found.dir, found.dir ? `${found.dir}/src` : "src"];
|
|
149
|
+
for (const root of roots) {
|
|
150
|
+
const key = resolvePath(posix.join(root || ".", sub || "index"));
|
|
151
|
+
if (key) return key;
|
|
152
|
+
}
|
|
153
|
+
// Entry points named in the manifest, with a build directory mapped back to src.
|
|
154
|
+
for (const entry of [found.json.source, found.json.module, found.json.main, found.json.types].filter((value) => typeof value === "string")) {
|
|
155
|
+
for (const candidate of [entry, entry.replace(/^\.?\/?(?:dist|build|lib|out)\//, "src/").replace(/\.d\.ts$/, ".ts")]) {
|
|
156
|
+
const key = resolvePath(posix.join(found.dir || ".", candidate));
|
|
157
|
+
if (key) return key;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return moduleKey(posix.join(found.dir || ".", "src/index"));
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const unresolved = new Set();
|
|
164
|
+
for (const file of code) {
|
|
165
|
+
let text;
|
|
166
|
+
try { text = await read(file); } catch { continue; }
|
|
167
|
+
const { modules, urls } = specifiers(text);
|
|
168
|
+
const dir = posix.dirname(file);
|
|
169
|
+
for (const url of urls) {
|
|
170
|
+
const target = posix.normalize(posix.join(dir, url));
|
|
171
|
+
edge(CODE.test(target) ? moduleKey(target) : target, file);
|
|
172
|
+
}
|
|
173
|
+
for (const specifier of modules) {
|
|
174
|
+
if (specifier.startsWith("node:")) continue;
|
|
175
|
+
if (specifier.startsWith(".")) {
|
|
176
|
+
const target = posix.join(dir, specifier);
|
|
177
|
+
// A missing target still gets an edge: deleting a module affects its importers.
|
|
178
|
+
edge(resolvePath(target) ?? moduleKey(posix.normalize(target)), file);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const config = await tsconfigFor(file);
|
|
182
|
+
let mapped = null;
|
|
183
|
+
if (config) {
|
|
184
|
+
for (const [pattern, targets] of Object.entries(config.paths)) {
|
|
185
|
+
const star = pattern.indexOf("*");
|
|
186
|
+
const matches = star === -1 ? specifier === pattern : specifier.startsWith(pattern.slice(0, star)) && specifier.endsWith(pattern.slice(star + 1));
|
|
187
|
+
if (!matches) continue;
|
|
188
|
+
const middle = star === -1 ? "" : specifier.slice(star, specifier.length - (pattern.length - star - 1));
|
|
189
|
+
for (const target of Array.isArray(targets) ? targets : []) {
|
|
190
|
+
const key = resolvePath(posix.join(config.base, target.replace("*", middle)));
|
|
191
|
+
if (key) { mapped = key; break; }
|
|
192
|
+
}
|
|
193
|
+
if (mapped) break;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
mapped ??= resolvePackage(specifier);
|
|
197
|
+
if (mapped) edge(mapped, file);
|
|
198
|
+
else unresolved.add(specifier.split("/")[0]);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return { importers, unresolved: [...unresolved] };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** How one changed path counts: `code` (walk the graph), `global` (full suite), `none` (no test), or `data`. */
|
|
205
|
+
export function classify(path) {
|
|
206
|
+
if (GLOBAL_FILE.some((pattern) => pattern.test(path))) return "global";
|
|
207
|
+
if (NO_TEST_FILE.some((pattern) => pattern.test(path))) return "none";
|
|
208
|
+
if (CODE.test(path)) return "code";
|
|
209
|
+
return "data";
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* The test files CHANGED reaches through IMPORTERS. A data file (JSON, SQL,
|
|
214
|
+
* shell, YAML) reaches the code files that name it, by its file name in a
|
|
215
|
+
* string; one nobody names selects the full suite (`full` lists why), and so
|
|
216
|
+
* does a changed source file that no test reaches.
|
|
217
|
+
*/
|
|
218
|
+
export function selectTests(changed, { importers, files, sources }) {
|
|
219
|
+
const tests = new Set();
|
|
220
|
+
const full = [];
|
|
221
|
+
const seen = new Set();
|
|
222
|
+
const queue = [];
|
|
223
|
+
const visit = (key) => { if (!seen.has(key)) { seen.add(key); queue.push(key); } };
|
|
224
|
+
for (const path of changed) {
|
|
225
|
+
const kind = classify(path);
|
|
226
|
+
if (kind === "global") { full.push({ path, reason: "a manifest, lockfile or test or build config" }); continue; }
|
|
227
|
+
if (kind === "none") continue;
|
|
228
|
+
if (kind === "code") {
|
|
229
|
+
if (TEST_FILE.test(path) && files.has(path)) tests.add(path);
|
|
230
|
+
visit(moduleKey(path));
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
// Data: the files that import it (new URL) or name it.
|
|
234
|
+
visit(path);
|
|
235
|
+
const name = posix.basename(path);
|
|
236
|
+
let named = importers.has(path);
|
|
237
|
+
for (const [file, text] of sources) {
|
|
238
|
+
if (text.includes(`"${name}"`) || text.includes(`'${name}'`) || text.includes(`/${name}"`) || text.includes(`/${name}'`) || text.includes(`/${name}\``) || text.includes(`\`${name}\``)) {
|
|
239
|
+
named = true;
|
|
240
|
+
visit(moduleKey(file));
|
|
241
|
+
if (TEST_FILE.test(file)) tests.add(file);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (!named) full.push({ path, reason: "a data file no source names" });
|
|
245
|
+
}
|
|
246
|
+
while (queue.length) {
|
|
247
|
+
const key = queue.shift();
|
|
248
|
+
for (const importer of importers.get(key) ?? []) {
|
|
249
|
+
if (TEST_FILE.test(importer)) tests.add(importer);
|
|
250
|
+
visit(moduleKey(importer));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
// Fail closed (MW2-20): a changed source file that no test reaches through the graph may still be reached some
|
|
254
|
+
// way the graph cannot see (a path built at run time, a spawned script, a fixture): it selects the full suite.
|
|
255
|
+
for (const path of changed) {
|
|
256
|
+
if (classify(path) !== "code" || TEST_FILE.test(path)) continue;
|
|
257
|
+
if (!reachesTest(moduleKey(path), importers)) full.push({ path, reason: "no test reaches it through the import graph" });
|
|
258
|
+
}
|
|
259
|
+
return { tests: [...tests].sort(), full };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Whether any test file imports KEY, directly or through other modules. */
|
|
263
|
+
function reachesTest(key, importers) {
|
|
264
|
+
const seen = new Set([key]);
|
|
265
|
+
const queue = [key];
|
|
266
|
+
while (queue.length) {
|
|
267
|
+
for (const importer of importers.get(queue.shift()) ?? []) {
|
|
268
|
+
if (TEST_FILE.test(importer)) return true;
|
|
269
|
+
const next = moduleKey(importer);
|
|
270
|
+
if (!seen.has(next)) { seen.add(next); queue.push(next); }
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ─── runners ────────────────────────────────────────────────────────────────
|
|
277
|
+
/** The nearest package directory ("" for the root) that holds FILE, from the set of manifest dirs. */
|
|
278
|
+
function owningPackage(file, dirs) {
|
|
279
|
+
let dir = posix.dirname(file);
|
|
280
|
+
for (;;) {
|
|
281
|
+
const key = dir === "." ? "" : dir;
|
|
282
|
+
if (dirs.has(key)) return key;
|
|
283
|
+
if (dir === "." || dir === "") return "";
|
|
284
|
+
dir = posix.dirname(dir);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Runner flags that always take a value, even one that looks like a path (`--config ./jest.config.mjs`).
|
|
289
|
+
export const VALUE_FLAGS = new Set(["--config", "-c", "--timeout", "--preload", "-r", "--require", "--import", "--loader", "--experimental-loader",
|
|
290
|
+
"--project", "--root", "--dir", "--reporter", "--test-reporter", "--test-reporter-destination", "--env-file", "--tsconfig", "--tsconfig-override",
|
|
291
|
+
"--setupFiles", "--testTimeout", "--maxWorkers", "-w", "--pool", "--environment", "--conditions", "--rootDir", "--selectProjects", "--rerun-each", "--test-name-pattern", "-t"]);
|
|
292
|
+
const tokenize = (script) => String(script ?? "").trim().split(/\s+/).filter(Boolean);
|
|
293
|
+
const shellQuote = (word) => (/^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, "'\\''")}'`);
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* The command that runs FILES (relative to the package) with the package's
|
|
297
|
+
* own runner. The runner and its flags come from the package's `test` script
|
|
298
|
+
* (paths and globs in it are dropped, the files appended), so a script's
|
|
299
|
+
* config, timeout and preload flags carry over. Null when the script is not
|
|
300
|
+
* one plain runner call: the caller then runs the full script.
|
|
301
|
+
*/
|
|
302
|
+
export function runnerCommand(script, files, { exec = "npx --no-install" } = {}) {
|
|
303
|
+
const text = String(script ?? "");
|
|
304
|
+
if (!text.trim() || /&&|\|\||;|\||\$\(|`/.test(text)) return null;
|
|
305
|
+
const words = tokenize(text);
|
|
306
|
+
let at = 0;
|
|
307
|
+
while (at < words.length && /^[A-Z_][A-Z0-9_]*=/.test(words[at])) at += 1;
|
|
308
|
+
const env = words.slice(0, at);
|
|
309
|
+
const rest = words.slice(at);
|
|
310
|
+
let lead;
|
|
311
|
+
let flags;
|
|
312
|
+
const name = posix.basename(rest[0] ?? "");
|
|
313
|
+
if (name === "bun" && rest[1] === "test") { lead = ["bun", "test"]; flags = rest.slice(2); }
|
|
314
|
+
else if (name === "node" && rest.includes("--test")) { lead = ["node"]; flags = rest.slice(1); }
|
|
315
|
+
else if (name === "vitest") { lead = [...exec.split(" "), "vitest", "run"]; flags = rest.slice(rest[1] === "run" ? 2 : 1); }
|
|
316
|
+
else if (name === "jest") { lead = [...exec.split(" "), "jest"]; flags = rest.slice(1); }
|
|
317
|
+
else if (name === "mocha") { lead = [...exec.split(" "), "mocha"]; flags = rest.slice(1); }
|
|
318
|
+
else return null;
|
|
319
|
+
// Keep flags and their values; drop paths, globs and directories the script names.
|
|
320
|
+
const kept = [];
|
|
321
|
+
for (let i = 0; i < flags.length; i += 1) {
|
|
322
|
+
const word = flags[i];
|
|
323
|
+
if (word.startsWith("-")) {
|
|
324
|
+
kept.push(word);
|
|
325
|
+
const next = flags[i + 1];
|
|
326
|
+
const takesValue = VALUE_FLAGS.has(word) || !/[*/]|\.[cm]?[jt]sx?$/.test(next ?? "");
|
|
327
|
+
if (!word.includes("=") && next !== undefined && !next.startsWith("-") && takesValue && !["--test", "--watch", "--run", "--runInBand", "-i"].includes(word)) { kept.push(next); i += 1; }
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
// A bare word: a path, glob or directory. The selected files replace it.
|
|
331
|
+
}
|
|
332
|
+
if (name === "jest") kept.push("--runTestsByPath");
|
|
333
|
+
if (name === "vitest") kept.push("--passWithNoTests");
|
|
334
|
+
return [...env, ...lead, ...kept, ...files].map(shellQuote).join(" ");
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** How a package's tools are run: the lockfile at the repository root decides. */
|
|
338
|
+
export function execPrefix(files) {
|
|
339
|
+
if (files.has("pnpm-lock.yaml")) return "pnpm exec";
|
|
340
|
+
if (files.has("bun.lock") || files.has("bun.lockb")) return "bunx";
|
|
341
|
+
if (files.has("yarn.lock")) return "yarn";
|
|
342
|
+
return "npx --no-install";
|
|
343
|
+
}
|
|
344
|
+
const runScript = (files, script) => (files.has("pnpm-lock.yaml") ? `pnpm run ${script}` : files.has("bun.lock") || files.has("bun.lockb") ? `bun run ${script}` : files.has("yarn.lock") ? `yarn ${script}` : `npm run ${script}`);
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* The plan for TESTS: one job per package, each with its directory and the
|
|
348
|
+
* command that runs that package's selected tests. FULL non-empty: the
|
|
349
|
+
* repository's full test script, one job at the root.
|
|
350
|
+
*/
|
|
351
|
+
export async function planJobs({ tests, full, files, read, fullScript = "test" }) {
|
|
352
|
+
if (full.length) return [{ dir: "", command: runScript(files, fullScript), tests: [], full: true }];
|
|
353
|
+
const manifests = [...files].filter((file) => /(?:^|\/)package\.json$/.test(file));
|
|
354
|
+
const dirs = new Set(manifests.map((file) => (posix.dirname(file) === "." ? "" : posix.dirname(file))));
|
|
355
|
+
const groups = new Map();
|
|
356
|
+
for (const test of tests) {
|
|
357
|
+
const dir = owningPackage(test, dirs);
|
|
358
|
+
if (!groups.has(dir)) groups.set(dir, []);
|
|
359
|
+
groups.get(dir).push(dir ? test.slice(dir.length + 1) : test);
|
|
360
|
+
}
|
|
361
|
+
const exec = execPrefix(files);
|
|
362
|
+
const jobs = [];
|
|
363
|
+
for (const [dir, relative] of groups) {
|
|
364
|
+
let scripts = {};
|
|
365
|
+
try { scripts = JSON.parse(await read(dir ? `${dir}/package.json` : "package.json")).scripts ?? {}; } catch { /* no manifest: no script */ }
|
|
366
|
+
const script = scripts.test ?? scripts["test:unit"];
|
|
367
|
+
const command = runnerCommand(script, relative, { exec });
|
|
368
|
+
if (command) jobs.push({ dir, command, tests: relative, full: false });
|
|
369
|
+
// A package whose test script is not one runner call: run its whole script there.
|
|
370
|
+
else jobs.push({ dir, command: runScript(files, scripts.test ? "test" : fullScript), tests: relative, full: true });
|
|
371
|
+
}
|
|
372
|
+
return jobs.sort((a, b) => a.dir.localeCompare(b.dir));
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ─── git ────────────────────────────────────────────────────────────────────
|
|
376
|
+
async function git(cwd, args) {
|
|
377
|
+
const { stdout } = await execFileAsync("git", ["-C", cwd, ...args], { maxBuffer: 256 * 1024 * 1024 });
|
|
378
|
+
return stdout;
|
|
379
|
+
}
|
|
380
|
+
const lines = (text) => text.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
381
|
+
|
|
382
|
+
/** The repository root, the merge base with BASE, the changed paths (committed, staged, unstaged, untracked) and every file. */
|
|
383
|
+
export async function changeSet(cwd, base = DEFAULT_BASE) {
|
|
384
|
+
let root;
|
|
385
|
+
try { root = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim(); } catch { throw new CliError("USAGE", "Run nodii-dev test affected inside a git repository.", 2); }
|
|
386
|
+
let mergeBase;
|
|
387
|
+
try { mergeBase = (await git(root, ["merge-base", "HEAD", base])).trim(); } catch {
|
|
388
|
+
throw new CliError("IMPACT_BASE_MISSING", `No merge base with ${base}: fetch it (git fetch origin main) or pass --base REF.`, 2);
|
|
389
|
+
}
|
|
390
|
+
const changed = new Set([
|
|
391
|
+
...lines(await git(root, ["diff", "--name-only", "--no-renames", mergeBase])),
|
|
392
|
+
...lines(await git(root, ["ls-files", "--others", "--exclude-standard"])),
|
|
393
|
+
]);
|
|
394
|
+
const files = new Set(lines(await git(root, ["ls-files", "--cached", "--others", "--exclude-standard", "--deduplicate"])));
|
|
395
|
+
// A deleted file is in the diff but not on disk: keep it for the graph, never read it.
|
|
396
|
+
return { root, mergeBase, changed: [...changed].sort(), files };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** The whole analysis for the worktree at CWD. */
|
|
400
|
+
export async function affected(cwd, { base = DEFAULT_BASE, maxLight = DEFAULT_MAX_LIGHT, fullScript = "test" } = {}) {
|
|
401
|
+
const { root, mergeBase, changed, files } = await changeSet(cwd, base);
|
|
402
|
+
const cache = new Map();
|
|
403
|
+
const read = async (path) => {
|
|
404
|
+
if (!cache.has(path)) cache.set(path, readFile(join(root, path), "utf8"));
|
|
405
|
+
return cache.get(path);
|
|
406
|
+
};
|
|
407
|
+
const present = [...files].filter((file) => !/(?:^|\/)node_modules\//.test(file));
|
|
408
|
+
const { importers } = await importGraph(present, read);
|
|
409
|
+
const sources = [];
|
|
410
|
+
for (const file of present.filter((path) => CODE.test(path))) {
|
|
411
|
+
try { sources.push([file, await read(file)]); } catch { /* deleted or unreadable */ }
|
|
412
|
+
}
|
|
413
|
+
const fileSet = new Set(present);
|
|
414
|
+
const { tests, full } = selectTests(changed, { importers, files: fileSet, sources });
|
|
415
|
+
const jobs = await planJobs({ tests, full, files: fileSet, read, fullScript });
|
|
416
|
+
const size = full.length || jobs.some((job) => job.full) || tests.length > maxLight ? "heavy" : "light";
|
|
417
|
+
return { root, base, mergeBase, changed, tests, full, jobs, size, maxLight };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// ─── command ────────────────────────────────────────────────────────────────
|
|
421
|
+
const human = (result) => {
|
|
422
|
+
const out = [`${result.changed.length} changed file(s) against ${result.base} (merge base ${result.mergeBase.slice(0, 12)}).`];
|
|
423
|
+
if (result.full.length) {
|
|
424
|
+
out.push("Full suite: the change reaches every test.");
|
|
425
|
+
for (const item of result.full) out.push(` ${item.path}: ${item.reason}`);
|
|
426
|
+
} else if (!result.tests.length) out.push("No test is affected by this change.");
|
|
427
|
+
else {
|
|
428
|
+
out.push(`${result.tests.length} affected test file(s), ${result.size} slot:`);
|
|
429
|
+
for (const test of result.tests) out.push(` ${test}`);
|
|
430
|
+
}
|
|
431
|
+
for (const job of result.jobs) out.push(`run${job.dir ? ` in ${job.dir}` : ""}: ${job.command}`);
|
|
432
|
+
if (result.ran) for (const ran of result.ran) out.push(`${ran.code === 0 ? "passed" : `failed (exit ${ran.code})`}: ${ran.command}`);
|
|
433
|
+
return out.join("\n");
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
/** One job through the heavy-slot queue at its size, output streamed. */
|
|
437
|
+
export function runJob(job, { root, size, spawnImpl = spawn, argv = heavySlotArgv } = {}) {
|
|
438
|
+
return new Promise((resolve) => {
|
|
439
|
+
const [file, args] = argv(["--size", size, "--", "/bin/sh", "-c", job.command]);
|
|
440
|
+
const child = spawnImpl(file, args, { cwd: job.dir ? join(root, job.dir) : root, stdio: ["ignore", "inherit", "inherit"] });
|
|
441
|
+
child.on("error", () => resolve(127));
|
|
442
|
+
child.on("close", (code, signal) => resolve(code ?? (signal ? 128 : 1)));
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
export async function testCommand(action, rest, flags = {}, { analyse = affected, run = runJob, readPolicy } = {}) {
|
|
447
|
+
if (action !== "affected") throw new CliError("USAGE", TEST_USAGE, 2);
|
|
448
|
+
if (rest.length) throw new CliError("USAGE", `test affected takes no arguments, got: ${rest.join(" ")}. ${TEST_USAGE}`, 2);
|
|
449
|
+
const base = flags.base && flags.base !== true ? String(flags.base) : DEFAULT_BASE;
|
|
450
|
+
const maxLight = flags["max-light"] === undefined ? DEFAULT_MAX_LIGHT : Number(flags["max-light"]);
|
|
451
|
+
if (!Number.isInteger(maxLight) || maxLight < 0) throw new CliError("USAGE", "--max-light needs a whole number of test files.", 2);
|
|
452
|
+
let fullScript = "test";
|
|
453
|
+
if (readPolicy) {
|
|
454
|
+
try {
|
|
455
|
+
const root = (await execFileAsync("git", ["rev-parse", "--show-toplevel"])).stdout.trim();
|
|
456
|
+
fullScript = (await readPolicy(root))?.tests?.full ?? "test";
|
|
457
|
+
} catch { /* no policy file: the `test` script is the full suite */ }
|
|
458
|
+
}
|
|
459
|
+
const result = await analyse(process.cwd(), { base, maxLight, fullScript });
|
|
460
|
+
if (flags.run) {
|
|
461
|
+
result.ran = [];
|
|
462
|
+
for (const job of result.jobs) {
|
|
463
|
+
const code = await run(job, { root: result.root, size: result.size });
|
|
464
|
+
result.ran.push({ dir: job.dir, command: job.command, code });
|
|
465
|
+
if (code !== 0) return { payload: result, human, exitCode: code };
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
return { payload: result, human, exitCode: 0 };
|
|
469
|
+
}
|
|
470
|
+
|
package/dist/lanes.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readPolicy } from "./repo-policy.js";
|
|
1
2
|
import { execFile } from "node:child_process";
|
|
2
3
|
import { readFile, realpath, writeFile } from "node:fs/promises";
|
|
3
4
|
import { isAbsolute } from "node:path";
|
|
@@ -821,6 +822,8 @@ export async function laneCommand(action, args, flags, deps = {}) {
|
|
|
821
822
|
...(checkDeps.reviewer ? { reviewer: checkDeps.reviewer } : {}),
|
|
822
823
|
...(checkDeps.picker ? { picker: checkDeps.picker } : {}),
|
|
823
824
|
...(checkDeps.now ? { now: checkDeps.now } : {}),
|
|
825
|
+
// hub-401: the policy file names the full-suite script a gate may not run per lane.
|
|
826
|
+
fullScript: checkDeps.fullScript ?? (await readPolicy(context.worktree).then((policy) => policy?.tests?.full).catch(() => null)) ?? "test",
|
|
824
827
|
});
|
|
825
828
|
// AGENT-HARNESS-61: an agent here without the lane's config gets no managed
|
|
826
829
|
// hooks. Reported, never blocking: the check itself cannot fix a process.
|
package/dist/repo-policy.js
CHANGED
|
@@ -17,7 +17,8 @@ export const POLICY_FILE = "nodii.repo.yaml";
|
|
|
17
17
|
export const SCHEMA_VERSION = 1;
|
|
18
18
|
export const DOCS_LAYOUTS = ["standard", "drive", "existing"];
|
|
19
19
|
export const CI_PR_MODES = ["none", "affected", "full"];
|
|
20
|
-
|
|
20
|
+
// `scheduled`: a cron more often than weekly, such as the twice-daily full suite of hub-401.
|
|
21
|
+
export const CI_FULL_TRIGGERS = ["weekly", "scheduled", "dispatch", "pr", "push", "release", "label"];
|
|
21
22
|
// MW4-31.1. pre-launch.md is optional, so it is not listed.
|
|
22
23
|
export const STANDARD_DOCS = ["docs/README.md", "docs/open.md", "docs/answered.md", "docs/architecture/", "docs/runbooks/", "docs/reports/", "docs/archive/"];
|
|
23
24
|
|
|
@@ -152,7 +153,9 @@ export function validatePolicy(policy) {
|
|
|
152
153
|
const perPush = pr !== "none" || (fullOk && (full.includes("pr") || full.includes("push")));
|
|
153
154
|
if (perPush && !named.length) errors.push("ci.required / ci.reporting: a repository that runs PR or push CI must name which checks are required and which only report (MW3-22)");
|
|
154
155
|
if (Array.isArray(required) && Array.isArray(reporting)) for (const name of required) if (reporting.includes(name)) errors.push(`ci: "${name}" is both required and reporting (MW3-22)`);
|
|
155
|
-
if (pr === "none" && fullOk && !perPush && !(full.includes("weekly") && full.includes("dispatch"))) errors.push("ci.full: a
|
|
156
|
+
if (pr === "none" && fullOk && !perPush && !((full.includes("weekly") || full.includes("scheduled")) && full.includes("dispatch"))) errors.push("ci.full: a repository without PR CI must run its full suite on a schedule (weekly or scheduled) and on dispatch (MW3-15)");
|
|
157
|
+
// hub-401: a repository whose PRs run only the affected tests still runs the whole suite somewhere.
|
|
158
|
+
if (pr === "affected" && fullOk && !full.some((item) => ["weekly", "scheduled", "release"].includes(item))) errors.push("ci.full: a repository whose PRs run only the affected tests must run its full suite on a schedule or a release");
|
|
156
159
|
}
|
|
157
160
|
|
|
158
161
|
if (isObject(policy.review)) {
|
package/dist/review.js
CHANGED
|
@@ -14,6 +14,7 @@ import { pickerPrompt } from "./gather.js";
|
|
|
14
14
|
import { componentSetsIn, designCatalogSets } from "./figma-scope.js";
|
|
15
15
|
import { gitPrivatePath } from "./safety.js";
|
|
16
16
|
import { GENERATED_PAGE_GLOB, GENERATED_SUFFIX, hasGeneratedPageStamp } from "./surface.js";
|
|
17
|
+
import { VALUE_FLAGS } from "./impact.js";
|
|
17
18
|
import { heavySlotArgv } from "./heavy.js";
|
|
18
19
|
|
|
19
20
|
const execFileAsync = promisify(execFile);
|
|
@@ -73,7 +74,9 @@ export const privateStore = (cwd) => ({
|
|
|
73
74
|
export function runGate(command, cwd, { argv = heavySlotArgv } = {}) {
|
|
74
75
|
return new Promise((resolve) => {
|
|
75
76
|
let tail = "";
|
|
76
|
-
|
|
77
|
+
// `nodii-dev test affected --run` takes a slot sized to the change itself (hub-401): around it, a
|
|
78
|
+
// heavy slot would hold the large size for a small change.
|
|
79
|
+
const [file, args] = selfSizedGate(command) ? ["/bin/sh", ["-c", command]] : argv(["/bin/sh", "-c", command]);
|
|
77
80
|
const child = spawn(file, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
78
81
|
const keep = (chunk) => {
|
|
79
82
|
process.stderr.write(chunk);
|
|
@@ -86,6 +89,50 @@ export function runGate(command, cwd, { argv = heavySlotArgv } = {}) {
|
|
|
86
89
|
});
|
|
87
90
|
}
|
|
88
91
|
|
|
92
|
+
/** A gate that is one `nodii-dev test affected … --run` call, which queues its own jobs at their size. */
|
|
93
|
+
export function selfSizedGate(command) {
|
|
94
|
+
const text = String(command ?? "").trim();
|
|
95
|
+
if (/&&|\|\||;|\||\$\(|`|\n/.test(text)) return false;
|
|
96
|
+
const words = text.split(/\s+/);
|
|
97
|
+
const at = words.findIndex((word) => /(?:^|\/)nodii-dev(?:\.js)?$/.test(word));
|
|
98
|
+
if (at === -1 || words.slice(0, at).some((word) => !/^(?:[A-Z_][A-Z0-9_]*=\S*|node|bun|npx|bunx)$/.test(word))) return false;
|
|
99
|
+
const rest = words.slice(at + 1).filter((word) => !word.startsWith("-"));
|
|
100
|
+
return rest[0] === "test" && rest[1] === "affected" && words.includes("--run");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* hub-401: a gate that runs the repository's whole test suite. Per lane and per push only the affected
|
|
105
|
+
* tests run (`nodii-dev test affected --run`); the full suite runs in the twice-daily CI and the release gate.
|
|
106
|
+
* FULL_SCRIPT is the policy file's tests.full script.
|
|
107
|
+
*/
|
|
108
|
+
export function fullSuiteGate(command, fullScript = "test") {
|
|
109
|
+
const text = String(command ?? "").trim();
|
|
110
|
+
const scripts = new Set(["test", "t", fullScript]);
|
|
111
|
+
for (const part of text.split(/&&|\|\||;/).map((x) => x.trim()).filter(Boolean)) {
|
|
112
|
+
let words = part.split(/\s+/).filter((word) => !/^[A-Z_][A-Z0-9_]*=/.test(word) && !/^(?:[0-9]?>|\|)/.test(word));
|
|
113
|
+
// `npx vitest`, `bunx jest`, `pnpm exec vitest run`: the tool they start.
|
|
114
|
+
for (;;) {
|
|
115
|
+
const first = (words[0] ?? "").split("/").pop();
|
|
116
|
+
if (["npx", "bunx", "pnpx"].includes(first)) words = words.slice(1).filter((word, i) => i > 0 || !word.startsWith("-"));
|
|
117
|
+
else if (["npm", "pnpm", "yarn"].includes(first) && ["exec", "dlx"].includes(words.find((word, i) => i > 0 && !word.startsWith("-")))) words = words.slice(words.findIndex((word) => ["exec", "dlx"].includes(word)) + 1);
|
|
118
|
+
else break;
|
|
119
|
+
while (words[0]?.startsWith("-")) words = words.slice(1);
|
|
120
|
+
}
|
|
121
|
+
const [tool, ...args] = words;
|
|
122
|
+
const name = (tool ?? "").split("/").pop();
|
|
123
|
+
// Operands: not a flag, and not the value of one (`--timeout 30000`, `--config ./jest.config.mjs`).
|
|
124
|
+
const operands = args.filter((word, i) => !word.startsWith("-") && !(i > 0 && (VALUE_FLAGS.has(args[i - 1]) || /^\d+$/.test(word))));
|
|
125
|
+
if (["npm", "pnpm", "yarn", "bun"].includes(name)) {
|
|
126
|
+
const [sub, script] = operands;
|
|
127
|
+
if (["run", "run-script"].includes(sub) && scripts.has(script) && operands.length === 2) return true;
|
|
128
|
+
if (sub === "test" && name === "bun") { if (operands.length === 1) return true; continue; }
|
|
129
|
+
if (scripts.has(sub) && operands.length === 1) return true;
|
|
130
|
+
}
|
|
131
|
+
if (["vitest", "jest"].includes(name) && operands.filter((word) => word !== "run").length === 0) return true;
|
|
132
|
+
}
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
|
|
89
136
|
/** The content a receipt and a review cover: the diff itself, so uncommitted changes count too. */
|
|
90
137
|
export const diffDigest = (text) => createHash("sha256").update(text).digest("hex");
|
|
91
138
|
|
|
@@ -342,7 +389,7 @@ export function spawnReviewer({ command, args, env, cwd, input, timeoutMs }, { a
|
|
|
342
389
|
}, timeoutMs);
|
|
343
390
|
};
|
|
344
391
|
// Inside a held slot, or when not queued at all, the reviewer starts at once.
|
|
345
|
-
if (runEnv.NODII_HEAVY_SLOT_HELD === "1" || file === command) start();
|
|
392
|
+
if (runEnv.NODII_HEAVY_SLOT || runEnv.NODII_HEAVY_SLOT_HELD === "1" || file === command) start();
|
|
346
393
|
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
|
347
394
|
child.stderr.on("data", (chunk) => {
|
|
348
395
|
stderr = (stderr + chunk).slice(-4000);
|
|
@@ -877,13 +924,16 @@ const errorCheck = (check, error, iterationCount, inputs) => ({ check, outcome:
|
|
|
877
924
|
* caller saves the round (saveLoop) once it is kept: still looping, or
|
|
878
925
|
* recorded; a run that records nothing leaves the loop where it was.
|
|
879
926
|
*/
|
|
880
|
-
export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now, exceptions = exceptionFiles, templates = codeConnectUnits }) {
|
|
927
|
+
export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now, exceptions = exceptionFiles, templates = codeConnectUnits, fullScript = "test" }) {
|
|
881
928
|
const critical = flags.critical === true;
|
|
882
929
|
const maxIterations = flags["max-iterations"] === undefined ? MAX_ITERATIONS : Number(flags["max-iterations"]);
|
|
883
930
|
if (!Number.isInteger(maxIterations) || maxIterations < 1 || maxIterations > 100)
|
|
884
931
|
throw new CliError("USAGE", "--max-iterations needs a whole number from 1 to 100.", 2);
|
|
885
932
|
const gates = [flags.gate ?? []].flat();
|
|
886
|
-
if (gates.some((x) => typeof x !== "string" || !x.trim())) throw new CliError("USAGE", "--gate needs a command, e.g. --gate '
|
|
933
|
+
if (gates.some((x) => typeof x !== "string" || !x.trim())) throw new CliError("USAGE", "--gate needs a command, e.g. --gate 'nodii-dev test affected --run'.", 2);
|
|
934
|
+
const whole = flags["full-suite"] === true ? [] : gates.filter((command) => fullSuiteGate(command, fullScript));
|
|
935
|
+
if (whole.length)
|
|
936
|
+
throw new CliError("GATE_FULL_SUITE", `Gate ${whole.map((command) => `\`${command}\``).join(", ")} runs the whole test suite. A lane runs only the tests its change reaches (MW2-20; hub-401): use --gate 'nodii-dev test affected --run', which also sizes the slot to the change. The full suite runs in the twice-daily CI and the release gate; pass --full-suite only when the change needs it (a release, or test infrastructure itself).`, 2, { gates: whole });
|
|
887
937
|
const changed = await gatesReceipt(gates, { cwd, current, store, diff, run: gate, ...(now ? { now } : {}) });
|
|
888
938
|
if (!changed.text.trim()) throw new CliError("LANE_DIFF_EMPTY", `${ref}: this worktree has no change against origin/main, so there is nothing to review.`, 1);
|
|
889
939
|
const runtime = lane.launch?.runtime === "codex" ? "codex" : "claude";
|