forgedock 1.60.1 → 1.61.0

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 +183 -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 +18 -0
  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,339 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Environment library: one snapshot of a repo's installed dependencies per (lockfiles + toolchain pins + lane_tools +
5
+ * base image), built once outside any job and consumed by lane sandboxes, CI jobs and deploy image builds.
6
+ *
7
+ * Key: a content hash, computable anywhere without running a tool. Ecosystem detection, the hashed files and the install
8
+ * commands are depcache's (`makeDepCache().describe`), so both modules agree on what "the dependencies" are.
9
+ *
10
+ * Local store (`<root>/<key>/`, root = FORGE_ENV_ROOT or ~/.forge/env):
11
+ * manifest.json {v, key, repo, ref, commit, prefix, ecosystems, trees, toolchain, lane_tools, image, platform, size_bytes, files, created}
12
+ * tree/<rel> the installed trees at their repo-relative paths (read-only files, never written again)
13
+ * ready/<id>/ staged hardlink copies of tree/, each claimed once by a lane with a directory rename
14
+ * last-used
15
+ * A lane claims a snapshot whose key equals its own: `rename(ready/<id>/<tree>, <worktree>/<tree>)` per tree, no per-file
16
+ * work. That needs the store on the worktree's filesystem (the pool mounts both from one cache volume); otherwise the
17
+ * trees are hardlinked, or copied across filesystems. Trees are built at one fixed prefix and the lane gets a symlink
18
+ * from that prefix to its worktree, so absolute paths baked into them (bin shims, venv shebangs, editable installs) stay
19
+ * valid and nothing is rewritten or repaired.
20
+ *
21
+ * OCI store: the same key tags an image built from a generated Dockerfile (base image + lane_tools + frozen installs at
22
+ * the prefix). CI jobs run in it; deploy images use it as their dependency layer.
23
+ */
24
+ import * as nodeFs from "node:fs";
25
+ import { createHash } from "node:crypto";
26
+ import { homedir } from "node:os";
27
+ import { dirname, join } from "node:path";
28
+ import { scanKeys } from "../config-schema.mjs";
29
+ import { depCommands } from "../lean/depcache.mjs";
30
+ import { checkRecipes, laneToolsDockerfile, validateLaneTools } from "../pool/lane-tools.mjs";
31
+
32
+ export const ENV_PREFIX = "/work/env";
33
+ export const ENV_DEFAULTS = Object.freeze({ store: "local", keep: 3, maxAgeDays: 14, ready: 2 });
34
+ export const envRoot = (env = process.env) => String(env.FORGE_ENV_ROOT ?? "").trim() || join(homedir(), ".forge", "env");
35
+ /** Toolchain pin files: their content is part of the key (package.json `packageManager`/`engines` are hashed with the manifests). */
36
+ export const PIN_FILES = [".nvmrc", ".node-version", ".python-version", ".tool-versions", ".go-version", "rust-toolchain", "rust-toolchain.toml"];
37
+ const KEY_RE = /^[0-9a-f]{16}$/;
38
+ const sha = (buf) => createHash("sha256").update(buf).digest("hex");
39
+
40
+ /** forge.yaml `env.snapshots` and `env.proxies`. Absent or `enabled: false` is off. Pure. */
41
+ export function readEnvSnapshots(text) {
42
+ const keys = scanKeys(String(text ?? ""));
43
+ const get = (k) => { const n = keys.get(k); return n && n.kind === "scalar" ? n.value.replace(/^["']|["']$/g, "").trim() : ""; };
44
+ const int = (k, def, min) => { const v = get(k); return /^\d+$/.test(v) && Number(v) >= min ? Number(v) : def; };
45
+ const proxies = {};
46
+ for (const p of ["npm", "pypi", "apt", "git"]) { const v = get(`env.proxies.${p}`); if (/^(https?|git):\/\/[^\s"'`$;&|<>\\]+$/.test(v)) proxies[p] = v.replace(/\/+$/, ""); }
47
+ return {
48
+ enabled: get("env.snapshots.enabled") === "true",
49
+ store: get("env.snapshots.store") === "oci" ? "oci" : ENV_DEFAULTS.store,
50
+ keep: int("env.snapshots.keep", ENV_DEFAULTS.keep, 1),
51
+ maxAgeDays: int("env.snapshots.max_age_days", ENV_DEFAULTS.maxAgeDays, 1),
52
+ ready: int("env.snapshots.ready", ENV_DEFAULTS.ready, 0),
53
+ baseImage: get("env.snapshots.base_image") || null,
54
+ image: get("env.snapshots.image") || null,
55
+ proxies,
56
+ };
57
+ }
58
+
59
+ /** Env vars that point package managers at the opt-in caching proxies (pool/services). {} when none is set. Pure. */
60
+ export function proxyEnv(proxies = {}) {
61
+ const out = {};
62
+ const host = (u) => { try { return new URL(u).hostname; } catch { return ""; } };
63
+ if (proxies.npm) Object.assign(out, { npm_config_registry: `${proxies.npm}/`, YARN_NPM_REGISTRY_SERVER: proxies.npm, ...(proxies.npm.startsWith("http://") ? { YARN_UNSAFE_HTTP_WHITELIST: host(proxies.npm) } : {}) });
64
+ if (proxies.pypi) Object.assign(out, { PIP_INDEX_URL: proxies.pypi, UV_DEFAULT_INDEX: proxies.pypi, UV_INDEX_URL: proxies.pypi, ...(proxies.pypi.startsWith("http://") ? { PIP_TRUSTED_HOST: host(proxies.pypi), UV_INSECURE_HOST: host(proxies.pypi) } : {}) });
65
+ if (proxies.apt) out.FORGE_APT_PROXY = proxies.apt;
66
+ if (proxies.git) out.FORGE_GIT_MIRROR = proxies.git;
67
+ return out;
68
+ }
69
+
70
+ /** The env a lane gets when snapshots are on (set by the dispatcher; the agent adds FORGE_ENV_IMAGE). {} when off. Pure. */
71
+ export function laneEnvFor(cfg, laneTools = []) {
72
+ if (!cfg?.enabled) return {};
73
+ return { FORGE_ENV_SNAPSHOTS: "1", FORGE_ENV_ROOT: "/cache/env", FORGE_ENV_PREFIX: ENV_PREFIX, ...(laneTools.length ? { FORGE_ENV_LANE_TOOLS: [...laneTools].sort().join(",") } : {}), ...proxyEnv(cfg.proxies) };
74
+ }
75
+
76
+ /**
77
+ * Pure key: 16 hex over the canonical inputs. `components` [{eco, dir, files: [{path, sha}]}], `pins` [{path, sha}],
78
+ * `laneTools` (any order), `image` (the base the trees were installed under), `platform`.
79
+ */
80
+ export function computeKey({ components = [], pins = [], laneTools = [], image = "", platform = "linux-x64" } = {}) {
81
+ const canon = {
82
+ v: 1, platform, image: String(image ?? ""), lane_tools: [...new Set(laneTools.map(String))].sort(),
83
+ components: components.map((c) => ({ eco: c.eco, dir: c.dir ?? ".", files: [...c.files].map((f) => [f.path, f.sha]).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)) }))
84
+ .sort((a, b) => (`${a.dir}\0${a.eco}` < `${b.dir}\0${b.eco}` ? -1 : 1)),
85
+ pins: pins.map((p) => [p.path, p.sha]).sort((a, b) => (a[0] < b[0] ? -1 : 1)),
86
+ };
87
+ return sha(JSON.stringify(canon)).slice(0, 16);
88
+ }
89
+
90
+ /**
91
+ * The environment of a checkout: its key and everything a build or a claim needs. `deps` is a depcache instance.
92
+ * @returns {Promise<{key, components: {eco, dir, lock, berry?, inputs, trees}[], skipped: {eco, dir, reason}[], pins: object, laneTools: string[], image: string, platform: string}>}
93
+ */
94
+ export async function describeEnv({ wt, deps, fs = nodeFs, laneTools = [], image = "", platform = "linux-x64" } = {}) {
95
+ const read = (rel) => { try { return fs.readFileSync(join(wt, rel)); } catch { return null; } };
96
+ const all = await deps.describe({ wt });
97
+ const components = all.filter((c) => !c.skip);
98
+ const pins = {}, pinList = [];
99
+ for (const f of PIN_FILES) { const b = read(f); if (b) { pins[f] = String(b).trim().slice(0, 200); pinList.push({ path: f, sha: sha(b) }); } }
100
+ const tools = validateLaneTools(laneTools).tools;
101
+ const key = computeKey({ platform, image, laneTools: tools, pins: pinList,
102
+ components: components.map((c) => ({ eco: c.eco, dir: c.dir, files: c.inputs.map((p) => { const b = read(p); return { path: p, sha: b ? sha(b) : "absent" }; }) })) });
103
+ return { key, components, skipped: all.filter((c) => c.skip).map((c) => ({ eco: c.eco, dir: c.dir, reason: c.skip })), pins, laneTools: tools, image: String(image ?? ""), platform };
104
+ }
105
+
106
+ /**
107
+ * How a lane gets the trees. Pure: `rename` (same filesystem and a staged copy is ready: no per-file work), `link` (same
108
+ * filesystem, nothing staged: one hardlink per file) or `copy` (different filesystems: every byte is copied; the mounts are wrong).
109
+ */
110
+ export function planClaim({ storeDev, worktreeDev, ready = 0 } = {}) {
111
+ const same = storeDev !== undefined && storeDev !== null && storeDev === worktreeDev;
112
+ if (!same) return { mode: "copy", reason: "the env store and the worktree are on different filesystems" };
113
+ return ready > 0 ? { mode: "rename", reason: null } : { mode: "link", reason: "no staged copy ready" };
114
+ }
115
+
116
+ /**
117
+ * Which snapshots GC removes. Pure. Per repo: the newest `keep` (by last use) stay; older ones go, and so does anything
118
+ * unused for `maxAgeMs` except each repo's newest one. `list` entries: {key, repo, lastUsed}.
119
+ */
120
+ export function planGc(list, { keep = ENV_DEFAULTS.keep, maxAgeMs = ENV_DEFAULTS.maxAgeDays * 86400000, now = Date.now() } = {}) {
121
+ const byRepo = new Map();
122
+ for (const s of list) { const k = s.repo ?? ""; if (!byRepo.has(k)) byRepo.set(k, []); byRepo.get(k).push(s); }
123
+ const out = [];
124
+ for (const snaps of byRepo.values()) {
125
+ snaps.sort((a, b) => (b.lastUsed ?? 0) - (a.lastUsed ?? 0));
126
+ snaps.forEach((s, i) => {
127
+ if (i === 0) return;
128
+ if (i >= Math.max(1, keep)) out.push({ key: s.key, repo: s.repo ?? null, reason: `beyond keep ${keep}` });
129
+ else if (now - (s.lastUsed ?? 0) > maxAgeMs) out.push({ key: s.key, repo: s.repo ?? null, reason: "unused past max age" });
130
+ });
131
+ }
132
+ return out;
133
+ }
134
+
135
+ const STALE_TMP_MS = 6 * 3600 * 1000;
136
+
137
+ /**
138
+ * Local-directory store. `linkTree(src, dst)` and `readOnly(dir)` are depcache's (hardlink, copy on EXDEV, writable
139
+ * copies of package-manager state files).
140
+ */
141
+ export function makeEnvStore({ root = envRoot(), fs = nodeFs, now = () => Date.now(), pid = process.pid, linkTree, readOnly } = {}) {
142
+ const dirOf = (key) => { if (!KEY_RE.test(String(key))) throw new Error(`invalid env key ${JSON.stringify(key)}`); return join(root, key); };
143
+ const present = (p) => { try { fs.lstatSync(p); return true; } catch { return false; } };
144
+ const names = (d) => { try { return fs.readdirSync(d); } catch { return []; } };
145
+ const manifest = (key) => { try { return JSON.parse(String(fs.readFileSync(join(dirOf(key), "manifest.json")))); } catch { return null; } };
146
+ const has = (key) => manifest(key) !== null;
147
+ const readyIds = (key) => names(join(dirOf(key), "ready")).filter((n) => !n.startsWith(".")).sort();
148
+ const touch = (key) => { try { fs.writeFileSync(join(dirOf(key), "last-used"), String(now())); } catch { /* best effort */ } };
149
+ const measure = (dir) => { let bytes = 0, files = 0; const walk = (d) => { for (const e of fs.readdirSync(d, { withFileTypes: true })) { const p = join(d, e.name); if (e.isDirectory()) walk(p); else { files++; if (e.isFile()) bytes += fs.statSync(p).size; } } }; walk(dir); return { bytes, files }; };
150
+
151
+ /** Move the installed `trees` of `wt` into a new snapshot (atomic; an existing snapshot of the key wins). Returns the manifest. */
152
+ function publish({ key, wt, trees, manifest: extra = {} }) {
153
+ const dir = dirOf(key), tmp = `${dir}.tmp-${pid}`;
154
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
155
+ fs.rmSync(tmp, { recursive: true, force: true });
156
+ try {
157
+ for (const t of trees) linkTree(join(wt, t), join(tmp, "tree", t));
158
+ readOnly(join(tmp, "tree"));
159
+ const { bytes, files } = measure(join(tmp, "tree"));
160
+ const man = { v: 1, key, prefix: wt, trees, ...extra, size_bytes: bytes, files, created: now() };
161
+ fs.writeFileSync(join(tmp, "manifest.json"), JSON.stringify(man, null, 2) + "\n");
162
+ fs.writeFileSync(join(tmp, "last-used"), String(now()));
163
+ try { fs.renameSync(tmp, dir); } catch (e) { if (!has(key)) throw e; fs.rmSync(tmp, { recursive: true, force: true }); return manifest(key); }
164
+ return man;
165
+ } catch (e) { try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* best effort */ } throw e; }
166
+ }
167
+
168
+ /** Stage hardlink copies until `count` are ready. Runs outside jobs (pool host). Returns how many were added. */
169
+ function stage({ key, count = ENV_DEFAULTS.ready }) {
170
+ const man = manifest(key);
171
+ if (!man) return 0;
172
+ const ready = join(dirOf(key), "ready");
173
+ fs.mkdirSync(ready, { recursive: true });
174
+ let added = 0;
175
+ for (let i = readyIds(key).length; i < count; i++) {
176
+ const id = `${now().toString(36)}-${pid}-${i}`, tmp = join(ready, `.tmp-${id}`);
177
+ try {
178
+ for (const t of man.trees) linkTree(join(dirOf(key), "tree", t), join(tmp, t));
179
+ fs.renameSync(tmp, join(ready, id));
180
+ added++;
181
+ } catch { try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* best effort */ } break; }
182
+ }
183
+ return added;
184
+ }
185
+
186
+ /**
187
+ * Put the snapshot's trees into `wt`. null (nothing changed) when there is no snapshot, a tree already exists in the
188
+ * worktree, or the build prefix cannot be aliased to `wt`. Otherwise {mode: rename|link|copy, ms, trees}.
189
+ */
190
+ function claim({ key, wt, prefix = null }) {
191
+ const t0 = now(), man = manifest(key);
192
+ if (!man || !Array.isArray(man.trees) || !man.trees.length) return null;
193
+ if (man.trees.some((t) => present(join(wt, t)))) return null;
194
+ if (man.prefix !== wt) {
195
+ // The trees name man.prefix in absolute paths: it must resolve to this worktree.
196
+ if (!prefix || prefix !== man.prefix) return null;
197
+ try {
198
+ let st = null;
199
+ try { st = fs.lstatSync(prefix); } catch { /* absent */ }
200
+ if (st && !st.isSymbolicLink()) return null;
201
+ if (st) fs.unlinkSync(prefix);
202
+ fs.mkdirSync(dirname(prefix), { recursive: true });
203
+ fs.symlinkSync(wt, prefix);
204
+ } catch { return null; }
205
+ }
206
+ const dir = dirOf(key);
207
+ const dev = (p) => { try { return fs.statSync(p).dev; } catch { return undefined; } };
208
+ const plan = planClaim({ storeDev: dev(dir), worktreeDev: dev(wt), ready: readyIds(key).length });
209
+ const undo = () => { for (const t of man.trees) { try { fs.rmSync(join(wt, t), { recursive: true, force: true }); } catch { /* best effort */ } } };
210
+ if (plan.mode === "rename") {
211
+ for (const id of readyIds(key)) {
212
+ const mine = join(dir, `.claim-${pid}-${id}`);
213
+ try { fs.renameSync(join(dir, "ready", id), mine); } catch { continue; } // another lane took it
214
+ try {
215
+ for (const t of man.trees) { fs.mkdirSync(dirname(join(wt, t)), { recursive: true }); fs.renameSync(join(mine, t), join(wt, t)); }
216
+ fs.rmSync(mine, { recursive: true, force: true });
217
+ touch(key);
218
+ return { mode: "rename", ms: now() - t0, trees: man.trees };
219
+ } catch { undo(); try { fs.rmSync(mine, { recursive: true, force: true }); } catch { /* best effort */ } break; }
220
+ }
221
+ }
222
+ try {
223
+ for (const t of man.trees) linkTree(join(dir, "tree", t), join(wt, t));
224
+ touch(key);
225
+ return { mode: plan.mode === "copy" ? "copy" : "link", ms: now() - t0, trees: man.trees };
226
+ } catch { undo(); return null; }
227
+ }
228
+
229
+ /** Every snapshot under the root. */
230
+ function list() {
231
+ const out = [];
232
+ for (const key of names(root).filter((n) => KEY_RE.test(n)).sort()) {
233
+ const man = manifest(key);
234
+ if (!man) continue;
235
+ let lastUsed = Number(man.created) || 0;
236
+ try { const v = Number(String(fs.readFileSync(join(dirOf(key), "last-used")))); if (Number.isFinite(v) && v > 0) lastUsed = v; } catch { /* created */ }
237
+ out.push({ key, repo: man.repo ?? null, ref: man.ref ?? null, commit: man.commit ?? null, ecosystems: (man.ecosystems ?? []).map((e) => e.eco), created: man.created, lastUsed, size_bytes: man.size_bytes ?? null, files: man.files ?? null, ready: readyIds(key).length, path: dirOf(key) });
238
+ }
239
+ return out;
240
+ }
241
+
242
+ /** Remove what planGc names (when `apply`), plus tmp and claim dirs older than 6 h. Returns {remove: planned, removed: keys}. */
243
+ function gc({ keep, maxAgeMs, apply = false } = {}) {
244
+ const remove = planGc(list(), { keep, maxAgeMs, now: now() });
245
+ const removed = [];
246
+ if (!apply) return { remove, removed };
247
+ for (const r of remove) { try { fs.rmSync(dirOf(r.key), { recursive: true, force: true }); removed.push(r.key); } catch { /* leave it */ } }
248
+ const old = (p) => { try { return now() - fs.statSync(p).mtimeMs > STALE_TMP_MS; } catch { return false; } };
249
+ for (const n of names(root)) if (/^[0-9a-f]{16}\.tmp-\d+$/.test(n) && old(join(root, n))) { try { fs.rmSync(join(root, n), { recursive: true, force: true }); } catch { /* leave it */ } }
250
+ for (const key of names(root).filter((n) => KEY_RE.test(n))) {
251
+ for (const n of names(dirOf(key))) if (n.startsWith(".claim-") && old(join(dirOf(key), n))) { try { fs.rmSync(join(dirOf(key), n), { recursive: true, force: true }); } catch { /* leave it */ } }
252
+ for (const n of names(join(dirOf(key), "ready"))) if (n.startsWith(".tmp-") && old(join(dirOf(key), "ready", n))) { try { fs.rmSync(join(dirOf(key), "ready", n), { recursive: true, force: true }); } catch { /* leave it */ } }
253
+ }
254
+ return { remove, removed };
255
+ }
256
+
257
+ return { kind: "local", root, has, manifest, publish, stage, claim, list, gc, locate: dirOf };
258
+ }
259
+
260
+ /** Manifest fields shared by both stores. */
261
+ export const manifestOf = (desc, { repo = null, ref = null, commit = null, resolved = {} } = {}) => ({
262
+ repo, ref, commit, ecosystems: desc.components.map((c) => ({ eco: c.eco, dir: c.dir, lock: c.lock })),
263
+ toolchain: { pins: desc.pins, resolved }, lane_tools: desc.laneTools, image: desc.image, platform: desc.platform,
264
+ });
265
+
266
+ /**
267
+ * Build a snapshot in the local store from a checkout at `wt` (the prefix). Runs the repo's own frozen installs through
268
+ * depcache; publishes only when every ecosystem installed. Meant for a build container on the pool host, never a job.
269
+ * @returns {Promise<{status: "exists"|"built"|"failed", key, reason?, manifest?}>}
270
+ */
271
+ export async function buildLocal({ wt, deps, store, desc, fs = nodeFs, exec = null, repo = null, ref = null, commit = null } = {}) {
272
+ if (store.has(desc.key)) return { status: "exists", key: desc.key, manifest: store.manifest(desc.key) };
273
+ if (!desc.components.length) return { status: "failed", key: desc.key, reason: "no lockfile the environment library can install" };
274
+ const res = await deps.prepare({ wt, repoKey: "env-build", publish: false });
275
+ const bad = res.find((r) => r.status === "failed");
276
+ if (bad) return { status: "failed", key: desc.key, reason: `${bad.eco ?? "install"}: ${bad.reason}` };
277
+ const trees = desc.components.flatMap((c) => c.trees).filter((t) => { try { fs.lstatSync(join(wt, t)); return true; } catch { return false; } });
278
+ if (!trees.length) return { status: "failed", key: desc.key, reason: "the installs produced no node_modules/.venv" };
279
+ const resolved = {};
280
+ if (exec) for (const tool of ["node", "python3"]) { try { resolved[tool] = String(await exec(tool, ["--version"], { timeoutMs: 30000 })).trim(); } catch { /* not installed */ } }
281
+ const manifest = store.publish({ key: desc.key, wt, trees, manifest: manifestOf(desc, { repo, ref, commit, resolved }) });
282
+ return { status: "built", key: desc.key, manifest };
283
+ }
284
+
285
+ /** depcache.prepare's hook: claim the snapshot for this worktree's key. {key, mode, ms}, or null on a miss (nothing changed). */
286
+ export async function claimForLane({ wt, deps, fs = nodeFs, env = process.env, now = () => Date.now() } = {}) {
287
+ const t0 = now();
288
+ const desc = await describeEnv({ wt, deps, fs, laneTools: String(env.FORGE_ENV_LANE_TOOLS ?? "").split(",").filter(Boolean), image: env.FORGE_ENV_IMAGE ?? "" });
289
+ if (!desc.components.length) return null;
290
+ const store = makeEnvStore({ root: envRoot(env), fs, now, linkTree: deps.linkTree, readOnly: deps.readOnly });
291
+ const got = store.claim({ key: desc.key, wt, prefix: String(env.FORGE_ENV_PREFIX ?? "").trim() || null });
292
+ return got ? { key: desc.key, mode: got.mode, ms: now() - t0 } : null;
293
+ }
294
+
295
+ const shq = (s) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${String(s).replace(/'/g, "'\\''")}'`);
296
+ /** Installs that need only the lockfile and manifests in the build context (no project source). */
297
+ function ociInstall(c) {
298
+ if (c.eco === "uv") return [["uv", ["venv", "--relocatable", ".venv"]], ["uv", ["sync", "--frozen", "--no-install-project"]]];
299
+ if (c.eco === "poetry") return [["poetry", ["install", "--sync", "--no-root"]]];
300
+ return depCommands(c).install;
301
+ }
302
+
303
+ /**
304
+ * OCI backend: the image for a key and how to build it. Pure; running docker is the pool host's job.
305
+ * `existing(path)` says which hashed inputs are in the checkout (absent optional files are not COPYed).
306
+ * @returns {{ref, dockerfile, build: string[], push: string[]}}
307
+ */
308
+ export function ociRecipe({ desc, baseImage, image, existing = () => true, prefix = ENV_PREFIX, repo = null, commit = null } = {}) {
309
+ if (!baseImage) throw new Error("env.snapshots.base_image is required for the oci store (the image the installs run in)");
310
+ if (!image) throw new Error("env.snapshots.image is required for the oci store (the repository snapshots are pushed to, without a tag)");
311
+ if (/[\s"'`$;&|<>\\]/.test(`${baseImage}${image}`)) throw new Error("env.snapshots.base_image and image must be plain image references");
312
+ checkRecipes(desc.laneTools);
313
+ const ref = `${image}:${desc.key}`;
314
+ const lines = [`# Environment snapshot ${desc.key}. Generated by \`forgedock env build\`; do not edit.`,
315
+ ...laneToolsDockerfile(baseImage, desc.laneTools).trimEnd().split("\n"), `WORKDIR ${prefix}`];
316
+ const copied = new Set();
317
+ const copy = (files) => {
318
+ const byDir = new Map();
319
+ for (const f of files) { if (copied.has(f) || !existing(f)) continue; copied.add(f); const d = dirname(f); if (!byDir.has(d)) byDir.set(d, []); byDir.get(d).push(f); }
320
+ for (const [d, fl] of [...byDir].sort()) lines.push(`COPY ${JSON.stringify([...fl, d === "." ? "./" : `${d}/`])}`);
321
+ };
322
+ copy(PIN_FILES);
323
+ for (const c of desc.components) {
324
+ copy(c.inputs);
325
+ const cd = c.dir === "." ? "" : `cd ${shq(c.dir)} && `;
326
+ lines.push(`RUN ${cd}${ociInstall(c).map(([cmd, args]) => [cmd, ...args].map(shq).join(" ")).join(" && ")}`);
327
+ }
328
+ const man = { v: 1, key: desc.key, prefix, trees: desc.components.flatMap((c) => c.trees), ...manifestOf(desc, { repo, commit }) };
329
+ lines.push(`RUN printf '%s\\n' ${shq(JSON.stringify(man))} > ${prefix}/.forge-env.json`, `LABEL io.forgedock.env.key=${desc.key}`, "");
330
+ return { ref, dockerfile: lines.join("\n"), manifest: man, build: ["docker", "build", "-f", "Dockerfile.env", "-t", ref, "."], push: ["docker", "push", ref] };
331
+ }
332
+
333
+ /** OCI store: same interface where it applies. `exec` (pool host only) answers `has` with `docker manifest inspect`. */
334
+ export function makeOciStore({ image, baseImage, exec = null } = {}) {
335
+ const locate = (key) => `${image}:${key}`;
336
+ return { kind: "oci", locate,
337
+ async has(key) { if (!exec) return null; try { await exec("docker", ["manifest", "inspect", locate(key)], { timeoutMs: 60000 }); return true; } catch { return false; } },
338
+ recipe: (o) => ociRecipe({ ...o, baseImage, image }) };
339
+ }
package/bin/forgedock.mjs CHANGED
@@ -3982,14 +3982,15 @@ async function watch() {
3982
3982
  const SPLASH_COMMANDS = new Set(["run", "bootstrap", "run-issue", "orchestrate", "triage", "probe", "gc", "resume-stalled", "demo", "first-run", "doctor", "watch", "help", "--help", "-h"]);
3983
3983
  const KNOWN_COMMANDS = new Set([
3984
3984
  "install", "init", "enable", "disable", "status", "uninstall", "update",
3985
- "run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "acceptance", "interfaces", "docs", "review-staging", "release", "intake", "gc", "sandbox", "resume-stalled", "demo", "first-run", "doctor", "auth", "watch", "issue-watch", "prod-watch", "selftest", "labels", "config", "stats", "limits", "decisions", "sched", "schedd", "pool", "check", "guide", "help", "--help", "-h",
3985
+ "run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "acceptance", "interfaces", "docs", "review-staging", "release", "intake", "gc", "env", "sandbox", "resume-stalled", "demo", "first-run", "doctor", "auth", "watch", "issue-watch", "prod-watch", "selftest", "labels", "config", "stats", "limits", "decisions", "sched", "schedd", "pool", "check", "guide", "help", "--help", "-h",
3986
+ "ci-step", "ci-hook", "tests",
3986
3987
  "version", "--version", "-v",
3987
3988
  ]);
3988
3989
  if (SPLASH_COMMANDS.has(command) || !KNOWN_COMMANDS.has(command)) splash(command);
3989
3990
 
3990
3991
  let exitCode = 0;
3991
3992
  // #5301: an App login puts a scoped installation token in this process's env (GH_TOKEN) for child gh calls; no login, no change.
3992
- if (command !== "auth") await applyAuthEnv();
3993
+ if (command !== "auth" && command !== "ci-step" && command !== "ci-hook") await applyAuthEnv();
3993
3994
  // #5381: installation tokens live 1h; long-running commands re-resolve before expiry so later gh calls and lanes inherit a fresh one.
3994
3995
  if (AUTH_REFRESH_COMMANDS.has(command)) startAuthRefresh();
3995
3996
  switch (command) {
@@ -4219,6 +4220,12 @@ switch (command) {
4219
4220
  exitCode = await runGc(restArgs);
4220
4221
  break;
4221
4222
  }
4223
+ case "env": {
4224
+ // Environment library: per-repo dependency snapshots keyed by lockfiles + toolchain + lane_tools (bin/env)
4225
+ const { envFromCli } = await import("./env/cli.mjs");
4226
+ exitCode = await envFromCli(restArgs);
4227
+ break;
4228
+ }
4222
4229
  case "sandbox": {
4223
4230
  // #5450: operator control of the lane test sandboxes (verify.sandboxes): up <name>... | down | ls
4224
4231
  const { sandboxFromCli } = await import("./lean/testsandbox.mjs");
@@ -4419,13 +4426,35 @@ switch (command) {
4419
4426
  // Actions-minutes budget and CI placement policy (#5278): `forgedock ci budget`.
4420
4427
  const { ciFromCli } = await import("./lean/ci-budget.mjs");
4421
4428
  try {
4422
- exitCode = await ciFromCli(restArgs);
4429
+ if (restArgs[0] === "cancel-superseded") { // #5718: cancel the verification runs of a superseded head (off unless verify.cancel_superseded or --mode)
4430
+ const [{ cancelSupersededFromCli }, { ciRunSeams }, { defaultGh, isValidRepo }, { resolveRepo }, { readVerify }] = await Promise.all([import("./lean/verify.mjs"), import("./lean/effects.mjs"), import("./stats/github-source.mjs"), import("./stats/index.mjs"), import("./engine-cli.mjs")]);
4431
+ const repo = resolveRepo(null);
4432
+ exitCode = await cancelSupersededFromCli(restArgs.slice(1), { gh: defaultGh, repo: isValidRepo(repo) ? repo : null, config: readVerify() ?? {}, seams: ({ repo: r }) => ciRunSeams({ gh: defaultGh, repo: r }) });
4433
+ } else exitCode = await ciFromCli(restArgs);
4423
4434
  } catch (err) {
4424
4435
  process.stderr.write(`${RED}${err.message}${RESET}\n`);
4425
4436
  exitCode = 1;
4426
4437
  }
4427
4438
  break;
4428
4439
  }
4440
+ case "tests": {
4441
+ // Test engine (#5710): `forgedock tests select|shard|recall` (affected-test selection, shard plan, shadow recall ledger).
4442
+ const { testsFromCli } = await import("./lean/testengine.mjs");
4443
+ try {
4444
+ exitCode = await testsFromCli(restArgs);
4445
+ } catch (err) {
4446
+ process.stderr.write(`${RED}${err.message}${RESET}\n`);
4447
+ exitCode = 1;
4448
+ }
4449
+ break;
4450
+ }
4451
+ case "ci-step":
4452
+ case "ci-hook": {
4453
+ // Runner-side CI event emitter (#5689): `forgedock ci-step --name <step> -- <cmd...>`, `forgedock ci-hook job-started|job-completed`.
4454
+ const { ciStepFromCli, ciHookFromCli } = await import("./lean/ci-emit.mjs");
4455
+ exitCode = await (command === "ci-step" ? ciStepFromCli : ciHookFromCli)(restArgs);
4456
+ break;
4457
+ }
4429
4458
  case "interfaces": {
4430
4459
  // Architecture and interface contracts (#5338): `forgedock interfaces check|register|contract`.
4431
4460
  const { interfacesFromCli } = await import("./lean/interfaces.mjs");
package/bin/help-text.mjs CHANGED
@@ -77,6 +77,7 @@ export const FULL_COMMAND_GROUPS = [
77
77
  ["npx forgedock issue-watch run [--name <w>] [--repo owner/repo] [--once] [--dry-run] | status [--name <w>]", "Named, scoped, capped watches (forge.yaml issue_watch.watches) that claim matching open issues into lanes or one long-lived orchestrate batch, or (mode: release) pool them and cut themed releases; see docs/ISSUE-WATCH.md"],
78
78
  ["npx forgedock prod-watch run [--repo owner/repo] [--once] [--interval <s>] [--dry-run] | status", "Production-side watcher (forge.yaml prod_watch): read-only signal sources -> triage -> governor -> issues, kill-switch file, owner digest; see docs/PROD-WATCH.md"],
79
79
  ["npx forgedock ci budget [--repo owner/repo] [--json] [--digest] [--propose [--base REF]] [--set-mode MODE] [--budget MINUTES] [--reserve PCT] [--plan PLAN]", "Actions-minutes budget: month-to-date usage, projection and where CI runs (remote or local-first); sets the mode and budget"],
80
+ ["npx forgedock tests select [--base REF | --changed FILE... | --changed-from FILE] [--full] [--json] [--out FILE] | tests shard [--shards N | --target-seconds S] [--report FILE]... [--from SELECTION] [--json | --matrix] | tests recall [record --selection FILE [--report FILE]... | status | check]", "Test engine (ci.tests, default off): the tests a change can affect with a reason each (JS/TS import graph, Python imports, ci.tests.suites globs; lockfile/manifest/CI changes and unmapped files select everything), a duration-balanced shard plan and CI matrix, and the shadow recall ledger that must graduate before selection: enforce may skip anything"],
80
81
  ["npx forgedock replan apply --amendment N --repo owner/repo", "After an amendment merged, re-evaluate the open sibling issues held behind it"],
81
82
  ["npx forgedock resume-stalled [--dry-run]", "Fleet stall recovery: re-dispatch issues whose run stopped holding its claim"],
82
83
  ]],
@@ -109,6 +110,7 @@ export const FULL_COMMAND_GROUPS = [
109
110
  ["npx forgedock schedd [status | watchdog]", "Host scheduler daemon hosting every orchestrate batch (auto-spawned by orchestrate; run in the foreground for a systemd-user unit); status shows its pid, batches and last tick; watchdog restarts a stalled daemon"],
110
111
  ["npx forgedock pool router [install] | enroll [--cpus N --mem GB] | status | upgrade [agent] | remove <agent>", "Built-in remote compute pool: run the router (foreground, or install it as a user service), print the one-time install command for a host, list agents, upgrade or remove them"],
111
112
  ["npx forgedock gc [--apply] [--older-than 6h] [--docker] [--worktrees] [--branches] [--tmp] [--processes] [--sandboxes]", "Report (dry-run default) and reclaim ForgeDock-owned leftovers: stale run ledgers, labelled containers/volumes, agent worktrees, abandoned branches, scratch files, orphaned processes and sandboxes; unowned resources and unpushed work are only reported"],
113
+ ["npx forgedock env key|build|status|gc [--store local|oci] [--out <dir>] [--apply] [--json]", "Environment library (forge.yaml env.snapshots, default off): dependency snapshots keyed by lockfiles + toolchain pins + lane_tools, built once outside jobs and reused by lane sandboxes, CI jobs and deploy images; build writes the recipe and manifest only (docs/ENV-LIBRARY.md)"],
112
114
  ]],
113
115
  ];
114
116
 
@@ -306,12 +306,14 @@ export function writeCiBlock(raw, set) {
306
306
  }
307
307
 
308
308
  // ---- CLI -------------------------------------------------------------------------------------------------------------
309
- export const CI_USAGE = "usage: forgedock ci budget [--repo owner/repo] [--json] [--digest] [--propose [--base REF]] [--set-mode MODE] [--budget MINUTES] [--reserve PCT] [--plan PLAN]";
309
+ export const CI_USAGE = "usage: forgedock ci preflight [--json] | forgedock ci runner-health [--recover] [--json] [--repo owner/repo] [--print-units] | forgedock ci budget [--repo owner/repo] [--json] [--digest] [--propose [--base REF]] [--set-mode MODE] [--budget MINUTES] [--reserve PCT] [--plan PLAN]";
310
310
  const flagVal = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : undefined; };
311
311
 
312
312
  /** `forgedock ci budget ...`; @returns the exit code. `deps`: {gh, cwd, now, out, dir}. */
313
313
  export async function ciFromCli(argv, deps = {}) {
314
314
  const out = deps.out ?? ((l) => console.log(l)), cwd = deps.cwd ?? process.cwd(), gh = deps.gh ?? defaultGh, now = deps.now ?? Date.now(), dir = deps.dir ?? cacheDir();
315
+ if (argv[0] === "preflight") return (await import("./ci-preflight.mjs")).ciPreflightFromCli(argv.slice(1), { out, cwd, ...deps.preflight });
316
+ if (argv[0] === "runner-health") return (await import("./ci-runner-health.mjs")).ciRunnerHealthFromCli(argv.slice(1), { out, cwd, ...deps.runnerHealth });
315
317
  if (argv[0] !== "budget") throw new Error(CI_USAGE);
316
318
  const rest = argv.slice(1);
317
319
  const valued = ["--repo", "--set-mode", "--budget", "--reserve", "--plan", "--base"];
@@ -0,0 +1,74 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { INFRA_SIGNATURES, signatureHash } from "./release-flakes.mjs";
4
+
5
+ /** #5690: deterministic CI failure impact classifier (parent #5687). Pure: no I/O, the caller passes the flake ledger. */
6
+ export const CI_CLASSES = ["deterministic-setup", "generated-artifact-stale", "infra", "flaky-suspect", "code"];
7
+ export const DOWNSTREAM_CLASSES = ["deterministic-setup", "generated-artifact-stale"];
8
+ export const FAIL_FAST_POLICIES = ["off", "deterministic"];
9
+
10
+ /** Setup failures that break every downstream job. Kept narrow: a false setup class on a code failure cancels good jobs. */
11
+ export const SETUP_SIGNATURES = [
12
+ ["command-not-found", /(?:^|[\s:])(?:[\w./-]+: )?(?:command not found|not found in PATH)|executable file not found in \$?PATH|is not recognized as an internal or external command|exec: "[^"]+": executable file not found/im],
13
+ ["missing-package", /npm ERR! 404 .*Not Found|ERR_PNPM_FETCH_404|ERR_PNPM_NO_MATCHING_VERSION|No matching distribution found for|Could not find a version that satisfies the requirement|ModuleNotFoundError: No module named '(?:pip|setuptools|wheel)'|go: (?:module )?\S+: reading \S+: 404|cannot find package "\S+" in any of|package \S+ is not in (?:GOROOT|std)/i],
14
+ ["package-config", /ERESOLVE|ERR_PNPM_(?:INVALID_|BAD_|UNSUPPORTED_ENGINE|UNEXPECTED_STORE|NO_PKG_MANIFEST)\w*|npm ERR! code (?:EUSAGE|E401|E403|EJSONPARSE|EBADENGINE)|npm ERR! (?:Invalid|Unsupported) |npm ERR! missing script|Unknown (?:env )?config "?\S+"?|\.npmrc/i],
15
+ ["lockfile-mismatch", /ERR_PNPM_OUTDATED_LOCKFILE|ERR_PNPM_LOCKFILE_\w+|`npm ci` can only install packages when your package\.json and package-lock\.json|lockfile .* (?:needs to be updated|not up to date|out of sync)|Cannot install with "frozen-lockfile"|uv\.lock .* (?:out of date|needs to be updated)|poetry\.lock is not up to date|pyproject\.toml changed significantly since poetry\.lock|updates to go\.(?:mod|sum) needed|go\.sum: missing|missing go\.sum entry/i],
16
+ ["image-pull", /manifest unknown|pull access denied|Error response from daemon: (?:manifest|pull access|Get ")|failed to pull image|ErrImagePull|ImagePullBackOff|repository does not exist|toomanyrequests: You have reached your pull rate limit|failed to resolve source metadata for|no matching manifest for/i],
17
+ ["setup-permission", /(?:EACCES|Permission denied)[^\n]*(?:node_modules|\.npm|\.cache|\.pnpm-store|\/usr\/(?:local\/)?(?:bin|lib)|site-packages|\.cargo|\/opt\/|\/home\/runner\/work\/_temp|docker\.sock|go\/pkg\/mod)/i],
18
+ ];
19
+
20
+ /** Generated artifacts out of date (diff-after-generate, drift checks). */
21
+ export const STALE_SIGNATURES = [
22
+ ["out-of-date-run", /(?:is|are|was|were)? ?(?:out of date|out-of-date|stale)[^\n]*\b(?:run|regenerate|re-run|rerun)\b|\b(?:run|regenerate)\b[^\n]*(?:to update|to regenerate|to fix)|please (?:run|regenerate)\b[^\n]*(?:and commit|again)|generated files? (?:are|is) (?:out of date|not up to date|stale)|(?:schema|snapshot|types?|openapi|docs|client|bindings|codegen)[^\n]*(?:out of date|not up to date|drift|stale)/i],
23
+ ["diff-after-generate", /(?:working tree|git diff|repository|tree) (?:is )?(?:not clean|dirty|has (?:uncommitted )?changes|differs)[^\n]*(?:after|generat|codegen)|(?:after|following) (?:running )?(?:generate|codegen|make gen)[^\n]*(?:diff|changes|modified|dirty)|files? (?:changed|modified) after (?:generat|build|codegen)|generated .* (?:differ|changed|not committed)|uncommitted changes (?:detected )?after (?:generat|codegen|build)/i],
24
+ ["drift-check", /(?:^|\b)(?:drift detected|drift check failed|schema drift|migration drift|api drift|openapi drift)\b|(?:check[-_ ]generated|verify[-_ ]generated|check[-_ ]drift|codegen[-_ ]check)\b[^\n]*(?:fail|error|differ|diff)|Files? differ(?:ing)? from (?:committed|generated)|differs from the committed/i],
25
+ ];
26
+
27
+ const MAX_SIG = 200;
28
+ /** First meaningful error line, digits and hex collapsed, so a re-run of the same failure hashes the same. */
29
+ function codeSignature(lines, test) {
30
+ const all = [test?.message, ...lines].filter((l) => typeof l === "string");
31
+ const hit = all.find((l) => /\b(?:error|assert\w*|fail\w*|expected|exception|panic|TS\d{4}|E\d{3,4})\b/i.test(l)) ?? all.find((l) => l.trim()) ?? "";
32
+ return hit.trim().toLowerCase().replace(/0x[0-9a-f]+|\b[0-9a-f]{7,40}\b/g, "H").replace(/\d+/g, "N").replace(/\s+/g, " ").slice(0, MAX_SIG);
33
+ }
34
+
35
+ const firstHit = (table, text) => table.find(([, re]) => re.test(text))?.[0] ?? null;
36
+
37
+ /**
38
+ * `{step, lines, test, flakes}` -> `{class, signature, downstream}`. `flakes` is the ledger list (release-flakes `readFlakes`).
39
+ * Order: setup, stale, infra, then a ledger hit overrides a would-be `code`. A test failure never classes as setup/stale: its
40
+ * output is the test's own, and e.g. a bad import in code would look like a missing module.
41
+ */
42
+ export function classifyCiFailure({ step, lines, test, flakes } = {}) {
43
+ const ls = Array.isArray(lines) ? lines.filter((l) => typeof l === "string") : [];
44
+ const text = [...ls, test?.message ?? ""].join("\n");
45
+ const out = (cls, signature) => ({ class: cls, signature, downstream: DOWNSTREAM_CLASSES.includes(cls) });
46
+ if (!test) {
47
+ const setup = firstHit(SETUP_SIGNATURES, text);
48
+ if (setup) return out("deterministic-setup", setup);
49
+ const stale = firstHit(STALE_SIGNATURES, text);
50
+ if (stale) return out("generated-artifact-stale", stale);
51
+ }
52
+ const infra = firstHit(INFRA_SIGNATURES, text);
53
+ if (infra) return out("infra", infra);
54
+ const sig = codeSignature(ls, test);
55
+ if (Array.isArray(flakes) && flakes.length) {
56
+ const h = signatureHash(step ?? "", test?.id ?? null, sig);
57
+ if (flakes.some((f) => f?.signature_hash === h)) return out("flaky-suspect", sig);
58
+ }
59
+ return out("code", sig);
60
+ }
61
+
62
+ /** `fail_fast` from a forge.yaml `ci` block or a bare string; anything but `deterministic` is `off`. */
63
+ export const failFastPolicy = (policy) => { const v = typeof policy === "string" ? policy : policy?.fail_fast; return v === "deterministic" ? "deterministic" : "off"; };
64
+
65
+ /**
66
+ * Decision only: `{action:"cancel"|"continue", reason}`. Cancelling is done by the subscriber (the #5687 lane consumer), never by the router.
67
+ * Only a downstream class under policy `deterministic` returns `cancel`.
68
+ */
69
+ export function failFastDecision(event, policy) {
70
+ const cls = event?.class ?? (event && (event.type === "step_failed" || event.type === "test_failed") ? classifyCiFailure(event).class : null);
71
+ if (failFastPolicy(policy) !== "deterministic") return { action: "continue", reason: "fail_fast off" };
72
+ if (DOWNSTREAM_CLASSES.includes(cls)) return { action: "cancel", reason: `${cls} breaks every downstream job` };
73
+ return { action: "continue", reason: `class ${cls ?? "none"} is not downstream` };
74
+ }