forgedock 1.54.0 → 1.55.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 (114) hide show
  1. package/bin/auth/app-token.mjs +2 -0
  2. package/bin/auth/app-token.test.mjs +9 -1
  3. package/bin/engine/events.mjs +1 -0
  4. package/bin/engine/events.test.mjs +5 -1
  5. package/bin/engine/outcome-codes.mjs +3 -0
  6. package/bin/engine-cli.mjs +126 -34
  7. package/bin/forgedock.mjs +56 -4
  8. package/bin/gc-schedule.mjs +83 -0
  9. package/bin/gc.mjs +56 -8
  10. package/bin/help-text.mjs +1 -1
  11. package/bin/hooks/pre-tool-use.mjs +1 -0
  12. package/bin/init-detect.mjs +73 -2
  13. package/bin/labels.json +5 -0
  14. package/bin/lean/admission.mjs +21 -1
  15. package/bin/lean/baselines.mjs +43 -0
  16. package/bin/lean/baselines.test.mjs +33 -0
  17. package/bin/lean/batch-health.mjs +43 -6
  18. package/bin/lean/batch-health.test.mjs +41 -1
  19. package/bin/lean/batch.mjs +41 -4
  20. package/bin/lean/batch.test.mjs +106 -3
  21. package/bin/lean/conformance.mjs +131 -12
  22. package/bin/lean/conformance.test.mjs +172 -3
  23. package/bin/lean/depcache.mjs +23 -2
  24. package/bin/lean/depcache.test.mjs +22 -0
  25. package/bin/lean/docsgate.mjs +137 -0
  26. package/bin/lean/docsgate.test.mjs +78 -0
  27. package/bin/lean/effects.mjs +31 -2
  28. package/bin/lean/enumerating.mjs +39 -13
  29. package/bin/lean/enumerating.test.mjs +20 -0
  30. package/bin/lean/execution.test.mjs +3 -3
  31. package/bin/lean/fastforward.mjs +93 -0
  32. package/bin/lean/fastforward.test.mjs +73 -0
  33. package/bin/lean/guardgate.mjs +38 -7
  34. package/bin/lean/guardgate.test.mjs +39 -0
  35. package/bin/lean/issuewatch-install.mjs +92 -0
  36. package/bin/lean/issuewatch-install.test.mjs +31 -0
  37. package/bin/lean/issuewatch-parity.mjs +33 -3
  38. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  39. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  40. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  41. package/bin/lean/issuewatch-verify.mjs +51 -9
  42. package/bin/lean/issuewatch.mjs +153 -33
  43. package/bin/lean/issuewatch.test.mjs +243 -22
  44. package/bin/lean/lean.mjs +381 -75
  45. package/bin/lean/lean.test.mjs +437 -20
  46. package/bin/lean/light.mjs +11 -3
  47. package/bin/lean/light.test.mjs +27 -0
  48. package/bin/lean/lightlane.mjs +8 -3
  49. package/bin/lean/lightlane.test.mjs +20 -0
  50. package/bin/lean/mechfix.mjs +35 -4
  51. package/bin/lean/mechfix.test.mjs +48 -1
  52. package/bin/lean/orchestrate-children.test.mjs +10 -0
  53. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  54. package/bin/lean/orchestrate.mjs +28 -4
  55. package/bin/lean/overlap.mjs +20 -0
  56. package/bin/lean/overlap.test.mjs +49 -0
  57. package/bin/lean/pagegate.mjs +152 -0
  58. package/bin/lean/pagegate.test.mjs +77 -0
  59. package/bin/lean/parked-relabel.mjs +32 -0
  60. package/bin/lean/parked-relabel.test.mjs +45 -0
  61. package/bin/lean/phaseledger.mjs +17 -2
  62. package/bin/lean/postdeploy-check.mjs +27 -0
  63. package/bin/lean/postdeploy-check.test.mjs +13 -1
  64. package/bin/lean/postrun.mjs +32 -0
  65. package/bin/lean/postrun.test.mjs +41 -0
  66. package/bin/lean/preflight.mjs +46 -0
  67. package/bin/lean/preflight.test.mjs +30 -1
  68. package/bin/lean/prompts.mjs +36 -6
  69. package/bin/lean/recovery.test.mjs +16 -0
  70. package/bin/lean/release.mjs +30 -3
  71. package/bin/lean/release.test.mjs +36 -0
  72. package/bin/lean/render.mjs +17 -6
  73. package/bin/lean/reproquality.mjs +116 -0
  74. package/bin/lean/reproquality.test.mjs +85 -0
  75. package/bin/lean/review-trigger.mjs +8 -3
  76. package/bin/lean/sandbox-budget.test.mjs +27 -0
  77. package/bin/lean/schedd.mjs +40 -11
  78. package/bin/lean/schedd.test.mjs +12 -1
  79. package/bin/lean/testadequacy.mjs +97 -0
  80. package/bin/lean/testadequacy.test.mjs +92 -0
  81. package/bin/lean/testsandbox.mjs +202 -0
  82. package/bin/lean/testsandbox.test.mjs +157 -0
  83. package/bin/lean/toolplace.mjs +5 -2
  84. package/bin/lean/toolplace.test.mjs +6 -0
  85. package/bin/lean/verify.mjs +6 -1
  86. package/bin/lean/verify.test.mjs +18 -2
  87. package/bin/lean/warmtree.mjs +77 -0
  88. package/bin/lean/warmtree.test.mjs +81 -0
  89. package/bin/runner.mjs +6 -1
  90. package/bin/stats/conformance-outcomes.mjs +12 -2
  91. package/bin/stats/depth.mjs +24 -1
  92. package/bin/stats/depth.test.mjs +21 -1
  93. package/bin/stats/index.mjs +5 -2
  94. package/bin/stats/query.mjs +2 -1
  95. package/commands/cleanup.md +18 -0
  96. package/commands/fd-introspect.md +19 -0
  97. package/commands/milestone.md +5 -1
  98. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  99. package/commands/recover-orphans.md +31 -1
  100. package/commands/review-pr-staging.md +9 -0
  101. package/commands/review-pr.md +2 -0
  102. package/docs/CI.md +1 -1
  103. package/docs/CONFIG.md +26 -1
  104. package/docs/EVENTS.md +1 -0
  105. package/docs/ISSUE-WATCH.md +12 -3
  106. package/docs/eval/adversarial-bench.md +1 -1
  107. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  108. package/package.json +1 -1
  109. package/scripts/bench-lightlane.mjs +3 -2
  110. package/scripts/hotspots.sh +7 -4
  111. package/scripts/hotspots.test.sh +12 -0
  112. package/scripts/recover-orphans-stateless.test.sh +79 -0
  113. package/scripts/transition-label.sh +2 -0
  114. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
@@ -0,0 +1,137 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5419: user docs for user-facing surfaces. forge.yaml `docs: {required_for, paths, registries, surfaces, link_prefixes, link_check}`.
5
+ * Absent or empty `required_for` = off (library/CLI repos). A diff that touches a configured surface needs a docs change (a file under
6
+ * `paths`/`registries`) or a typed `docs: [{surface, justification}]` in the lane's result; every internal `/docs/...` link the diff adds
7
+ * must resolve (the repo's `link_check` command, else a docs file under `paths`). A milestone with user-facing children cannot close
8
+ * without a merged `docs` child. Deterministic, 0 LLM calls; core stays repo-agnostic (#1347), like routecheck.mjs and prodparity.mjs.
9
+ */
10
+ import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
11
+ import { globToRegex } from "../../scripts/ci-local/lib.mjs";
12
+ import { routePathOf } from "./routecheck.mjs";
13
+
14
+ export const DOCS_KINDS = Object.freeze(["api", "mcp", "dashboard", "cli", "sdk"]);
15
+ const DEFAULT_PATHS = ["docs/**", "**/docs/**"];
16
+ const PAGE_RE = /(?:^|\/)app\/(?:.*\/)?page\.[cm]?[jt]sx?$/;
17
+ const TEST_RE = /(?:^|\/)(?:__tests__|tests?)\/|\.(?:test|spec)\.[cm]?[jt]sx?$/;
18
+ const norm = (p) => String(p ?? "").trim().replace(/^\.\//, "");
19
+ const sq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
20
+ const list = (v) => (Array.isArray(v) ? v : typeof v === "string" ? v.replace(/^\[|\]$/g, "").split(",") : []).map((x) => String(x ?? "").trim().replace(/^(["'])(.*)\1$/, "$2").trim()).filter(Boolean);
21
+
22
+ /** forge.yaml docs: section -> {required_for, paths, registries, surfaces, link_prefixes, link_check} or null when off. */
23
+ export function parseDocsConfig(raw) {
24
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
25
+ const requiredFor = [...new Set(list(raw.required_for).map((k) => k.toLowerCase()).filter((k) => DOCS_KINDS.includes(k)))];
26
+ if (!requiredFor.length) return null;
27
+ const surfaces = {};
28
+ if (raw.surfaces && typeof raw.surfaces === "object" && !Array.isArray(raw.surfaces)) for (const [k, v] of Object.entries(raw.surfaces)) { const g = list(v); if (g.length && DOCS_KINDS.includes(k.toLowerCase())) surfaces[k.toLowerCase()] = g.map(norm); }
29
+ const prefixes = list(raw.link_prefixes);
30
+ const check = typeof raw.link_check === "string" ? raw.link_check.trim() : "";
31
+ return { required_for: requiredFor, paths: list(raw.paths).map(norm), registries: list(raw.registries).map(norm), surfaces, link_prefixes: prefixes.length ? prefixes : ["/docs"], link_check: check || null };
32
+ }
33
+
34
+ const anyGlob = (globs, f) => globs.some((g) => globToRegex(g).test(f));
35
+
36
+ /** Touched surfaces `{kind: [files]}` for the configured kinds: built-in Next route handlers (api) and dashboard pages, plus `surfaces` globs. */
37
+ export function userFacingSurfaces(files, cfg) {
38
+ const out = {};
39
+ if (!cfg) return out;
40
+ for (const f0 of files ?? []) {
41
+ const f = norm(f0);
42
+ if (!f || TEST_RE.test(f)) continue;
43
+ const kinds = new Set();
44
+ if (routePathOf(f)) kinds.add("api");
45
+ if (PAGE_RE.test(f) && /dashboard/i.test(f)) kinds.add("dashboard");
46
+ for (const [k, globs] of Object.entries(cfg.surfaces)) if (anyGlob(globs, f)) kinds.add(k);
47
+ for (const k of kinds) if (cfg.required_for.includes(k)) (out[k] ??= []).push(f);
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /** Sorted unique internal docs links (`href="/docs/x"`, `docsHref="/docs/x"`, `docsHref={"/docs/x"}`) on the added lines of a unified diff. */
53
+ export function docsLinks(diff, prefixes = ["/docs"]) {
54
+ const found = new Set(), re = /(?:href|docsHref)\s*=\s*\{?\s*["'`](\/[^"'`#?\s{}$]*)/g;
55
+ for (const line of String(diff ?? "").split("\n")) {
56
+ if (!line.startsWith("+") || line.startsWith("+++")) continue;
57
+ for (const m of line.matchAll(re)) if (prefixes.some((p) => m[1] === p || m[1].startsWith(`${p}/`))) found.add(m[1].replace(/\/+$/, "") || "/");
58
+ }
59
+ return [...found].sort();
60
+ }
61
+
62
+ /** True when some docs file under `paths` serves `link` (`rel.md|mdx`, `rel/index.*`, `rel/page.*`). */
63
+ export function linkResolves(link, cfg, files) {
64
+ const prefix = cfg.link_prefixes.find((p) => link === p || link.startsWith(`${p}/`)) ?? "";
65
+ const rel = link.slice(prefix.length).replace(/^\/+/, "");
66
+ const globs = cfg.paths.length ? cfg.paths : DEFAULT_PATHS;
67
+ const esc = rel.replace(/[.+^${}()|[\]\\]/g, "\\$&");
68
+ const re = new RegExp(`(?:^|/)${esc ? `${esc}(?:/(?:index|page|readme))?` : "(?:index|page|readme)"}\\.(?:mdx?|[jt]sx?)$`, "i");
69
+ return (files ?? []).some((f) => re.test(f) && anyGlob(globs, f));
70
+ }
71
+
72
+ /**
73
+ * Blocking failures (conformance.unimplemented): `docs_missing` (a touched surface with no docs change and no result.docs justification),
74
+ * `docs_link_broken` (a `/docs/...` link the diff adds that does not resolve). `run` is ({command}) => {rc, output}; `tracked` the repo's files.
75
+ */
76
+ export async function docsFailures({ cfg, files = [], diff = "", result = null, run = null, tracked = null }) {
77
+ if (!cfg) return [];
78
+ const C = OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, out = [];
79
+ const surfaces = userFacingSurfaces(files, cfg);
80
+ const docGlobs = [...(cfg.paths.length ? cfg.paths : DEFAULT_PATHS), ...cfg.registries];
81
+ const changedDocs = files.map(norm).filter((f) => anyGlob(docGlobs, f));
82
+ const given = Array.isArray(result?.docs) ? result.docs : [];
83
+ for (const [kind, fs] of Object.entries(surfaces)) {
84
+ if (changedDocs.length || given.some((d) => String(d?.surface ?? "").trim().toLowerCase() === kind && String(d?.justification ?? "").trim())) continue;
85
+ out.push({ code: C, kind: "docs_missing", detail: `${fs.slice(0, 3).join(", ")} changes the user-facing ${kind} surface (forge.yaml docs.required_for) but no docs file changed: add the page(s) under ${(cfg.paths.length ? cfg.paths : DEFAULT_PATHS).join(", ")}${cfg.registries.length ? ` and register them (${cfg.registries.join(", ")})` : ""}, or record docs: [{"surface":"${kind}","justification":"<why none>"}] in the result file` });
86
+ }
87
+ const links = docsLinks(diff, cfg.link_prefixes);
88
+ if (!links.length) return out;
89
+ if (cfg.link_check && run) {
90
+ let r;
91
+ try { r = await run({ command: `${cfg.link_check} ${links.map(sq).join(" ")}` }); r = r?.r ?? r; } catch (e) { r = { rc: 127, output: String(e?.message ?? e) }; }
92
+ if (r?.rc !== 0) {
93
+ const tail = String(r?.output ?? "").trim().split("\n").slice(-12).join("\n").slice(0, 1500);
94
+ out.push({ code: C, kind: "docs_link_broken", detail: `forge.yaml docs.link_check (\`${cfg.link_check}\`) exited ${r?.rc ?? "?"} for the docs link(s) ${links.join(", ")} this diff adds: create the page or fix the link${tail ? `:\n${tail}` : ""}` });
95
+ }
96
+ } else if (!cfg.link_check && tracked) {
97
+ const known = [...new Set([...tracked, ...files].map(norm))];
98
+ const bad = links.filter((l) => !linkResolves(l, cfg, known));
99
+ if (bad.length) out.push({ code: C, kind: "docs_link_broken", detail: `the diff links to ${bad.join(", ")} but no docs file under ${(cfg.paths.length ? cfg.paths : DEFAULT_PATHS).join(", ")} serves it (forge.yaml docs): create the page or fix the link` });
100
+ }
101
+ return out;
102
+ }
103
+
104
+ const names = (c) => (c.labels ?? []).map((l) => String(l?.name ?? l).toLowerCase());
105
+ /** Milestone children `{number, state, labels}` -> {ok, reasons}. User-facing = labelled `user-facing` or a configured kind; the docs child is labelled `docs`. */
106
+ export function milestoneDocsGate({ children = [], cfg }) {
107
+ if (!cfg) return { ok: true, gated: false, reasons: [] };
108
+ const kinds = new Set(["user-facing", ...cfg.required_for]);
109
+ const docs = children.filter((c) => names(c).includes("docs"));
110
+ const facing = children.filter((c) => !docs.includes(c) && names(c).some((n) => kinds.has(n)));
111
+ if (!facing.length) return { ok: true, gated: false, reasons: [] };
112
+ if (!docs.length) return { ok: false, gated: true, reasons: [`user-facing children (${facing.map((c) => `#${c.number}`).join(", ")}) have no docs child: create an issue labelled \`docs\` in the milestone`] };
113
+ const open = docs.filter((c) => String(c.state).toLowerCase() !== "closed");
114
+ return open.length ? { ok: false, gated: true, reasons: [`docs child ${open.map((c) => `#${c.number}`).join(", ")} is not merged yet`] } : { ok: true, gated: true, reasons: [] };
115
+ }
116
+
117
+ /** `forgedock docs gate --milestone T --repo o/r`: exits 1 when the milestone's docs gate blocks; 0 when off or satisfied. */
118
+ export async function docsFromCli(argv, deps = {}) {
119
+ const val = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : null; };
120
+ const print = deps.print ?? ((t) => console.log(t));
121
+ const usage = "usage: forgedock docs gate --milestone T [--repo o/r]";
122
+ if (argv[0] !== "gate" || !val("--milestone")) throw new Error(usage);
123
+ const cfg = parseDocsConfig(deps.config ?? (await import("../engine-cli.mjs")).readEnvConfig(deps.cwd ?? process.cwd()).docsConfig);
124
+ if (!cfg) { print("docs: forge.yaml docs.required_for is not set; not gated"); return 0; }
125
+ const repo = val("--repo") ?? deps.repo;
126
+ if (!repo) throw new Error("docs gate needs the repo: pass --repo owner/repo");
127
+ const io = deps.io ?? (await import("./effects.mjs")).makeLeanIo({ repo });
128
+ const { findMilestone } = await import("./acceptance.mjs");
129
+ const ms = await findMilestone({ io, repo, title: val("--milestone") });
130
+ if (!ms) throw new Error(`no milestone titled ${val("--milestone")}`);
131
+ const children = JSON.parse(String(await io.gh(["api", `repos/${repo}/issues?milestone=${ms.number}&state=all&per_page=100`, "--jq", "[.[] | select(.pull_request == null) | {number, state, labels: [.labels[].name]}]"])) || "[]");
132
+ const g = milestoneDocsGate({ children, cfg });
133
+ if (!g.gated) print("docs: milestone has no user-facing children; not gated");
134
+ else if (g.ok) print(`docs: pass (${ms.title})`);
135
+ else for (const r of g.reasons) print(`docs: BLOCKED: ${r}`);
136
+ return g.ok ? 0 : 1;
137
+ }
@@ -0,0 +1,78 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { parseDocsConfig, userFacingSurfaces, docsLinks, docsFailures, milestoneDocsGate, docsFromCli } from "./docsgate.mjs";
6
+ import { docsPlanNote, domainChecksBlock } from "./prompts.mjs";
7
+ import { pathDomains } from "./review-trigger.mjs";
8
+
9
+ const cfg = parseDocsConfig({ required_for: "[api, dashboard]", paths: ["web/docs/**"], registries: ["web/public/llms.txt"] });
10
+ // The shape of the AlterLab Hands dashboard PR (#40276): a dashboard page linking a docs page that does not exist.
11
+ const handsFiles = ["web/app/dashboard/hands/page.tsx", "web/app/dashboard/hands/HandsDashPage.tsx"];
12
+ const handsDiff = "+++ b/web/app/dashboard/hands/page.tsx\n+<HandsDashPage docsHref=\"/docs/hands\" />\n+<a href=\"/docs/hands/credentials\">How it works</a>\n+<a href=\"/pricing\">x</a>\n";
13
+
14
+ describe("docs gate (#5419)", () => {
15
+ it("is off without required_for (library/CLI repos)", async () => {
16
+ assert.equal(parseDocsConfig(undefined), null);
17
+ assert.equal(parseDocsConfig({ paths: ["docs/**"] }), null);
18
+ assert.equal(parseDocsConfig({ required_for: "bogus" }), null);
19
+ assert.deepEqual(await docsFailures({ cfg: null, files: handsFiles, diff: handsDiff }), []);
20
+ assert.equal(docsPlanNote(null), "");
21
+ });
22
+ it("detects configured surfaces only, ignoring tests", () => {
23
+ assert.deepEqual(Object.keys(userFacingSurfaces(["web/app/api/x/route.ts", "web/app/dashboard/p/page.tsx", "web/app/api/x/route.test.ts"], cfg)).sort(), ["api", "dashboard"]);
24
+ assert.deepEqual(userFacingSurfaces(["src/cli.ts"], parseDocsConfig({ required_for: ["cli"], surfaces: { cli: ["src/cli.ts"] } })), { cli: ["src/cli.ts"] });
25
+ assert.deepEqual(userFacingSurfaces(["web/app/api/x/route.ts"], parseDocsConfig({ required_for: ["cli"] })), {});
26
+ });
27
+ it("extracts only added internal docs links", () => {
28
+ assert.deepEqual(docsLinks(handsDiff), ["/docs/hands", "/docs/hands/credentials"]);
29
+ assert.deepEqual(docsLinks("-<a href=\"/docs/old\">\n+<a href=\"https://x.io/docs/a\">"), []);
30
+ });
31
+ it("replay: the Hands dashboard diff fails docs_missing and the link gate, and its plan carries R-docs", async () => {
32
+ const f = await docsFailures({ cfg, files: handsFiles, diff: handsDiff, tracked: ["web/docs/api/index.mdx"] });
33
+ assert.deepEqual(f.map((x) => x.kind).sort(), ["docs_link_broken", "docs_missing"]);
34
+ assert.match(docsPlanNote(cfg), /R-docs/);
35
+ assert.match(docsPlanNote(cfg), /web\/docs\/\*\*/);
36
+ });
37
+ it("passes when the pages exist, or the repo link_check exits 0, or the change is justified", async () => {
38
+ const files = [...handsFiles, "web/docs/hands/index.mdx", "web/docs/hands/credentials.mdx"];
39
+ assert.deepEqual(await docsFailures({ cfg, files, diff: handsDiff, tracked: [] }), []);
40
+ const c2 = parseDocsConfig({ required_for: ["dashboard"], paths: ["web/docs/**"], link_check: "bash chk.sh" });
41
+ let ran; const run = async ({ command }) => { ran = command; return { rc: 0 }; };
42
+ assert.deepEqual(await docsFailures({ cfg: c2, files: [...handsFiles, "web/docs/x.mdx"], diff: handsDiff, run }), []);
43
+ assert.match(ran, /^bash chk\.sh '\/docs\/hands' '\/docs\/hands\/credentials'$/);
44
+ const bad = await docsFailures({ cfg: c2, files: ["web/docs/x.mdx"], diff: handsDiff, run: async () => ({ rc: 1, output: "404 /docs/hands" }) });
45
+ assert.equal(bad[0].kind, "docs_link_broken");
46
+ const crashed = await docsFailures({ cfg: c2, files: [], diff: handsDiff, run: async () => { throw new Error("nope"); } });
47
+ assert.match(crashed[0].detail, /exited 127/);
48
+ assert.deepEqual(await docsFailures({ cfg, files: handsFiles, result: { docs: [{ surface: "dashboard", justification: "internal page" }] }, diff: "" }), []);
49
+ });
50
+ it("adds the docs domain and its reviewer check only for a configured surface", () => {
51
+ assert.ok(pathDomains(handsFiles, { docs: cfg })?.includes("docs"));
52
+ assert.ok(!pathDomains(handsFiles)?.includes("docs"));
53
+ assert.match(domainChecksBlock(["docs"]), /docs that contradict the code/);
54
+ });
55
+ it("blocks milestone close until a docs child is merged", () => {
56
+ const ui = { number: 1, state: "closed", labels: ["dashboard"] };
57
+ assert.equal(milestoneDocsGate({ children: [ui], cfg: null }).ok, true);
58
+ assert.equal(milestoneDocsGate({ children: [{ number: 2, state: "open", labels: ["chore"] }], cfg }).gated, false);
59
+ assert.match(milestoneDocsGate({ children: [ui], cfg }).reasons[0], /no docs child/);
60
+ assert.match(milestoneDocsGate({ children: [ui, { number: 3, state: "open", labels: ["docs"] }], cfg }).reasons[0], /not merged/);
61
+ assert.equal(milestoneDocsGate({ children: [ui, { number: 3, state: "closed", labels: ["docs"] }], cfg }).ok, true);
62
+ });
63
+ it("docs gate CLI exits 1 on a blocked milestone and 0 when off", async () => {
64
+ const out = [], print = (t) => out.push(t);
65
+ assert.equal(await docsFromCli(["gate", "--milestone", "M", "--repo", "o/r"], { config: undefined, print }), 0);
66
+ assert.equal(await docsFromCli(["gate", "--milestone", "M", "--repo", "o/r"], { config: cfg, print, io: { gh: async (a) => { if (String(a[1]).includes("issues?milestone")) return JSON.stringify([{ number: 1, state: "closed", labels: ["dashboard"] }]); return JSON.stringify([{ number: 7, title: "M" }]); } } }), 1);
67
+ });
68
+ });
69
+
70
+ import { precheck } from "./conformance.mjs";
71
+ it("precheck: configured docs.paths files are authorized, others stay scope creep (#5419)", () => {
72
+ const contract = { requirements: [], deliverables: [{ id: "D1", path: "src/a.mjs" }], preserve: [], validate: [] };
73
+ const base = { contract, result: { status: "fixed", requirements: [], validation: [], tests: [] }, ignore: [] };
74
+ const withDocs = precheck({ ...base, changedFiles: ["src/a.mjs", "docs/api/x.md"], docsPaths: ["docs/**"] });
75
+ assert.ok(!withDocs.failures.some((f) => f.kind === "scope_creep"));
76
+ const without = precheck({ ...base, changedFiles: ["src/a.mjs", "docs/api/x.md"] });
77
+ assert.ok(without.failures.some((f) => f.kind === "scope_creep"));
78
+ });
@@ -14,6 +14,7 @@ import { makeProjector } from "../engine/projector.mjs";
14
14
  import { makeLedger, countLiveLanes, ledgerRoot } from "./ledger.mjs";
15
15
  import { makeDepCache } from "./depcache.mjs";
16
16
  import { makeHeavyIo } from "./heavy.mjs";
17
+ import { diskLow } from "./admission.mjs";
17
18
  import { gatherContextFacts } from "./context.mjs";
18
19
  import { makePitfallStore } from "./pitfalls.mjs";
19
20
  import { enumeratingTests, missingEntries } from "./enumerating.mjs";
@@ -160,6 +161,11 @@ export const runTmpRoot = () => join(homedir(), ".forge", "tmp", "runs");
160
161
  const OWNER = ".forge-run-owner";
161
162
  const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e?.code !== "ESRCH"; } };
162
163
 
164
+ /** The run-owner marker (#5421): any scratch dir ForgeDock creates under ~/.forge/tmp carries it so gc can reclaim it once its owner is dead. */
165
+ export function markOwned(dir, { issue = null, now = () => Date.now(), host = hostname() } = {}) {
166
+ try { writeFileSync(join(dir, OWNER), JSON.stringify({ issue, pid: process.pid, host, created: now() })); } catch { /* best effort: unmarked dirs are only reported */ }
167
+ }
168
+
163
169
  /** Per-run scratch dirs under ~/.forge/tmp/runs/<issue>-<run>/. Only dirs carrying our owner marker are ever removed. */
164
170
  export function makeRunTmp({ root = runTmpRoot(), now = () => Date.now(), alive = pidAlive, host = hostname() } = {}) {
165
171
  const inside = (d) => { const r = resolve(d); return r.startsWith(resolve(root) + sep) && !r.slice(resolve(root).length + 1).includes(sep); };
@@ -216,6 +222,27 @@ export function killLedgerPid(pid, marker, { kill = process.kill.bind(process),
216
222
  try { kill(-n, "SIGTERM"); return true; } catch { try { kill(n, "SIGTERM"); return true; } catch (e) { return e?.code === "ESRCH"; } }
217
223
  }
218
224
 
225
+ /**
226
+ * Heavy-step gate on free disk (#5421): below `minFreeGb()` the guard runs `gc()` (owned GC) once, re-checks, and, if the
227
+ * disk is still low, refuses the step with a DISK_LOW error (an image build must not fill the host). Otherwise it passes
228
+ * through to `heavy.acquire`. A failed gc or probe never refuses.
229
+ */
230
+ export function guardHeavyDisk(heavy, { host, minFreeGb = () => null, gc = async () => {} } = {}) {
231
+ if (!heavy) return heavy;
232
+ return {
233
+ ...heavy,
234
+ async acquire(entry, cfg) {
235
+ const min = await minFreeGb();
236
+ if ((await diskLow({ host, minFreeGb: min })).low) {
237
+ try { await gc(); } catch { /* the re-check decides */ }
238
+ const again = await diskLow({ host, minFreeGb: min });
239
+ if (again.low) { const e = new Error(`host disk low: ${again.reasons.join(", ")}`); e.code = "DISK_LOW"; throw e; }
240
+ }
241
+ return heavy.acquire(entry, cfg);
242
+ },
243
+ };
244
+ }
245
+
219
246
  /** Real host probes for admission (#4105). MemAvailable from /proc/meminfo (fallback os.freemem), statfs for tmp. */
220
247
  export function makeHostProbe() {
221
248
  return {
@@ -236,6 +263,8 @@ export function makeHostProbe() {
236
263
  cores: () => cpus().length || 1,
237
264
  /** Live lanes on this host from the ledger (#4182), this lane included once it registered. */
238
265
  activeLanes: () => countLiveLanes({ root: ledgerRoot(), host: hostname() }),
266
+ /** Filesystems a lane fills (#5421): the worktree root and ~/.forge. */
267
+ hygienePaths: (cwd = process.cwd()) => [...new Set([join(cwd, ".claude", "worktrees"), join(homedir(), ".forge")])],
239
268
  tmpPaths: () => [...new Set([join(homedir(), ".forge", "tmp"), tmpdir(), "/tmp"].filter((x) => existsSync(x) || x === join(homedir(), ".forge", "tmp")))],
240
269
  };
241
270
  }
@@ -306,7 +335,7 @@ export function makeGhCache({ root = null, tmp = tmpdir() } = {}) {
306
335
  drop(dir);
307
336
  if (disposed) return;
308
337
  if (root) { dir = join(root, `gh-cache-${++n}`); return; }
309
- try { dir = mkdtempSync(join(tmp, "forge-gh-cache-")); made.add(dir); } catch { dir = null; }
338
+ try { dir = mkdtempSync(join(tmp, "forge-gh-cache-")); made.add(dir); markOwned(dir); } catch { dir = null; }
310
339
  },
311
340
  dispose() { disposed = true; for (const d of [...made]) drop(d); },
312
341
  };
@@ -326,7 +355,7 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
326
355
  };
327
356
  return {
328
357
  ghCache: (root) => makeGhCache({ root }),
329
- gh: run("gh"), git: run("git"), docker: run("docker"), killGroup: async (pid, marker) => killLedgerPid(pid, marker), ledger: (opts) => makeLedger(opts), runTmp: makeRunTmp(), host: makeHostProbe(), heavy: makeHeavyIo({ host: makeHostProbe() }), projector: makeProjector({ gh: base.gh }, { repo }), runner: makeLeanRunner({ subagentModel }), waitCiGreen: base.waitCiGreen,
358
+ gh: run("gh"), git: run("git"), docker: run("docker"), killGroup: async (pid, marker) => killLedgerPid(pid, marker), ledger: (opts) => makeLedger(opts), runTmp: makeRunTmp(), host: makeHostProbe(), heavy: guardHeavyDisk(makeHeavyIo({ host: makeHostProbe() }), { host: makeHostProbe(), minFreeGb: async () => (await import("../gc.mjs")).readHygiene(process.cwd()).min_free_gb, gc: async () => { const g = await import("../gc.mjs"); return g.runOwnedGc({ probes: g.makeGcProbes({ cwd: process.cwd() }), hygiene: g.readHygiene(process.cwd()), budgetMs: 60000 }); } }), projector: makeProjector({ gh: base.gh }, { repo }), runner: makeLeanRunner({ subagentModel }), waitCiGreen: base.waitCiGreen,
330
359
  /** Shared dependency cache (#4220): the repo's own package manager, argv only, bounded by the cache's timeout. */
331
360
  deps: makeDepCache({ exec: async (cmd, args, { cwd, env, timeoutMs } = {}) => String((await pexec(cmd, args, { cwd, env: { ...process.env, ...(env ?? {}) }, timeout: timeoutMs ?? 0, maxBuffer: 100 * 1024 * 1024 })).stdout) }),
332
361
  /** Names of the checks the base branch requires: classic protection plus rulesets (#4158). [] when neither has any. */
@@ -43,18 +43,42 @@ export function exportNames(text, path = "") {
43
43
  return [...out];
44
44
  }
45
45
 
46
- /** Line (1-based) of the first literal/key mention of any of `names` in `text`, and the distinct names mentioned. */
47
- function mentions(text, names) {
46
+ const PATH_CONTEXT = /\.[cm]?[jt]sx?\b|readdir|import\(/;
47
+ const SUFFIXED = /\.[cm]?[jt]sx?["'`]$/;
48
+ /** Local names bound by an ES import (named, default or namespace). */
49
+ function importedNames(text) {
50
+ const out = new Set();
51
+ for (const m of text.matchAll(/import\s+(?:([A-Za-z_$][\w$]*)\s*,?\s*)?(?:\*\s+as\s+([A-Za-z_$][\w$]*)|\{([^}]*)\})?\s*from\s*["']/g)) {
52
+ for (const n of [m[1], m[2]]) if (n) out.add(n);
53
+ for (const part of (m[3] ?? "").split(",")) { const n = /([A-Za-z_$][\w$]*)\s*$/.exec(part.trim())?.[1]; if (n) out.add(n); }
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /**
59
+ * Line (1-based) of the first literal/key mention of any of `names` in `text`, and the distinct names mentioned. `dir` (files groups,
60
+ * #5480): a bare word that merely equals a stem is not a mention; it needs an extension, or readdir / import( / the directory's name
61
+ * within two lines, and a line asserting `.has(x)` of an imported Set is never one.
62
+ */
63
+ function mentions(text, names, dir) {
48
64
  const hit = new Set();
49
65
  let line = 0;
66
+ const rows = dir ? text.split("\n") : [], imported = dir ? importedNames(text) : null;
67
+ const dirRe = dir ? new RegExp(`(?<![\\w$])${esc(dir)}(?![\\w$])`) : null;
50
68
  for (const n of names) {
51
69
  if (n.length < MIN_NAME) continue;
52
- const re = new RegExp(`(["'\`])${esc(n)}\\1|(?:^|[{,\\s])${esc(n)}\\s*:(?!:)`, "m");
53
- const m = re.exec(text);
54
- if (!m) continue;
55
- hit.add(n);
56
- const l = text.slice(0, m.index).split("\n").length;
57
- if (!line || l < line) line = l;
70
+ const re = new RegExp(`(["'\`])${esc(n)}${dir ? "(?:\\.[cm]?[jt]sx?)?" : ""}\\1|(?:^|[{,\\s])${esc(n)}\\s*:(?!:)`, "gm");
71
+ for (const m of text.matchAll(re)) {
72
+ const l = text.slice(0, m.index).split("\n").length;
73
+ if (dir) {
74
+ if ([...rows[l - 1].matchAll(/([A-Za-z_$][\w$]*)\.has\(/g)].some((x) => imported.has(x[1]))) continue;
75
+ const near = rows.slice(Math.max(0, l - 3), l + 2).join("\n");
76
+ if (!SUFFIXED.test(m[0]) && !PATH_CONTEXT.test(near) && !dirRe.test(near)) continue;
77
+ }
78
+ hit.add(n);
79
+ if (!line || l < line) line = l;
80
+ break;
81
+ }
58
82
  }
59
83
  return { hit, line };
60
84
  }
@@ -98,14 +122,14 @@ async function loadTests(git, cwd) {
98
122
  }
99
123
 
100
124
  /** Tests enumerating one group: [{test, line, why}]. `exports` groups also match Object.keys/entries of an import of `module`. */
101
- function enumerators(tests, { module, names, kind }, pkgs) {
125
+ function enumerators(tests, { module, names, kind, strict }, pkgs) {
102
126
  const out = [];
103
127
  const usable = names.filter((n) => n.length >= MIN_NAME);
104
128
  if (usable.length < 2) return out;
105
129
  const need = Math.min(3, usable.length);
106
130
  for (const t of tests) {
107
131
  if (t.path === module) continue;
108
- const { hit, line } = mentions(t.text, usable);
132
+ const { hit, line } = mentions(t.text, usable, kind === "files" && strict ? basename(module) : undefined);
109
133
  if (hit.size >= need) { out.push({ test: t.path, line, why: `literal list of ${hit.size} sibling ${kind === "files" ? "file names" : "export names"}` }); continue; }
110
134
  if (kind !== "exports") continue;
111
135
  for (const b of importBindings(t.text, t.path, module, pkgs)) {
@@ -116,6 +140,8 @@ function enumerators(tests, { module, names, kind }, pkgs) {
116
140
  return out.slice(0, MAX_TESTS_PER_MODULE);
117
141
  }
118
142
 
143
+ /** #5480: a directory of source files has stems that collide with common words, so its lists need path context; data files (locale namespaces) do not. */
144
+ const strictDir = (files, dir) => files.some((f) => dirname(f) === dir && SOURCE_RE.test(f) && !isTestPath(f));
119
145
  const fileGroup = (files, dir, exclude = new Set()) => [...new Set(files.filter((f) => dirname(f) === dir && !isTestPath(f) && !exclude.has(f) && stem(f) !== "index").map(stem))];
120
146
 
121
147
  /**
@@ -132,8 +158,8 @@ export async function enumeratingTests({ git, cwd, paths = [] }) {
132
158
  if (tracked.has(raw) && SOURCE_RE.test(raw) && !isTestPath(raw)) {
133
159
  let text = ""; try { text = fs.readFileSync(join(cwd, raw), "utf8"); } catch { /* sparse */ }
134
160
  groups.push({ module: raw, names: exportNames(text, raw), kind: "exports" });
135
- groups.push({ module: dirname(raw), names: fileGroup(files, dirname(raw)), kind: "files" });
136
- } else if (files.some((f) => dirname(f) === raw)) groups.push({ module: raw, names: fileGroup(files, raw), kind: "files" });
161
+ groups.push({ module: dirname(raw), names: fileGroup(files, dirname(raw)), kind: "files", strict: strictDir(files, dirname(raw)) });
162
+ } else if (files.some((f) => dirname(f) === raw)) groups.push({ module: raw, names: fileGroup(files, raw), kind: "files", strict: strictDir(files, raw) });
137
163
  for (const g of groups) for (const e of enumerators(tests, g, pkgs)) {
138
164
  const k = `${g.module}\0${e.test}`;
139
165
  if (!seen.has(k)) { seen.add(k); out.push({ module: g.module, ...e }); }
@@ -169,7 +195,7 @@ export async function missingEntries({ git, cwd, base }) {
169
195
  const newFiles = [...added].filter((f) => !isTestPath(f) && !SKIP_RE.test(f));
170
196
  for (const dir of [...new Set(newFiles.map(dirname))]) {
171
197
  const fresh = newFiles.filter((f) => dirname(f) === dir).map(stem).filter((s) => s.length >= MIN_NAME && s !== "index");
172
- if (fresh.length) groups.push({ module: dir, names: fileGroup(files, dir, added), fresh, kind: "files" });
198
+ if (fresh.length) groups.push({ module: dir, names: fileGroup(files, dir, added), fresh, kind: "files", strict: strictDir(files, dir) });
173
199
  }
174
200
  const out = [];
175
201
  for (const g of groups.slice(0, MAX_MODULES)) {
@@ -95,3 +95,23 @@ describe("enumerating tests (#4322)", () => {
95
95
  assert.deepEqual(await enumeratingTests({ git: bad, cwd: d, paths: ["x"] }), []);
96
96
  });
97
97
  });
98
+
99
+ describe("#5480 bare words that equal sibling stems are not a directory enumeration", () => {
100
+ const SRC = { "bin/lean/run.mjs": "", "bin/lean/watch.mjs": "", "bin/lean/release.mjs": "", "bin/lean/fresh.mjs": "export const fresh = 1;\n" };
101
+ const base = (extra) => repo({ ...Object.fromEntries(Object.entries(SRC).filter(([k]) => !k.endsWith("fresh.mjs"))), ...extra });
102
+ const add = async (d) => { put(d, { "bin/lean/fresh.mjs": SRC["bin/lean/fresh.mjs"] }); sh(d, "checkout", "-qb", "lane"); sh(d, "add", "-A"); sh(d, "commit", "-qm", "lane"); return missingEntries({ git: gitIn(d), cwd: d, base: "main" }); };
103
+ it("bare-word stems are not an enumeration (unrelated lists, imported Set membership)", async () => {
104
+ const d = base({
105
+ "bin/auth/a.test.mjs": "import { CMDS } from './x.mjs';\nfor (const c of [\"run\", \"watch\", \"release\"]) assert.ok(CMDS.has(c), c);\n",
106
+ "bin/lean/guards.test.mjs": "const guards = [\"run\", \"watch\", \"release\"];\n",
107
+ });
108
+ assert.deepEqual(await add(d), []);
109
+ });
110
+ it("a literal list of file names, with a suffix or readdir, still is one", async () => {
111
+ const d = base({
112
+ "bin/lean/a.test.mjs": "const FILES = [\"run.mjs\", \"watch.mjs\", \"release.mjs\"];\n",
113
+ "bin/lean/b.test.mjs": "const got = readdirSync(dir);\nassert.deepEqual(got, [\"run\", \"watch\", \"release\"]);\n",
114
+ });
115
+ assert.deepEqual((await add(d)).map((m) => m.test).sort(), ["bin/lean/a.test.mjs", "bin/lean/b.test.mjs"]);
116
+ });
117
+ });
@@ -878,7 +878,7 @@ describe("host capabilities in placement (#4542)", () => {
878
878
  assert.deepEqual(detectNeeds(t, exec), ["promtool"]);
879
879
  });
880
880
 
881
- it("#4785 orchestrate: a remote lane that ends env.tool_missing is relaunched locally", async () => {
881
+ it("#4785/#5423 orchestrate: a remote lane that ends env.tool_missing is retried remotely once (sandbox provisioned), see recovery.test.mjs for the host fallback", async () => {
882
882
  const calls = [];
883
883
  const rows = await orchestrate({ issues: [5], parallel: 2, recovery: { maxAttempts: 1 }, readBody: async () => "",
884
884
  remote: { max: 2, isRemote: () => true, place: () => ({ where: "remote", reason: "mode remote" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 },
@@ -886,8 +886,8 @@ describe("host capabilities in placement (#4542)", () => {
886
886
  calls.push({ placement: ctx.placement?.where, reason: ctx.placement?.reason, recover: ctx.recover?.code ?? null });
887
887
  return ctx.recover ? { terminalReason: "merged", pr: 9 } : { terminalReason: "needs-human", code: "env.tool_missing", detail: "promtool: command not found" };
888
888
  } });
889
- assert.deepEqual(calls.map((c) => [c.placement, c.recover]), [["remote", null], ["local", "env.tool_missing"]]);
890
- assert.equal(calls[1].reason, "host capability: recovering env.tool_missing");
889
+ assert.deepEqual(calls.map((c) => [c.placement, c.recover]), [["remote", null], ["remote", "env.tool_missing"]]);
890
+ assert.equal(calls[1].reason, "retry remotely after sandbox provisioning");
891
891
  assert.equal(rows.find((r) => r.issue === 5).outcome, "merged");
892
892
  });
893
893
 
@@ -0,0 +1,93 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Investigation decides pipeline depth (#5426, builds on the light lane #4450). By default (forge.yaml `lean.light.source:
5
+ * investigation`; `text` is the kill-switch) the first builder call is investigation-only: it writes investigation.md and `.forge-lean/triage.json`
6
+ * ({files, size, risk, decision_needed}). Eligibility for the light lane is then computed from those grounded findings
7
+ * (predicted non-test files, size, risk, hotspot) by the same `lightEligibility` rules; the text heuristic over the issue body
8
+ * stays only as a `pre_text_*` shadow signal. An eligible issue fast-forwards: one implement session, deterministic gates
9
+ * (`runLightStep`), merge; the stages it skips are named. Anything else continues into the full lane's contract step.
10
+ * `source: investigation` with `mode: shadow` changes nothing: it logs FASTFORWARD_ELIGIBILITY after the normal plan session.
11
+ * Pure helpers and prompts: no I/O, no model call.
12
+ */
13
+ import { lightEligibility, LIGHT_SOURCES } from "./light.mjs";
14
+ import { builderPlanPrompt, LEAN_DIR, CONTRACT_FILE } from "./prompts.mjs";
15
+
16
+ export const TRIAGE_FILE = `${LEAN_DIR}/triage.json`;
17
+
18
+ /** `lean.light.source` of a parsed light config: investigation (default; investigate always, the verdict picks the depth) or text (the kill-switch). */
19
+ export const fastForwardSource = (cfg) => (LIGHT_SOURCES.includes(cfg?.source) ? cfg.source : "investigation");
20
+
21
+ const PATH_RE = /[A-Za-z0-9_@.][A-Za-z0-9_@.\-]*(?:\/[A-Za-z0-9_@.\-]+)*\.[A-Za-z0-9]{1,8}\b/g;
22
+ const SECTION_RE = /^###\s+Affected Files\s*$([\s\S]*?)(?=^###\s|(?![\s\S]))/m;
23
+ const uniq = (xs) => [...new Set(xs)];
24
+
25
+ /** Paths named in the `### Affected Files` section of investigation.md (deterministic fallback when triage.json is absent). */
26
+ export function affectedFilesOf(md) {
27
+ const sec = SECTION_RE.exec(String(md ?? ""))?.[1] ?? "";
28
+ const out = [];
29
+ for (const line of sec.split("\n")) {
30
+ if (!/^\s*[-*]/.test(line)) continue;
31
+ const first = line.replace(/^\s*[-*]\s*/, "").replace(/`/g, "").match(PATH_RE)?.[0]; // the first token names the file; later ones are prose
32
+ if (first && !/^\d/.test(first) && (first.includes("/") || /\.(m?[jt]sx?|py|go|rs|md|json|ya?ml|sh|css|sql)$/.test(first))) out.push(first.replace(/^\.\//, ""));
33
+ }
34
+ return uniq(out);
35
+ }
36
+
37
+ /**
38
+ * triage.json text + investigation.md -> {files, size, risk, decisionNeeded, source}. A malformed or absent triage falls back to
39
+ * the Affected Files section with an unknown size; a size outside S|M|L is unknown.
40
+ */
41
+ export function parseTriage(triageRaw, md = "") {
42
+ let t = null;
43
+ try { const j = JSON.parse(String(triageRaw ?? "")); t = j && typeof j === "object" && !Array.isArray(j) ? j : null; } catch { /* fall back */ }
44
+ const files = t && Array.isArray(t.files) ? uniq(t.files.map((f) => String(f ?? "").trim().replace(/^\.\//, "")).filter(Boolean)) : affectedFilesOf(md);
45
+ const size = ["S", "M", "L"].includes(String(t?.size ?? "").toUpperCase()) ? String(t.size).toUpperCase() : null;
46
+ return { files, size, risk: t?.risk === true, decisionNeeded: t?.decision_needed === true, source: t ? "triage" : "affected_files" };
47
+ }
48
+
49
+ /** Eligibility from the investigation's findings; the text verdict is recorded as the shadow `pre_text_*` signal. */
50
+ export function fastForwardEligibility({ title = "", body = "", labels = [], triage = null, textFiles = [], riskPaths = [], hotspots = [], cfg = {} } = {}) {
51
+ const t = triage ?? { files: [], size: null, risk: false, decisionNeeded: false };
52
+ const text = lightEligibility({ title, body, labels, predictedFiles: textFiles, cfg: { ...cfg, mode: cfg.mode === "off" ? "off" : "shadow" } });
53
+ const extraHard = [
54
+ ...(t.risk ? [{ code: "risk", detail: "the investigation flagged the change as risky" }] : []),
55
+ ...(t.decisionNeeded ? [{ code: "decision", detail: "the investigation says a decision is needed" }] : []),
56
+ ];
57
+ return lightEligibility({ title, body, labels, predictedFiles: t.files, riskPaths, hotspots, cfg, source: "investigation", size: t.size, extraHard, preText: text.verdict });
58
+ }
59
+
60
+ /** The stages a fast-forwarded lane skips and why: [{stage, why}]. */
61
+ export function skippedStages(elig = null) {
62
+ const why = `investigation predicts a small change (${elig?.signals?.find((s) => s.code === "files_named")?.detail ?? "?"} non-test file(s), no risk path or hotspot)`;
63
+ return ["plan", "contract freeze", "multi-session review"].map((stage) => ({ stage, why }));
64
+ }
65
+
66
+ /** One line for the trajectory and the FORGE:LITE receipt. */
67
+ export const skippedLine = (elig) => `Fast-forward: skipped ${skippedStages(elig).map((x) => x.stage).join(", ")}; ${skippedStages(elig)[0].why}`;
68
+
69
+ const TRIAGE_RULE = `3. Write ${TRIAGE_FILE}: {"files":["<non-test file you predict will change>"],"size":"S|M|L","risk":false,"decision_needed":false}. "files" are repo-relative non-test paths from your Affected Files; size S = a small fix in at most a couple of files; risk true when the fix touches auth, security, payments, migrations, CI or public API shape; decision_needed true when a design or product choice must be made first. The engine reads it to pick the pipeline depth.
70
+
71
+ Stop after the files above. Do not write ${CONTRACT_FILE} yet: the engine tells you whether to continue.`;
72
+
73
+ /** Call 1 when source is investigation: step 1 of the plan prompt (investigation, close rules, block rules) plus the triage file. */
74
+ export function investigationOnlyPrompt(n, opts = {}) {
75
+ const full = builderPlanPrompt(n, opts);
76
+ const cut = full.indexOf("\n2. Otherwise write"), blocks = full.indexOf('"blocked" needs a typed');
77
+ if (cut < 0 || blocks < 0) return full;
78
+ return `${full.slice(0, cut)}\n2. Do not write the contract yet.\n${TRIAGE_RULE}\n\n${full.slice(blocks)}`;
79
+ }
80
+
81
+ /** Call 2 (same session) when the issue is not fast-forwarded: the contract step of the plan prompt. */
82
+ export function contractStepPrompt(n, opts = {}) {
83
+ const full = builderPlanPrompt(n, opts);
84
+ const cut = full.indexOf("2. Otherwise write");
85
+ return `Your investigation is written and the engine is continuing with the full lane. This is still PLANNING ONLY: no code edits, no commits.\n\n${cut < 0 ? full : full.slice(cut)}`;
86
+ }
87
+
88
+ /** The light build prompt's lead-in when it resumes the investigation session. */
89
+ export const FF_BUILD_LEAD = `The investigation step is complete and the engine fast-forwards this issue (small, no risk path): the planning-only rule no longer applies. Implement the fix now.\n\n`;
90
+
91
+ /** The FASTFORWARD_ELIGIBILITY run-log event (read by `stats --depth`); `shadow` = logged beside a normal full-lane plan session. */
92
+ export const fastForwardEvent = (elig, triage, { shadow = false } = {}) => ({ event: "FASTFORWARD_ELIGIBILITY", mode: elig.mode, verdict: elig.verdict, eligible: elig.eligible, light: elig.light, shadow,
93
+ files: triage.files.length, size: triage.size, triage: triage.source, reasons: elig.reasons, signals: elig.signals });
@@ -0,0 +1,73 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { affectedFilesOf, parseTriage, fastForwardEligibility, skippedStages, skippedLine, investigationOnlyPrompt, contractStepPrompt, fastForwardSource, TRIAGE_FILE } from "./fastforward.mjs";
6
+ import { parseLightConfig } from "./light.mjs";
7
+
8
+ const CFG = { mode: "on", maxLines: 40, maxFiles: 2 };
9
+ const MD = "### Affected Files\n- `bin/lean/light.mjs`: eligibility\n- bin/lean/light.test.mjs\n- docs/CONFIG.md (see section 3)\n\n### Sibling Sweep\n- other/file.mjs\n";
10
+ const triage = (o = {}) => ({ files: ["src/a.mjs"], size: "S", risk: false, decisionNeeded: false, ...o });
11
+ const codes = (e) => e.reasons.map((r) => r.code);
12
+
13
+ describe("triage parsing (#5426)", () => {
14
+ it("reads paths from the Affected Files section only, first token per bullet", () => {
15
+ assert.deepEqual(affectedFilesOf(MD), ["bin/lean/light.mjs", "bin/lean/light.test.mjs", "docs/CONFIG.md"]);
16
+ assert.deepEqual(affectedFilesOf("no section"), []);
17
+ });
18
+ it("prefers triage.json, falls back to Affected Files on junk, and treats a bad size as unknown", () => {
19
+ assert.deepEqual(parseTriage('{"files":["./a.js","a.js","b.js"],"size":"s","risk":true,"decision_needed":true}', MD), { files: ["a.js", "b.js"], size: "S", risk: true, decisionNeeded: true, source: "triage" });
20
+ const f = parseTriage("not json", MD);
21
+ assert.equal(f.source, "affected_files"); assert.equal(f.size, null); assert.equal(f.files.length, 3);
22
+ assert.equal(parseTriage('{"files":[],"size":"XL"}', "").size, null);
23
+ });
24
+ it("lean.light.source: investigation by default, text is the kill-switch", () => {
25
+ assert.equal(fastForwardSource(parseLightConfig({})), "investigation");
26
+ assert.equal(fastForwardSource(parseLightConfig({ source: "Text" })), "text");
27
+ assert.equal(fastForwardSource(parseLightConfig({ light_source: "bogus" })), "investigation");
28
+ assert.equal("source" in parseLightConfig({}), false);
29
+ });
30
+ });
31
+
32
+ describe("eligibility from the investigation (#5426)", () => {
33
+ it("an issue naming no file and no size label qualifies when the investigation predicts one small file", () => {
34
+ const e = fastForwardEligibility({ title: "bug: x", body: "It breaks.", triage: triage(), cfg: CFG });
35
+ assert.equal(e.verdict, "eligible"); assert.equal(e.light, true);
36
+ assert.ok(e.signals.some((s) => s.code === "source_investigation"));
37
+ assert.ok(e.signals.some((s) => s.code === "pre_text_ambiguous"), "the text heuristic is only a shadow signal");
38
+ });
39
+ it("the text heuristic never decides: text-eligible but the investigation predicts 3 files is ineligible", () => {
40
+ const body = "```\nrepro\n```\nbin/a.mjs";
41
+ const e = fastForwardEligibility({ body, textFiles: ["bin/a.mjs"], triage: triage({ files: ["a.mjs", "b.mjs", "c.mjs"] }), cfg: CFG });
42
+ assert.equal(e.verdict, "ineligible"); assert.ok(codes(e).includes("files"));
43
+ assert.ok(e.signals.some((s) => s.code === "pre_text_eligible"));
44
+ });
45
+ it("risk path, hotspot, size M, flagged risk and decision are each hard reasons", () => {
46
+ assert.ok(codes(fastForwardEligibility({ triage: triage({ files: ["src/auth/login.mjs"] }), cfg: CFG })).includes("risk_path"));
47
+ assert.ok(codes(fastForwardEligibility({ triage: triage(), hotspots: [{ path: "src/a.mjs", lines: 3000, over: true }], cfg: CFG })).includes("hotspot"));
48
+ assert.ok(codes(fastForwardEligibility({ triage: triage({ size: "M" }), cfg: CFG })).includes("size"));
49
+ assert.ok(codes(fastForwardEligibility({ triage: triage({ risk: true }), cfg: CFG })).includes("risk"));
50
+ assert.ok(codes(fastForwardEligibility({ triage: triage({ decisionNeeded: true }), cfg: CFG })).includes("decision"));
51
+ });
52
+ it("no predicted files is ambiguous, not eligible; shadow mode never runs light; off is off", () => {
53
+ assert.equal(fastForwardEligibility({ triage: triage({ files: [] }), cfg: CFG }).verdict, "ambiguous");
54
+ const s = fastForwardEligibility({ triage: triage(), cfg: { ...CFG, mode: "shadow" } });
55
+ assert.equal(s.eligible, true); assert.equal(s.light, false);
56
+ assert.equal(fastForwardEligibility({ triage: triage(), cfg: { ...CFG, mode: "off" } }).verdict, "off");
57
+ });
58
+ });
59
+
60
+ describe("fast-forward prompts and trajectory (#5426)", () => {
61
+ it("names the skipped stages and why", () => {
62
+ const e = fastForwardEligibility({ triage: triage(), cfg: CFG });
63
+ assert.deepEqual(skippedStages(e).map((x) => x.stage), ["plan", "contract freeze", "multi-session review"]);
64
+ assert.match(skippedLine(e), /Fast-forward: skipped plan, contract freeze.*1 non-test file/);
65
+ });
66
+ it("investigation-only keeps the close and block rules but defers the contract; the contract step carries it", () => {
67
+ const a = investigationOnlyPrompt(7), b = contractStepPrompt(7);
68
+ assert.match(a, /Write \.forge-lean\/investigation\.md/); assert.ok(a.includes(TRIAGE_FILE)); assert.match(a, /"blocked" needs a typed/);
69
+ assert.ok(!a.includes('{"requirements":['));
70
+ assert.ok(b.includes('{"requirements":[') && b.includes('"blocked" needs a typed'));
71
+ assert.ok(!/1\. Write \.forge-lean\/investigation\.md/.test(b));
72
+ });
73
+ });