forgedock 1.60.1 → 1.61.1

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 (70) hide show
  1. package/bin/config-schema.mjs +44 -1
  2. package/bin/engine/runlog.mjs +52 -0
  3. package/bin/engine-cli.mjs +9 -4
  4. package/bin/env/bench.mjs +38 -0
  5. package/bin/env/cli.mjs +134 -0
  6. package/bin/env/env.mjs +339 -0
  7. package/bin/forgedock.mjs +32 -3
  8. package/bin/help-text.mjs +2 -0
  9. package/bin/lean/ci-budget.mjs +3 -1
  10. package/bin/lean/ci-classify.mjs +74 -0
  11. package/bin/lean/ci-classify.test.mjs +147 -0
  12. package/bin/lean/ci-emit.mjs +175 -0
  13. package/bin/lean/ci-emit.test.mjs +177 -0
  14. package/bin/lean/ci-preflight.mjs +183 -0
  15. package/bin/lean/ci-preflight.test.mjs +122 -0
  16. package/bin/lean/ci-runner-health.mjs +213 -0
  17. package/bin/lean/ci-runner-health.test.mjs +113 -0
  18. package/bin/lean/ci-watch.mjs +79 -0
  19. package/bin/lean/ci-watch.test.mjs +80 -0
  20. package/bin/lean/depcache.mjs +38 -8
  21. package/bin/lean/deploy-stages.mjs +514 -0
  22. package/bin/lean/deploy-stages.test.mjs +580 -0
  23. package/bin/lean/effects.mjs +50 -0
  24. package/bin/lean/execution.mjs +8 -1
  25. package/bin/lean/lean.mjs +38 -6
  26. package/bin/lean/lean.test.mjs +61 -0
  27. package/bin/lean/release-deploy.mjs +12 -6
  28. package/bin/lean/release-flakes.mjs +16 -0
  29. package/bin/lean/release-flakes.test.mjs +15 -0
  30. package/bin/lean/release-gates.mjs +24 -1
  31. package/bin/lean/release-ledger.mjs +21 -0
  32. package/bin/lean/release-minutes-timing.test.mjs +57 -0
  33. package/bin/lean/release-minutes.mjs +98 -0
  34. package/bin/lean/release-promote.mjs +444 -0
  35. package/bin/lean/release-promote.test.mjs +470 -0
  36. package/bin/lean/release-rollback.mjs +14 -6
  37. package/bin/lean/release.mjs +31 -2
  38. package/bin/lean/sandbox-remote.mjs +11 -3
  39. package/bin/lean/testengine-recall.mjs +82 -0
  40. package/bin/lean/testengine-recall.test.mjs +103 -0
  41. package/bin/lean/testengine-shard.mjs +150 -0
  42. package/bin/lean/testengine-shard.test.mjs +111 -0
  43. package/bin/lean/testengine.mjs +486 -0
  44. package/bin/lean/testengine.test.mjs +303 -0
  45. package/bin/lean/verify-settle.test.mjs +156 -0
  46. package/bin/lean/verify.mjs +98 -3
  47. package/bin/pool/agent.mjs +57 -6
  48. package/bin/pool/ci-events.mjs +189 -0
  49. package/bin/pool/ci-events.test.mjs +143 -0
  50. package/bin/pool/docker.mjs +7 -0
  51. package/bin/pool/lane-tools.mjs +1 -0
  52. package/bin/pool/router.mjs +25 -1
  53. package/bin/pool/warm.mjs +1 -1
  54. package/bin/stats/ci-awareness.mjs +66 -0
  55. package/bin/stats/index.mjs +44 -3
  56. package/bin/stats/release-ledger.test.mjs +226 -0
  57. package/bin/stats/release.mjs +365 -1
  58. package/bin/stats/stats.test.mjs +36 -0
  59. package/docs/CI.md +31 -0
  60. package/docs/CONFIG.md +235 -2
  61. package/docs/ENV-LIBRARY.md +172 -0
  62. package/docs/STATS.md +43 -0
  63. package/docs/ci-events.md +88 -0
  64. package/docs/test-engine.md +98 -0
  65. package/package.json +1 -1
  66. package/pool/README.md +1 -0
  67. package/pool/image/entrypoint.sh +15 -3
  68. package/pool/services/docker-compose.yml +53 -0
  69. package/pool/services/git-mirror.sh +22 -0
  70. package/templates/github-actions/forge-env/action.yml +65 -0
@@ -0,0 +1,486 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Test engine (#5710, Forge CI W3): affected-test selection and the `forgedock tests select|shard|recall` CLI.
5
+ * - Selection: changed files -> test files. JS/TS by a static import/require graph, Python by module imports (plus
6
+ * `conftest.py`), quoted repo paths, `ci.tests.suites` path -> suite globs as the declared fallback. A lockfile, manifest or CI-file change,
7
+ * and any changed file nothing maps, select everything. Every selected test carries a reason.
8
+ * - Modes (`ci.tests.selection`): off (default: nothing is computed) | shadow (selection recorded, full suite runs) |
9
+ * enforce (refused, stays shadow, until the recall ledger graduated; `testengine-recall.mjs`). Scheduled runs and
10
+ * release branches always run the full suite.
11
+ * - Config: the one-level forge.yaml parser flattens `ci.tests.*` under `ci`, so the key names are unique within `ci`.
12
+ * Pure functions over injected `files` / `read`; only the CLI touches git and the filesystem. No network, no model call.
13
+ */
14
+ import { createHash } from "node:crypto";
15
+ import { execFileSync } from "node:child_process";
16
+ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
17
+ import { homedir } from "node:os";
18
+ import { join, posix } from "node:path";
19
+ import { parseForgeYaml } from "../forge-utils.mjs";
20
+
21
+ export const ENGINE_VERSION = 1;
22
+ export const SELECTION_MODES = ["off", "shadow", "enforce"];
23
+ export const QUARANTINE_MODES = ["off", "report", "non-blocking"];
24
+ /** Changes that select everything: dependency manifests and lockfiles, toolchain and test-runner config, CI files. */
25
+ export const RUN_ALL_DEFAULT = [
26
+ "package.json", "package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "yarn.lock", ".npmrc", ".yarnrc*", "bun.lock*",
27
+ "pyproject.toml", "poetry.lock", "uv.lock", "Pipfile", "Pipfile.lock", "requirements*.txt", "constraints*.txt", "setup.py", "setup.cfg", "tox.ini", "noxfile.py", "pytest.ini",
28
+ "go.mod", "go.sum", "Cargo.toml", "Cargo.lock",
29
+ "tsconfig*.json", "jsconfig*.json", "babel.config.*", ".babelrc*", "jest.config.*", "vitest.config.*", "vitest.workspace.*", "playwright.config.*", ".mocharc*",
30
+ ".nvmrc", ".node-version", ".python-version", ".tool-versions",
31
+ ".github/**", "forge.yaml", ".forge/**", "Dockerfile*", "docker-compose*.y*ml", "compose*.y*ml", "Makefile", "GNUmakefile", ".env*",
32
+ ];
33
+ export const FULL_BRANCHES_DEFAULT = ["main", "master", "release/**"];
34
+
35
+ const str = (v) => (v == null ? "" : String(v)).trim();
36
+ const list = (v) => (Array.isArray(v) ? v : str(v) ? [str(v)] : []).map(str).filter(Boolean);
37
+ const posInt = (v, d) => { const n = Number(str(v)); return Number.isInteger(n) && n > 0 ? n : d; };
38
+ const nonNeg = (v, d) => { const n = Number(str(v)); return str(v) !== "" && Number.isInteger(n) && n >= 0 ? n : d; };
39
+ const uniq = (a) => [...new Set(a)];
40
+
41
+ /** A glob as an anchored RegExp: `*` within a segment, `**` across segments (`**​/` also matches no directory), `?` one character. */
42
+ export function globRe(glob) {
43
+ const g = String(glob);
44
+ let re = "";
45
+ for (let i = 0; i < g.length; i++) {
46
+ const c = g[i];
47
+ if (c === "*" && g[i + 1] === "*") { if (g[i + 2] === "/") { re += "(?:.*/)?"; i += 2; } else { re += ".*"; i++; } }
48
+ else if (c === "*") re += "[^/]*";
49
+ else if (c === "?") re += "[^/]";
50
+ else re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
51
+ }
52
+ return new RegExp(`^${re}$`);
53
+ }
54
+ /** True when `path` matches `glob`; a glob without `/` is matched against the basename (so `package.json` matches in any directory). */
55
+ export const matchGlob = (path, glob) => globRe(glob).test(String(glob).includes("/") ? path : posix.basename(path));
56
+ const firstGlob = (path, globs) => globs.find((g) => matchGlob(path, g));
57
+
58
+ /** One `ci.tests.suites` entry `"<glob> [<glob>...] => <target> [<target>...]"`; a target is a test-file glob, `@name` or `*`. */
59
+ export function parseSuiteRule(entry) {
60
+ const [l, r, extra] = str(entry).split("=>");
61
+ const when = str(l).split(/\s+/).filter(Boolean), targets = str(r).split(/\s+/).filter(Boolean);
62
+ return extra === undefined && when.length && targets.length ? { when, targets } : null;
63
+ }
64
+
65
+ /** forge.yaml `ci` section (flattened `ci.tests.*`) -> the engine config; junk keeps the defaults, and the default is off. */
66
+ export function parseTestsConfig(ci) {
67
+ const s = ci && typeof ci === "object" ? ci : {};
68
+ const pick = (v, allowed, d) => (allowed.includes(str(v)) ? str(v) : d);
69
+ const rules = list(s.suites).map(parseSuiteRule);
70
+ return {
71
+ selection: pick(s.selection, SELECTION_MODES, "off"),
72
+ suites: rules.filter(Boolean),
73
+ badSuites: list(s.suites).filter((_, i) => !rules[i]),
74
+ runAll: [...RUN_ALL_DEFAULT, ...list(s.run_all)],
75
+ ignore: list(s.ignore),
76
+ testGlobs: list(s.test_globs),
77
+ fullBranches: s.full_branches === undefined ? FULL_BRANCHES_DEFAULT : list(s.full_branches),
78
+ graduateAfter: posInt(s.graduate_after, 50),
79
+ graduateMinFailing: nonNeg(s.graduate_min_failing, 1),
80
+ shards: posInt(s.shards, 0),
81
+ shardTargetS: posInt(s.shard_target_s, 0),
82
+ quarantine: pick(s.quarantine, QUARANTINE_MODES, "report"),
83
+ quarantineAfter: posInt(s.quarantine_after, 3),
84
+ quarantineWindowDays: posInt(s.quarantine_window_days, 14),
85
+ ledger: str(s.recall_ledger),
86
+ };
87
+ }
88
+ export function readTestsConfig(cwd = process.cwd()) {
89
+ try { return parseTestsConfig(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.ci); } catch { return parseTestsConfig(null); }
90
+ }
91
+ /** Identity of everything that decides a selection: a change restarts the graduation count. */
92
+ export const configHash = (cfg) => createHash("sha256")
93
+ .update(JSON.stringify([ENGINE_VERSION, cfg.suites, cfg.runAll, cfg.ignore, cfg.testGlobs])).digest("hex").slice(0, 12);
94
+
95
+ // ---- ecosystems --------------------------------------------------------------------------------------------------------
96
+ const JS_EXT = [".js", ".mjs", ".cjs", ".jsx", ".ts", ".mts", ".cts", ".tsx"];
97
+ const JS_RE = /\.[cm]?[jt]sx?$/;
98
+ const JS_TEST_RE = /(^|\/)__tests__\/.*\.[cm]?[jt]sx?$|\.(test|spec)\.[cm]?[jt]sx?$/;
99
+ const PY_TEST_RE = /(^|\/)(test_[^/]*|[^/]*_test)\.py$/;
100
+ export const ecosystemOf = (f) => (JS_RE.test(f) && !f.endsWith(".d.ts") ? "js" : f.endsWith(".py") ? "python" : "other");
101
+ /** Test files of `files`: `ci.tests.test_globs` when set, else the JS (`*.test.*`, `*.spec.*`, `__tests__/`) and pytest (`test_*.py`, `*_test.py`) conventions. */
102
+ export function testFilesOf(files, cfg = {}) {
103
+ const globs = cfg.testGlobs ?? [];
104
+ return files.filter((f) => (globs.length ? globs.some((g) => matchGlob(f, g)) : JS_TEST_RE.test(f) || PY_TEST_RE.test(f))).sort();
105
+ }
106
+
107
+ const JS_SPEC_RES = [
108
+ /\bimport\s+(?:[^'"()]*?\s+from\s+)?["']([^"'\n]+)["']/g,
109
+ /\bexport\s+[^'";]*?\s+from\s+["']([^"'\n]+)["']/g,
110
+ /\b(?:require|import|require\.resolve|jest\.(?:mock|doMock|requireActual)|vi\.(?:mock|doMock|importActual))\s*\(\s*["'`]([^"'`\n]+)["'`]/g,
111
+ /\bnew\s+URL\(\s*["'`](\.{1,2}\/[^"'`\n]+)["'`]\s*,\s*import\.meta\.url/g,
112
+ ];
113
+ const JS_DYNAMIC_RE = /\b(?:require|import)\s*\(\s*(?:[A-Za-z_$]|`[^`]*\$\{)/;
114
+ const PATH_LITERAL_RE = /["'`]((?:\.{1,2}\/)?[\w@.-]+(?:\/[\w@.-]+)+)["'`]/g;
115
+ /** Literal module specifiers of a JS/TS source (imports, re-exports, require, dynamic import, mocks, `new URL(rel, import.meta.url)`). */
116
+ export function jsSpecifiers(src) {
117
+ const out = [];
118
+ for (const re of JS_SPEC_RES) for (const m of String(src).matchAll(re)) if (!m[1].includes("${")) out.push(m[1]);
119
+ return uniq(out);
120
+ }
121
+
122
+ /** The file a path-like import base names: itself, with an extension, a TS source behind a `.js` specifier, or a directory index. */
123
+ function tryFile(base, has) {
124
+ const b = base.replace(/[?#].*$/, "").replace(/\/+$/, "");
125
+ if (!b || b.startsWith("..")) return null;
126
+ if (has(b)) return b;
127
+ for (const e of JS_EXT) if (has(b + e)) return b + e;
128
+ const swap = /\.([cm]?)jsx?$/.exec(b);
129
+ if (swap) for (const e of [`.${swap[1]}ts`, ".tsx", ".ts"]) { const c = b.slice(0, swap.index) + e; if (has(c)) return c; }
130
+ for (const e of JS_EXT) if (has(`${b}/index${e}`)) return `${b}/index${e}`;
131
+ return null;
132
+ }
133
+ const lenientJson = (text) => {
134
+ try { return JSON.parse(String(text)); } catch { /* tsconfig allows comments and trailing commas */ }
135
+ try { return JSON.parse(String(text).replace(/\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm, "").replace(/,(\s*[}\]])/g, "$1")); } catch { return null; }
136
+ };
137
+ const dirOf = (f) => (posix.dirname(f) === "." ? "" : posix.dirname(f));
138
+ const under = (f, dir) => dir === "" || f.startsWith(`${dir}/`);
139
+ const pj = (...p) => posix.normalize(p.filter((x) => x !== "").join("/") || ".").replace(/^\.$/, "");
140
+
141
+ /** Workspace packages (`name` -> dir, entry) and tsconfig/jsconfig `baseUrl` + `paths` aliases, read from the repo's own files. */
142
+ function jsResolvers(files, read) {
143
+ const packages = [], aliases = [];
144
+ for (const f of files) {
145
+ const base = posix.basename(f);
146
+ if (base === "package.json" && !f.includes("node_modules/")) {
147
+ const p = lenientJson(read(f) ?? "");
148
+ if (p && typeof p.name === "string") packages.push({ name: p.name, dir: dirOf(f), main: [p.source, p.module, p.main, typeof p.exports === "string" ? p.exports : p.exports?.["."]?.import ?? p.exports?.["."]?.default ?? (typeof p.exports?.["."] === "string" ? p.exports["."] : null)].filter((x) => typeof x === "string") });
149
+ } else if (/^[tj]sconfig(\..+)?\.json$/.test(base)) {
150
+ const co = lenientJson(read(f) ?? "")?.compilerOptions;
151
+ if (!co || typeof co !== "object") continue;
152
+ const root = pj(dirOf(f), str(co.baseUrl) || ".");
153
+ const paths = Object.entries(co.paths && typeof co.paths === "object" ? co.paths : {}).map(([k, v]) => ({ key: k, targets: list(v) }));
154
+ aliases.push({ dir: dirOf(f), root, paths, baseUrl: co.baseUrl !== undefined });
155
+ }
156
+ }
157
+ packages.sort((a, b) => b.name.length - a.name.length);
158
+ aliases.sort((a, b) => b.dir.length - a.dir.length);
159
+ return { packages, aliases };
160
+ }
161
+
162
+ /** Repo files a JS specifier of `from` resolves to ([] for an external package). */
163
+ function resolveJs(spec, from, { has, files, packages, aliases }) {
164
+ if (spec.startsWith(".")) { const r = tryFile(pj(dirOf(from), spec), has); return r ? [r] : []; }
165
+ if (spec.startsWith("/") || /^[a-z]+:/i.test(spec)) return [];
166
+ for (const a of aliases) {
167
+ if (!under(from, a.dir)) continue;
168
+ for (const p of a.paths) {
169
+ const star = p.key.indexOf("*");
170
+ const hit = star < 0 ? spec === p.key : spec.startsWith(p.key.slice(0, star)) && spec.endsWith(p.key.slice(star + 1));
171
+ if (!hit) continue;
172
+ const mid = star < 0 ? "" : spec.slice(star, spec.length - (p.key.length - star - 1));
173
+ for (const t of p.targets) { const r = tryFile(pj(a.root, t.split("*").join(mid)), has); if (r) return [r]; }
174
+ }
175
+ if (a.baseUrl) { const r = tryFile(pj(a.root, spec), has); if (r) return [r]; }
176
+ }
177
+ const pkg = packages.find((p) => spec === p.name || spec.startsWith(`${p.name}/`));
178
+ if (!pkg) return [];
179
+ const sub = spec.slice(pkg.name.length + 1);
180
+ const tries = sub ? [pj(pkg.dir, sub), pj(pkg.dir, "src", sub)] : [...pkg.main.map((m) => pj(pkg.dir, m)), pj(pkg.dir, "src/index"), pj(pkg.dir, "index")];
181
+ for (const t of tries) { const r = tryFile(t, has); if (r) return [r]; }
182
+ // A workspace package whose entry cannot be found statically: depend on every source file of it (over-approximation, never under).
183
+ return files.filter((f) => under(f, pkg.dir) && ecosystemOf(f) === "js" && !JS_TEST_RE.test(f));
184
+ }
185
+
186
+ /** Imported module names of a Python source: [{level, module, names}] (`level` = leading dots of a relative import). */
187
+ export function pyImports(src) {
188
+ const out = [], text = String(src);
189
+ for (const m of text.matchAll(/^[ \t]*from[ \t]+(\.*)([\w.]*)[ \t]+import[ \t]+(\([^)]*\)|[^\n]*)/gm)) {
190
+ const names = m[3].replace(/[()\\]/g, " ").replace(/#.*$/gm, "").split(",").map((n) => n.trim().split(/\s+as\s+/)[0].trim()).filter((n) => /^\w+$/.test(n));
191
+ out.push({ level: m[1].length, module: m[2], names });
192
+ }
193
+ for (const m of text.matchAll(/^[ \t]*import[ \t]+([\w., \t]+)/gm)) for (const part of m[1].split(",")) {
194
+ const name = part.trim().split(/\s+as\s+/)[0].trim();
195
+ if (/^[\w.]+$/.test(name)) out.push({ level: 0, module: name, names: [] });
196
+ }
197
+ // String references that import at run time: importlib, __import__, mock.patch targets, pytest_plugins.
198
+ for (const m of text.matchAll(/\b(?:import_module|__import__|patch(?:\.object)?)\(\s*["']([A-Za-z_][\w.]*)["']/g)) out.push({ level: 0, module: m[1], names: [] });
199
+ for (const m of text.matchAll(/^pytest_plugins\s*=\s*(.+)$/gm)) for (const s of m[1].matchAll(/["']([A-Za-z_][\w.]*)["']/g)) out.push({ level: 0, module: s[1], names: [] });
200
+ return out;
201
+ }
202
+
203
+ /** Files a dotted module name resolves to under `base`: the longest prefix that is a module or package, plus the `__init__.py` of its parents. */
204
+ function resolvePy(base, dotted, has) {
205
+ const parts = dotted.split(".").filter(Boolean);
206
+ for (let k = parts.length; k >= 1; k--) {
207
+ const p = pj(base, parts.slice(0, k).join("/"));
208
+ const hit = has(`${p}.py`) ? `${p}.py` : has(`${p}/__init__.py`) ? `${p}/__init__.py` : null;
209
+ if (!hit) continue;
210
+ const out = [hit];
211
+ for (let j = 1; j < k; j++) { const init = `${pj(base, parts.slice(0, j).join("/"))}/__init__.py`; if (has(init)) out.push(init); }
212
+ return out;
213
+ }
214
+ return [];
215
+ }
216
+ const ancestors = (dir) => { const out = [dir]; let d = dir; while (d !== "") { d = dirOf(d); out.push(d); } return out; };
217
+
218
+ /**
219
+ * Static dependency graph of the repo's JS/TS and Python files.
220
+ * @param {{files: string[], read: (path: string) => string|null}} p repo-relative posix paths and a reader (null = unreadable)
221
+ * @returns {{deps: Map<string, Set<string>>, dynamic: string[]}} `dynamic` = files with a computed import the graph cannot follow
222
+ */
223
+ export function buildGraph({ files, read }) {
224
+ const set = new Set(files), has = (f) => set.has(f);
225
+ const deps = new Map(), dynamic = [];
226
+ const add = (from, to) => { if (to && to !== from) (deps.get(from) ?? deps.set(from, new Set()).get(from)).add(to); };
227
+ const js = { has, files, ...jsResolvers(files, read) };
228
+ const pyRoots = uniq(["", "src", ...files.filter((f) => /^(pyproject\.toml|setup\.(py|cfg)|requirements[^/]*\.txt)$/.test(posix.basename(f))).flatMap((f) => [dirOf(f), pj(dirOf(f), "src")])]);
229
+ for (const f of files) {
230
+ const eco = ecosystemOf(f);
231
+ if (eco === "other") continue;
232
+ const src = read(f);
233
+ if (src == null) continue;
234
+ // A quoted repo path (root-relative or relative to the file) is a dependency too: tests that read a doc, fixture or script by path.
235
+ for (const m of src.matchAll(PATH_LITERAL_RE)) { const lit = m[1].replace(/^\.\//, ""); add(f, has(lit) ? lit : has(pj(dirOf(f), lit)) ? pj(dirOf(f), lit) : null); }
236
+ if (eco === "js") {
237
+ if (JS_DYNAMIC_RE.test(src)) dynamic.push(f);
238
+ for (const spec of jsSpecifiers(src)) for (const to of resolveJs(spec, f, js)) add(f, to);
239
+ continue;
240
+ }
241
+ const here = ancestors(dirOf(f));
242
+ const bases = uniq([...here, ...here.map((d) => pj(d, "src")), ...pyRoots]);
243
+ for (const imp of pyImports(src)) {
244
+ const targets = imp.names.length ? [...imp.names.map((n) => [imp.module, n].filter(Boolean).join(".")), imp.module].filter(Boolean) : [imp.module];
245
+ if (imp.level > 0) {
246
+ let pkg = dirOf(f);
247
+ for (let i = 1; i < imp.level; i++) pkg = dirOf(pkg);
248
+ if (has(`${pkg}/__init__.py`.replace(/^\//, ""))) add(f, `${pkg}/__init__.py`.replace(/^\//, ""));
249
+ for (const t of targets) for (const to of resolvePy(pkg, t, has)) add(f, to);
250
+ } else for (const t of targets) for (const b of bases) { const r = resolvePy(b, t, has); if (r.length) { r.forEach((to) => add(f, to)); break; } }
251
+ }
252
+ if (/\b(?:import_module|__import__)\(\s*[A-Za-z_]/.test(src)) dynamic.push(f);
253
+ // pytest loads every conftest.py from the rootdir down to the test file's directory.
254
+ if (PY_TEST_RE.test(f) || posix.basename(f) === "conftest.py") for (const d of here) add(f, pj(d, "conftest.py") === f ? null : has(pj(d, "conftest.py")) ? pj(d, "conftest.py") : null);
255
+ }
256
+ return { deps, dynamic };
257
+ }
258
+
259
+ /**
260
+ * Tests a change can affect.
261
+ * @param {{files: string[], changed: string[], read: Function, cfg: object}} p
262
+ * @returns {{mode: "all"|"subset"|"none", tests: string[], suites: string[], total: number, reasons: Record<string, string[]>,
263
+ * run_all: {file: string, why: string}[], ignored: string[], warnings: string[], by_ecosystem: Record<string, string[]>}}
264
+ */
265
+ export function selectTests({ files, changed, read, cfg }) {
266
+ const all = testFilesOf(files, cfg), isTest = new Set(all), set = new Set(files);
267
+ const { deps, dynamic } = buildGraph({ files, read });
268
+ const rdeps = new Map();
269
+ for (const [from, tos] of deps) for (const to of tos) (rdeps.get(to) ?? rdeps.set(to, []).get(to)).push(from);
270
+ const picked = new Map(), suites = new Set(), runAll = [], ignored = [], warnings = [];
271
+ const pick = (t, why) => { const r = picked.get(t) ?? picked.set(t, []).get(t); if (r.length < 3 && !r.includes(why)) r.push(why); };
272
+ const changes = uniq((changed ?? []).map((c) => str(c).replace(/^\.\//, "")).filter(Boolean));
273
+ if (!changes.length) runAll.push({ file: "", why: "no changed files were given (unknown diff)" });
274
+ for (const c of changes) {
275
+ if (firstGlob(c, cfg.ignore ?? [])) { ignored.push(c); continue; }
276
+ const trigger = firstGlob(c, cfg.runAll ?? RUN_ALL_DEFAULT);
277
+ if (trigger) { runAll.push({ file: c, why: `matches run-everything glob ${trigger}` }); continue; }
278
+ let mapped = false;
279
+ for (const rule of cfg.suites ?? []) {
280
+ const when = firstGlob(c, rule.when);
281
+ if (!when) continue;
282
+ mapped = true;
283
+ for (const t of rule.targets) {
284
+ if (t === "*") runAll.push({ file: c, why: `ci.tests.suites maps ${when} to everything` });
285
+ else if (t.startsWith("@")) suites.add(t);
286
+ else {
287
+ const hits = all.filter((f) => matchGlob(f, t));
288
+ if (!hits.length) warnings.push(`ci.tests.suites target ${t} (for ${when}) matches no test file`);
289
+ for (const h of hits) pick(h, `${c} matches ${when} => ${t}`);
290
+ }
291
+ }
292
+ }
293
+ if (isTest.has(c)) { pick(c, "changed test file"); mapped = true; }
294
+ else if (!set.has(c) && (cfg.testGlobs?.length ? cfg.testGlobs.some((g) => matchGlob(c, g)) : JS_TEST_RE.test(c) || PY_TEST_RE.test(c))) mapped = true; // a deleted test file
295
+ // Reverse reachability: every test that (transitively) imports the changed file.
296
+ const via = new Map([[c, null]]), queue = [c];
297
+ for (let i = 0; i < queue.length; i++) for (const up of rdeps.get(queue[i]) ?? []) if (!via.has(up)) { via.set(up, queue[i]); queue.push(up); }
298
+ for (const f of queue.slice(1)) {
299
+ if (!isTest.has(f)) continue;
300
+ mapped = true;
301
+ pick(f, via.get(f) === c ? `depends on ${c}` : `reaches ${c} through ${via.get(f)}`);
302
+ }
303
+ if (!mapped) runAll.push({ file: c, why: set.has(c) ? "no test imports it and no ci.tests.suites glob maps it" : "deleted or unknown file that no ci.tests.suites glob maps" });
304
+ }
305
+ const hitDynamic = dynamic.filter((f) => !isTest.has(f)).length;
306
+ if (hitDynamic) warnings.push(`${hitDynamic} file(s) use a computed import the static graph cannot follow (shadow recall measures the effect)`);
307
+ for (const b of cfg.badSuites ?? []) warnings.push(`ci.tests.suites entry ignored (want "<glob> ... => <target> ..."): ${b}`);
308
+ const tests = runAll.length ? all : [...picked.keys()].sort();
309
+ const mode = runAll.length ? "all" : tests.length || suites.size ? "subset" : "none";
310
+ const reasons = Object.fromEntries([...picked.entries()].sort(([a], [b]) => (a < b ? -1 : 1)));
311
+ const by = {};
312
+ for (const t of tests) (by[ecosystemOf(t)] ??= []).push(t);
313
+ return { mode, tests, suites: [...suites].sort(), total: all.length, reasons, run_all: runAll, ignored, warnings, by_ecosystem: by };
314
+ }
315
+
316
+ /** Why this run must be the full suite whatever the mode: `--full`, a scheduled (nightly) run, or a release branch. */
317
+ export function fullReason({ flag = false, event = "", ref = "", baseRef = "", cfg }) {
318
+ if (flag) return "--full was passed";
319
+ if (event === "schedule") return "scheduled run: the full suite always runs nightly";
320
+ const branch = [baseRef, ref.replace(/^refs\/heads\//, "")].map(str).find((b) => b && (cfg.fullBranches ?? []).some((g) => globRe(g).test(b)));
321
+ return branch ? `release branch ${branch}: the full suite always runs on the release commit` : null;
322
+ }
323
+
324
+ /**
325
+ * What actually runs. Skipping is allowed only when enforce is configured, the ledger graduated and nothing forces a full run.
326
+ * @returns {{configured, effective, run: "all"|"selection", why: string, refused?: string}}
327
+ */
328
+ export function planRun({ cfg, selection, graduation, full = null }) {
329
+ const configured = cfg.selection;
330
+ if (configured === "off") return { configured, effective: "off", run: "all", why: "ci.tests.selection is off" };
331
+ if (configured === "enforce" && !graduation?.graduated) {
332
+ const refused = `ci.tests.selection: enforce refused: ${graduation?.why ?? "no recall ledger"}`;
333
+ return { configured, effective: "shadow", run: "all", why: refused, refused };
334
+ }
335
+ if (configured === "shadow") return { configured, effective: "shadow", run: "all", why: "shadow: the selection is recorded, the full suite runs" };
336
+ if (full) return { configured, effective: "enforce", run: "all", why: full };
337
+ if (selection.mode === "all") return { configured, effective: "enforce", run: "all", why: selection.run_all[0]?.why ?? "everything is selected" };
338
+ return { configured, effective: "enforce", run: "selection", why: `graduated: ${selection.tests.length} of ${selection.total} test file(s) selected` };
339
+ }
340
+
341
+ // ---- CLI ---------------------------------------------------------------------------------------------------------------
342
+ export const TESTS_USAGE = [
343
+ "usage: forgedock tests select [--base <ref>] [--head <ref>] [--changed <file>]... [--changed-from <file|->] [--full] [--json] [--out <file>]",
344
+ " forgedock tests shard [--shards <n> | --target-seconds <s>] [--max-shards <n>] [--report <file>]... [--from <selection.json>] [--ecosystem js|python] [--json | --matrix]",
345
+ " forgedock tests recall record --selection <selection.json> [--report <file>]... [--failed <test>]... [--sha <sha>] [--run-id <id>]",
346
+ " forgedock tests recall [status] [--json] | recall check",
347
+ " common: [--ledger <file>]",
348
+ ].join("\n");
349
+
350
+ const flagVals = (argv, name) => argv.flatMap((a, i) => (a === name && argv[i + 1] !== undefined ? [argv[i + 1]] : []));
351
+ const flagVal = (argv, name) => flagVals(argv, name).at(-1);
352
+ function checkFlags(argv, valued, bare) {
353
+ for (let i = 0; i < argv.length; i++) {
354
+ if (valued.includes(argv[i])) { if (argv[i + 1] === undefined) throw new Error(`${argv[i]} needs a value\n${TESTS_USAGE}`); i++; }
355
+ else if (!bare.includes(argv[i])) throw new Error(`unknown argument ${argv[i]}\n${TESTS_USAGE}`);
356
+ }
357
+ }
358
+ const git = (cwd, args) => execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
359
+ const MAX_SOURCE_BYTES = 1024 * 1024;
360
+
361
+ /** Repo facts for the CLI: tracked + untracked-unignored files, and a size-capped reader. */
362
+ export function repoInputs(cwd) {
363
+ const files = git(cwd, ["-c", "core.quotepath=off", "ls-files", "-z", "--cached", "--others", "--exclude-standard"]).split("\0").filter(Boolean)
364
+ .filter((f) => existsSync(join(cwd, f)));
365
+ const read = (f) => { try { const p = join(cwd, f); return statSync(p).size > MAX_SOURCE_BYTES ? null : readFileSync(p, "utf8"); } catch { return null; } };
366
+ return { files, read };
367
+ }
368
+ /** Default ledger file: outside the checkout, so a change under test cannot edit its own recall record. */
369
+ export function ledgerPath({ cwd, cfg, flag, env = process.env }) {
370
+ if (flag) return flag;
371
+ if (cfg.ledger) return cfg.ledger;
372
+ if (env.FORGEDOCK_TESTS_LEDGER) return env.FORGEDOCK_TESTS_LEDGER;
373
+ let slug = "";
374
+ try { slug = /[:/]([^/:]+\/[^/]+?)(?:\.git)?\s*$/.exec(git(cwd, ["remote", "get-url", "origin"]))?.[1].replace("/", "__") ?? ""; } catch { /* no remote */ }
375
+ return join(env.FORGEDOCK_TESTS_DIR || join(homedir(), ".forge", "tests"), slug || createHash("sha1").update(cwd).digest("hex").slice(0, 12), "recall.jsonl");
376
+ }
377
+
378
+ async function selectFromCli(argv, { out, cwd, env, now, stdin }) {
379
+ checkFlags(argv, ["--base", "--head", "--changed", "--changed-from", "--out", "--ledger", "--event", "--ref", "--base-ref"], ["--full", "--json"]);
380
+ const cfg = readTestsConfig(cwd);
381
+ const emit = (res) => {
382
+ if (flagVal(argv, "--out")) writeFileSync(flagVal(argv, "--out"), `${JSON.stringify(res, null, 2)}\n`);
383
+ if (argv.includes("--json")) { out(JSON.stringify(res, null, 2)); return 0; }
384
+ out(`tests: selection ${res.plan.configured}${res.plan.configured !== res.plan.effective ? ` -> ${res.plan.effective}` : ""}; run ${res.plan.run} (${res.plan.why})`);
385
+ if (!res.selection) return 0;
386
+ const s = res.selection;
387
+ out(`selected: ${s.mode === "all" ? `all ${s.total}` : `${s.tests.length} of ${s.total}`} test file(s)${s.suites.length ? `, suites ${s.suites.join(" ")}` : ""}`);
388
+ for (const r of s.run_all) out(` everything: ${r.file ? `${r.file}: ` : ""}${r.why}`);
389
+ if (s.mode !== "all") for (const [t, why] of Object.entries(s.reasons)) out(` ${t}: ${why.join("; ")}`);
390
+ for (const f of s.ignored) out(` ignored: ${f}`);
391
+ for (const w of s.warnings) out(` warning: ${w}`);
392
+ for (const q of res.quarantined) out(` quarantined${q.blocking ? "" : " (non-blocking)"}: ${q.target} flaked ${q.count}x`);
393
+ if (res.graduation) out(`recall: ${res.graduation.why}`);
394
+ return 0;
395
+ };
396
+ if (cfg.selection === "off") return emit({ plan: planRun({ cfg }), selection: null, run_tests: null, quarantined: [], graduation: null });
397
+ let changed = flagVals(argv, "--changed");
398
+ const from = flagVal(argv, "--changed-from");
399
+ if (from) changed = [...changed, ...String(from === "-" ? await stdin() : readFileSync(from, "utf8")).split(/\r?\n|\0/)];
400
+ const base = flagVal(argv, "--base") ?? (env.GITHUB_BASE_REF ? `origin/${env.GITHUB_BASE_REF}` : null);
401
+ if (!changed.length && !from) {
402
+ if (!base) throw new Error(`tests select needs --base <ref>, --changed or --changed-from\n${TESTS_USAGE}`);
403
+ changed = git(cwd, ["-c", "core.quotepath=off", "diff", "--name-only", "-z", `${base}...${flagVal(argv, "--head") ?? "HEAD"}`]).split("\0");
404
+ }
405
+ const { files, read } = repoInputs(cwd);
406
+ const selection = selectTests({ files, changed, read, cfg });
407
+ const { readLedger, graduation: grad, quarantineFromLedger } = await import("./testengine-recall.mjs");
408
+ const entries = readLedger(ledgerPath({ cwd, cfg, flag: flagVal(argv, "--ledger"), env }));
409
+ const graduation = grad(entries, { after: cfg.graduateAfter, minFailing: cfg.graduateMinFailing, config: configHash(cfg) });
410
+ const full = fullReason({ flag: argv.includes("--full"), event: flagVal(argv, "--event") ?? env.GITHUB_EVENT_NAME ?? "", ref: flagVal(argv, "--ref") ?? env.GITHUB_REF ?? "", baseRef: flagVal(argv, "--base-ref") ?? env.GITHUB_BASE_REF ?? "", cfg });
411
+ const plan = planRun({ cfg, selection, graduation, full });
412
+ const run_tests = plan.run === "selection" ? selection.tests : testFilesOf(files, cfg);
413
+ return emit({ plan, config: configHash(cfg), selection, run_tests, run_suites: plan.run === "selection" ? selection.suites : null, quarantined: quarantineFromLedger(entries, cfg, now), graduation });
414
+ }
415
+
416
+ async function shardFromCli(argv, { out, cwd }) {
417
+ checkFlags(argv, ["--shards", "--target-seconds", "--max-shards", "--report", "--from", "--ecosystem"], ["--json", "--matrix"]);
418
+ const cfg = readTestsConfig(cwd);
419
+ const { parseReport, fileDurations, planShards } = await import("./testengine-shard.mjs");
420
+ const all = testFilesOf(repoInputs(cwd).files, cfg);
421
+ let files = all;
422
+ if (flagVal(argv, "--from")) {
423
+ const sel = JSON.parse(readFileSync(flagVal(argv, "--from"), "utf8"));
424
+ files = sel.run_tests ?? sel.selection?.tests ?? sel.tests ?? all;
425
+ }
426
+ const eco = flagVal(argv, "--ecosystem");
427
+ if (eco) files = files.filter((f) => ecosystemOf(f) === eco);
428
+ const durations = fileDurations(flagVals(argv, "--report").flatMap((r) => parseReport(readFileSync(r, "utf8"))), all);
429
+ const num = (name, d) => { const v = flagVal(argv, name); if (v === undefined) return d; if (!(Number(v) > 0)) throw new Error(`${name} must be a positive number`); return Number(v); };
430
+ const plan = planShards({ files, durations, shards: num("--shards", cfg.shards), targetS: num("--target-seconds", cfg.shardTargetS), maxShards: num("--max-shards", 0) });
431
+ if (argv.includes("--matrix")) { out(JSON.stringify(plan.matrix)); return 0; }
432
+ if (argv.includes("--json")) { out(JSON.stringify(plan, null, 2)); return 0; }
433
+ const timed = plan.source === "durations";
434
+ out(timed ? `shards: ${plan.shards.length} by durations; estimated longest ${plan.est_max_s} s of ${plan.est_total_s} s total (${plan.known} of ${files.length} file(s) have a recorded duration)`
435
+ : `shards: ${plan.shards.length} by file count (no recorded durations; pass --report <junit.xml|tap|json>)`);
436
+ for (const s of plan.shards) out(` shard ${s.index}/${plan.shards.length}: ${s.files.length} file(s)${timed ? `, ~${s.est_s} s` : ""}`);
437
+ for (const o of plan.oversize) out(` oversize: ${o.file} takes ~${o.s} s alone, over the ${plan.target_s} s target: no file split can shorten it`);
438
+ return 0;
439
+ }
440
+
441
+ async function recallFromCli(argv, { out, cwd, env, now }) {
442
+ const sub = argv[0] && !argv[0].startsWith("--") ? argv[0] : "status", rest = argv[0] === sub ? argv.slice(1) : argv;
443
+ if (!["record", "status", "check"].includes(sub)) throw new Error(`unknown tests recall subcommand ${sub}\n${TESTS_USAGE}`);
444
+ checkFlags(rest, ["--selection", "--report", "--failed", "--sha", "--run-id", "--ledger", "--event"], ["--json"]);
445
+ const cfg = readTestsConfig(cwd);
446
+ const R = await import("./testengine-recall.mjs");
447
+ const file = ledgerPath({ cwd, cfg, flag: flagVal(rest, "--ledger"), env });
448
+ if (sub === "record") {
449
+ if (cfg.selection === "off") { out("tests recall: ci.tests.selection is off; nothing recorded"); return 0; }
450
+ if (!flagVal(rest, "--selection")) throw new Error(`tests recall record needs --selection <selection.json>\n${TESTS_USAGE}`);
451
+ const sel = JSON.parse(readFileSync(flagVal(rest, "--selection"), "utf8"));
452
+ if (!sel.selection) { out("tests recall: the selection file has no selection (mode off); nothing recorded"); return 0; }
453
+ const { parseReport, failedFiles } = await import("./testengine-shard.mjs");
454
+ const known = testFilesOf(repoInputs(cwd).files, cfg);
455
+ const fromReports = failedFiles(flagVals(rest, "--report").flatMap((r) => parseReport(readFileSync(r, "utf8"))), known);
456
+ let sha = flagVal(rest, "--sha") ?? env.GITHUB_SHA;
457
+ if (!sha) try { sha = git(cwd, ["rev-parse", "HEAD"]).trim(); } catch { sha = ""; }
458
+ const entry = R.recallEntry({ selection: sel.selection, ran: sel.plan?.run ?? "all", config: sel.config ?? configHash(cfg), failed: [...fromReports.failed, ...flagVals(rest, "--failed")],
459
+ unattributed: fromReports.unattributed, sha, runId: flagVal(rest, "--run-id") ?? env.GITHUB_RUN_ID ?? null, event: flagVal(rest, "--event") ?? env.GITHUB_EVENT_NAME ?? null, now });
460
+ R.appendLedger(file, entry);
461
+ if (rest.includes("--json")) out(JSON.stringify(entry));
462
+ else out(`tests recall: ${entry.ok ? "ok" : "MISS"}: ${entry.failed.length} failing test file(s), ${entry.missed.length} outside the selection${entry.unattributed.length ? `, ${entry.unattributed.length} failure(s) without a file` : ""}${entry.missed.length ? `: ${entry.missed.join(" ")}` : ""}`);
463
+ return 0; // recording never fails the build: the full suite's own result is the gate
464
+ }
465
+ const entries = R.readLedger(file);
466
+ const g = R.graduation(entries, { after: cfg.graduateAfter, minFailing: cfg.graduateMinFailing, config: configHash(cfg) });
467
+ const quarantined = R.quarantineFromLedger(entries, cfg, now);
468
+ if (rest.includes("--json")) out(JSON.stringify({ ledger: file, selection: cfg.selection, runs: entries.length, graduation: g, quarantined }, null, 2));
469
+ else {
470
+ out(`ledger: ${file} (${entries.length} run(s)); ci.tests.selection: ${cfg.selection}`);
471
+ out(`recall: ${g.why}`);
472
+ if (g.last_miss) out(`last miss: ${g.last_miss.sha?.slice(0, 12) || "?"} at ${g.last_miss.at}: ${[...g.last_miss.missed, ...g.last_miss.unattributed.map((u) => `(no file) ${u}`)].join(" ")}`);
473
+ for (const q of quarantined) out(`quarantined${q.blocking ? "" : " (non-blocking)"}: ${q.target} flaked ${q.count}x in ${cfg.quarantineWindowDays} d: ${q.why}`);
474
+ }
475
+ return sub === "check" && !g.graduated ? 1 : 0;
476
+ }
477
+
478
+ /** `forgedock tests select|shard|recall`. */
479
+ export async function testsFromCli(argv, deps = {}) {
480
+ const ctx = { out: deps.out ?? ((l) => console.log(l)), cwd: deps.cwd ?? process.cwd(), env: deps.env ?? process.env, now: deps.now ?? Date.now(),
481
+ stdin: deps.stdin ?? (async () => { let s = ""; for await (const c of process.stdin) s += c; return s; }) };
482
+ if (argv[0] === "select") return selectFromCli(argv.slice(1), ctx);
483
+ if (argv[0] === "shard") return shardFromCli(argv.slice(1), ctx);
484
+ if (argv[0] === "recall") return recallFromCli(argv.slice(1), ctx);
485
+ throw new Error(TESTS_USAGE);
486
+ }