forgedock 1.56.0 → 1.57.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 (131) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +46 -10
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +3 -1
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +88 -17
  14. package/bin/lean/conformance.test.mjs +98 -3
  15. package/bin/lean/decisions.mjs +86 -1
  16. package/bin/lean/decisions.test.mjs +21 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +12 -2
  32. package/bin/lean/issuewatch-parity.test.mjs +26 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +72 -21
  39. package/bin/lean/lean.test.mjs +149 -3
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +3 -2
  44. package/bin/lean/orphan-pr.test.mjs +8 -1
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +25 -0
  52. package/bin/lean/release-config.mjs +158 -0
  53. package/bin/lean/release-config.test.mjs +109 -0
  54. package/bin/lean/release-control.mjs +148 -0
  55. package/bin/lean/release-control.test.mjs +143 -0
  56. package/bin/lean/release-fence.mjs +50 -0
  57. package/bin/lean/release-fence.test.mjs +105 -0
  58. package/bin/lean/release-flakes.mjs +139 -0
  59. package/bin/lean/release-flakes.test.mjs +116 -0
  60. package/bin/lean/release-ledger.mjs +160 -0
  61. package/bin/lean/release-ledger.test.mjs +226 -0
  62. package/bin/lean/release-minutes.mjs +92 -0
  63. package/bin/lean/release-minutes.test.mjs +99 -0
  64. package/bin/lean/release-nightly.mjs +75 -0
  65. package/bin/lean/release-nightly.test.mjs +48 -0
  66. package/bin/lean/release-postmerge.mjs +8 -2
  67. package/bin/lean/release-review.e2e.test.mjs +1 -0
  68. package/bin/lean/release-review.mjs +54 -7
  69. package/bin/lean/release-review.test.mjs +76 -7
  70. package/bin/lean/release-unitmap.mjs +35 -0
  71. package/bin/lean/release-unitmap.test.mjs +41 -0
  72. package/bin/lean/release.mjs +177 -19
  73. package/bin/lean/release.test.mjs +40 -0
  74. package/bin/lean/render.mjs +3 -1
  75. package/bin/lean/run-issue-placement.test.mjs +82 -0
  76. package/bin/lean/sandbox-remote.mjs +16 -0
  77. package/bin/lean/schedd.mjs +1 -1
  78. package/bin/lean/seam.mjs +115 -0
  79. package/bin/lean/seam.test.mjs +118 -0
  80. package/bin/lean/selftest-journey.mjs +40 -2
  81. package/bin/lean/selftest-journey.test.mjs +43 -3
  82. package/bin/lean/statuscomment.mjs +168 -0
  83. package/bin/lean/statuscomment.test.mjs +133 -0
  84. package/bin/lean/ui-quality.mjs +57 -0
  85. package/bin/lean/ui-quality.test.mjs +55 -0
  86. package/bin/lean/visual-gate.test.mjs +63 -0
  87. package/bin/pool/agent.mjs +16 -2
  88. package/bin/pool/router.mjs +5 -1
  89. package/bin/review-staging.mjs +5 -3
  90. package/bin/stats/card.mjs +117 -0
  91. package/bin/stats/card.test.mjs +109 -0
  92. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  93. package/bin/stats/depth.mjs +1 -1
  94. package/bin/stats/gh-retry.test.mjs +152 -0
  95. package/bin/stats/github-source.mjs +147 -14
  96. package/bin/stats/index.mjs +35 -2
  97. package/bin/stats/stats.test.mjs +31 -3
  98. package/bin/vendor/js-yaml/LICENSE +21 -0
  99. package/bin/vendor/js-yaml/PIN.md +7 -0
  100. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  101. package/commands/design-render-critique-loop.md +2 -0
  102. package/commands/design.md +2 -0
  103. package/commands/issue.md +1 -1
  104. package/commands/milestone.md +1 -1
  105. package/commands/review-pr-agents/frontend.md +1 -0
  106. package/commands/review-pr-staging.md +5 -0
  107. package/docs/CONFIG.md +75 -1
  108. package/docs/ISSUE-WATCH.md +7 -0
  109. package/docs/OUTCOME-CODES.md +1 -0
  110. package/docs/STATS.md +10 -0
  111. package/docs/design/visual-gate.md +25 -0
  112. package/docs/eval/adversarial-bench.md +2 -2
  113. package/docs/eval/corpus/adversarial-v1.json +3 -3
  114. package/docs/site/start-a-new-project.md +7 -0
  115. package/docs/spec/forge-protocol-v1.md +31 -0
  116. package/package.json +1 -1
  117. package/pool/README.md +2 -0
  118. package/scripts/acceptance-red-green.sh +15 -1
  119. package/scripts/acceptance-red-green.test.sh +12 -0
  120. package/scripts/bench-adversarial.mjs +4 -0
  121. package/scripts/bench-lightlane.mjs +4 -1
  122. package/scripts/bootstrap-create.mjs +8 -2
  123. package/scripts/ci-local.test.sh +3 -3
  124. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  125. package/scripts/plan-validate-live.mjs +9 -6
  126. package/scripts/review-prepare.sh +7 -1
  127. package/scripts/review-roster.sh +5 -2
  128. package/scripts/review-roster.test.sh +9 -0
  129. package/scripts/visual-gate.mjs +64 -0
  130. package/templates/bootstrap/technical-spike.md +17 -0
  131. package/templates/contracts/seam-check.mjs +236 -0
@@ -0,0 +1,169 @@
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 { parseDesignConfig, designOn, designFiles, designPages, routeOf, specApproved, designGate, designGateNote, critiqueMarkup, visualGate, designFailures, visualGateComment } from "./design-gate.mjs";
6
+ import { precheck } from "./conformance.mjs";
7
+ import { parseForgeYaml } from "../forge-utils.mjs";
8
+
9
+ // The AlterLab block as filed on #5330 (2026-11-10): these exact keys are consumed.
10
+ const YAML = `design:
11
+ gate: blocking
12
+ routes: ["web/src/app/(site)/**/page.tsx", "web/src/app/(site)/**/layout.tsx"]
13
+ exclude: ["web/src/app/(site)/api/**"]
14
+ system: [web/src/components/marketing/home, web/src/components/dashboard, web/src/components/ui]
15
+ spec_label: design:approved
16
+ needed_label: design:needed
17
+ directions_param: dir
18
+ viewports: [390, 1440]
19
+ require_visual_check: true
20
+ `;
21
+ const cfg = parseDesignConfig(parseForgeYaml(YAML).design);
22
+
23
+ /** The regression fixture: Hands 2026-11-09, a plain-text hero, empty Needs/Evidence/Action boxes, a bare "Get access" link. */
24
+ const HANDS_BAD = `export default function Page() {
25
+ return (
26
+ <main>
27
+ <h1>AlterLab Hands</h1>
28
+ <p>Delegate any task to a person.</p>
29
+ <div className="rounded border p-4"><h3>Needs</h3></div>
30
+ <div className="rounded border p-4"></div>
31
+ <div className="rounded border p-4" />
32
+ <a href="/signup">Get access</a>
33
+ </main>
34
+ );
35
+ }`;
36
+ const HANDS_GOOD = `import { Hero } from "@/components/marketing/home/Hero";
37
+ import { NeedCard } from "@/components/marketing/home/NeedCard";
38
+ export default function Page() {
39
+ return (
40
+ <main>
41
+ <Hero title="AlterLab Hands" />
42
+ <section className="grid">
43
+ <NeedCard title="Needs" body="A named task with an owner." />
44
+ <div className="rounded border p-4"><h3>Evidence</h3><p>Receipts and photos.</p></div>
45
+ </section>
46
+ <Button asChild><a href="/signup">Get access</a></Button>
47
+ </main>
48
+ );
49
+ }`;
50
+
51
+ describe("design config (#5330 R15)", () => {
52
+ it("parses the AlterLab keys exactly", () => {
53
+ assert.equal(cfg.gate, "blocking");
54
+ assert.deepEqual(cfg.routes, ["web/src/app/(site)/**/page.tsx", "web/src/app/(site)/**/layout.tsx"]);
55
+ assert.deepEqual(cfg.exclude, ["web/src/app/(site)/api/**"]);
56
+ assert.equal(cfg.system.length, 3);
57
+ assert.equal(cfg.specLabel, "design:approved"); assert.equal(cfg.neededLabel, "design:needed"); assert.equal(cfg.directionsParam, "dir");
58
+ assert.deepEqual(cfg.viewports, [390, 1440]); assert.equal(cfg.requireVisual, true);
59
+ assert.ok(designOn(cfg));
60
+ });
61
+ it("defaults: advisory, 390/1440, label design:approved, rendered check required", () => {
62
+ const c = parseDesignConfig({ routes: ["web/app/**"], gate: "bogus" });
63
+ assert.deepEqual([c.gate, c.viewports, c.specLabel, c.requireVisual], ["advisory", [390, 1440], "design:approved", true]);
64
+ assert.equal(parseDesignConfig({ routes: "web/app/**, other/**", require_visual_check: "false" }).requireVisual, false);
65
+ });
66
+ it("opt-in: no design block or no design.routes means the gate is off and nothing is routed", () => {
67
+ for (const c of [null, undefined, parseDesignConfig(undefined), parseDesignConfig({ system: ["docs/ds.md"] }), parseDesignConfig({ gate: "blocking" })]) {
68
+ assert.equal(designOn(c), false);
69
+ assert.deepEqual(designGate({ files: ["web/app/x/page.tsx"], cfg: c }), { route: false, blocked: false, pages: [], reason: "" });
70
+ assert.equal(designGateNote(designGate({ files: ["web/app/x/page.tsx"], cfg: c })), "");
71
+ assert.deepEqual(designFailures({ cfg: c, files: ["web/app/x/page.tsx"], readFile: () => HANDS_BAD }), []);
72
+ assert.equal(visualGate({ cfg: c, files: ["web/app/x/page.tsx"] }).verdict, "SKIP");
73
+ }
74
+ assert.deepEqual(parseDesignConfig({ system: ["docs/ds.md"] }).system, ["docs/ds.md"]); // system is still read for UI lanes
75
+ });
76
+ });
77
+
78
+ describe("design routing (#5330 R11)", () => {
79
+ const P = "web/src/app/(site)/hands/page.tsx";
80
+ it("selects user-visible route files, minus exclude and tests", () => {
81
+ const files = [P, "web/src/app/(site)/layout.tsx", "web/src/app/(site)/api/x/page.tsx", "web/src/app/(site)/hands/page.test.tsx", "web/src/app/dashboard/page.tsx", "services/api/x.py"];
82
+ assert.deepEqual(designFiles(files, cfg), [P, "web/src/app/(site)/layout.tsx"]);
83
+ assert.deepEqual(designPages(files, cfg), [P]);
84
+ assert.equal(routeOf(P), "/hands"); assert.equal(routeOf("web/src/app/(site)/layout.tsx"), "/");
85
+ });
86
+ it("a predicted new page.tsx under design.routes with no spec is routed to /design and blocked with gate: blocking", () => {
87
+ const g = designGate({ files: [P, "src/a.mjs"], cfg });
88
+ assert.deepEqual([g.route, g.blocked, g.pages], [true, true, [P]]);
89
+ assert.match(g.reason, /\/design/); assert.match(designGateNote(g), /stop with a block asking for \/design/);
90
+ });
91
+ it("advisory routes without blocking", () => {
92
+ const g = designGate({ files: [P], cfg: { ...cfg, gate: "advisory" } });
93
+ assert.deepEqual([g.route, g.blocked], [true, false]); assert.match(designGateNote(g), /reference a \/design spec/);
94
+ });
95
+ it("a FORGE:DESIGN_SPEC comment or the spec label clears it; a draft spec does not", () => {
96
+ assert.equal(designGate({ files: [P], cfg, comments: [{ body: "<!-- FORGE:DESIGN_SPEC -->\nok" }] }).route, false);
97
+ assert.equal(designGate({ files: [P], cfg, labels: [{ name: "design:approved" }] }).route, false);
98
+ assert.equal(designGate({ files: [P], cfg, comments: [{ body: '<!-- FORGE:DESIGN_SPEC {"status":"draft"} -->' }] }).route, true);
99
+ assert.equal(specApproved({ labels: ["design:approved"], cfg }), true);
100
+ });
101
+ it("a change that adds no page entry (a component, an excluded api route) is not routed", () => {
102
+ assert.equal(designGate({ files: ["web/src/components/ui/button.tsx", "web/src/app/(site)/api/x/page.tsx"], cfg }).route, false);
103
+ });
104
+ });
105
+
106
+ describe("deterministic render critique floor (#5330 R14)", () => {
107
+ const ids = (src) => critiqueMarkup(src).map((f) => f.id);
108
+ it("flags the plain-text hero page with empty boxes", () => {
109
+ const f = ids(HANDS_BAD);
110
+ assert.ok(f.includes("empty_box")); assert.ok(f.includes("plain_text_hero")); assert.ok(f.includes("bare_cta"));
111
+ });
112
+ it("passes a page with components, filled cards and a real button", () => assert.deepEqual(critiqueMarkup(HANDS_GOOD), []));
113
+ it("placeholder copy and null samples block", () => {
114
+ assert.ok(ids("<main><Hero/><p>Lorem ipsum dolor</p></main>").includes("placeholder_text"));
115
+ assert.ok(ids("<main><Hero/><p>[[null]]</p></main>").includes("placeholder_text"));
116
+ });
117
+ it("decorative dividers, skeletons and commented-out boxes are not empty boxes", () => {
118
+ assert.deepEqual(ids('<main><Hero/><div className="border-t" /><div className="rounded animate-pulse" /><div aria-hidden className="rounded border" />{/* <div className="rounded border"></div> */}</main>'), []);
119
+ });
120
+ });
121
+
122
+ describe("visual gate (#5330 R12, R14; shared with #5369)", () => {
123
+ const P = "web/src/app/(site)/hands/page.tsx";
124
+ const shots = { "/hands": { screenshots: ["shots/hands-390.png", "shots/hands-1440.png"], verdict: "PASS" } };
125
+ it("regression fixture: a bundle adding the plain-text hero page with empty boxes fails the gate", () => {
126
+ const g = visualGate({ cfg, files: [P], specs: true, sources: { [P]: HANDS_BAD } });
127
+ assert.equal(g.verdict, "FAIL");
128
+ assert.ok(g.rows.some((r) => r.kind === "visual_critique_failed" && /empty_box/.test(r.detail)));
129
+ assert.ok(g.rows.some((r) => /plain_text_hero/.test(r.detail)));
130
+ });
131
+ it("the same bundle through the lane precheck is a conformance.unimplemented failure", () => {
132
+ const rows = designFailures({ cfg, files: [P], specs: true, readFile: () => HANDS_BAD });
133
+ assert.ok(rows.length >= 2); assert.ok(rows.every((r) => r.code === "conformance.unimplemented"));
134
+ const p = precheck({ contract: { requirements: [], deliverables: [{ id: "D1", path: P }] }, result: { status: "fixed" }, changedFiles: [P], pageFailures: rows });
135
+ assert.ok(JSON.stringify(p).includes("visual_critique_failed"));
136
+ });
137
+ it("blocking: a missing spec yields a failure; a good page with a spec, screenshots at both viewports and a PASS verdict passes", () => {
138
+ assert.equal(visualGate({ cfg, files: [P], specs: false, sources: { [P]: HANDS_GOOD } }).rows[0].kind, "design_spec_missing");
139
+ const g = visualGate({ cfg, files: [P], specs: true, sources: { [P]: HANDS_GOOD }, evidence: shots, rendered: true });
140
+ assert.deepEqual([g.verdict, g.rows], ["PASS", []]);
141
+ });
142
+ it("rendered evidence is required: a missing viewport, a missing verdict or a non-PASS verdict fails", () => {
143
+ const run = (evidence) => visualGate({ cfg, files: [P], specs: true, sources: { [P]: HANDS_GOOD }, evidence, rendered: true });
144
+ assert.match(run({ "/hands": { screenshots: ["a-1440.png"], verdict: "PASS" } }).rows[0].detail, /390px/);
145
+ assert.equal(run({}).rows.map((r) => r.kind).join(), "visual_screenshots_missing,visual_critique_missing");
146
+ assert.match(run({ "/hands": { ...shots["/hands"], verdict: "BUDGET-EXHAUSTED" } }).rows[0].detail, /BUDGET-EXHAUSTED/);
147
+ assert.equal(visualGate({ cfg: { ...cfg, requireVisual: false }, files: [P], specs: true, rendered: true }).verdict, "PASS");
148
+ });
149
+ it("advisory reports the same rows but never fails; lane precheck returns no rows", () => {
150
+ const a = { ...cfg, gate: "advisory" };
151
+ const g = visualGate({ cfg: a, files: [P], specs: false, sources: { [P]: HANDS_BAD } });
152
+ assert.equal(g.verdict, "ADVISORY"); assert.ok(g.rows.length >= 2);
153
+ assert.deepEqual(designFailures({ cfg: a, files: [P], readFile: () => HANDS_BAD }), []);
154
+ });
155
+ it("per-route specs: only the route without a spec is flagged", () => {
156
+ const Q = "web/src/app/(site)/pricing/page.tsx";
157
+ const g = visualGate({ cfg, files: [P, Q], specs: { "/hands": true } });
158
+ assert.deepEqual(g.rows.map((r) => r.route), ["/pricing"]);
159
+ });
160
+ it("nothing user-visible in the bundle: PASS with no routes", () => {
161
+ const g = visualGate({ cfg, files: ["services/api/x.py"] });
162
+ assert.deepEqual([g.verdict, g.routes.length], ["PASS", 0]);
163
+ });
164
+ it("the comment lists each route with its screenshots and the verdict", () => {
165
+ const g = visualGate({ cfg, files: [P], specs: true, sources: { [P]: HANDS_GOOD }, evidence: shots, rendered: true });
166
+ const c = visualGateComment(g, shots);
167
+ assert.match(c, /FORGE:VISUAL_GATE/); assert.match(c, /Visual gate: PASS/); assert.match(c, /hands-390\.png/);
168
+ });
169
+ });
@@ -0,0 +1,17 @@
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 { execCapped } from "./effects.mjs";
6
+
7
+ describe("#5592 a huge git/gh output never crashes the lane", () => {
8
+ it("output past the cap is truncated with a marker, not a maxBuffer error", async () => {
9
+ const out = await execCapped(process.execPath, ["-e", "process.stdout.write('x'.repeat(3e6))"], { cap: 1_000_000 });
10
+ assert.ok(out.startsWith("xxxx") && out.length < 1_000_200);
11
+ assert.match(out, /output truncated at 1000000 bytes/);
12
+ });
13
+ it("normal output passes through; a failing child rejects with stderr", async () => {
14
+ assert.equal(await execCapped(process.execPath, ["-e", "process.stdout.write('hi')"]), "hi");
15
+ await assert.rejects(execCapped(process.execPath, ["-e", "console.error('boom');process.exit(3)"]), (e) => e.code === 3 && /boom/.test(e.stderr) && /boom/.test(e.message));
16
+ });
17
+ });
@@ -8,6 +8,7 @@ import { homedir, hostname, freemem, loadavg, cpus, tmpdir } from "node:os";
8
8
  import { promises as fsp } from "node:fs";
9
9
  import { dirname, join, resolve, sep } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
+ import { randomBytes } from "node:crypto";
11
12
  import { runCliBackendAsync, resolveClaudeCliBinary, getClaudeCliCapabilities, buildLeanSessionFlags, buildReadOnlyToolFlags, sanitizeCliModel } from "../runner.mjs";
12
13
  import { makeIo, readSubagentModel } from "../engine-cli.mjs";
13
14
  import { makeProjector } from "../engine/projector.mjs";
@@ -113,12 +114,13 @@ export const leanSettingsFlags = ({ subagentModel = null, reread = false, guard
113
114
  };
114
115
 
115
116
  export function makeLeanRunner({ runCli = runCliBackendAsync, probe = systemdRunAvailable, subagentModel = null, sandboxed = inSandbox() } = {}) {
116
- return async ({ role, issue, cwd, model, resume, system, prompt, readOnly = false, noTools = false, rereadNudge = false, maxTurns = null, agents = null, env = null, idleMs = 0, maxMs = 0, laneLimits = null, control = null, onSpawn = null, session = null, contextMax = 0, turnMax = 0, busy = null, busyMs = 0, onIdleExtend = null, bin: pinnedBin = null }) => {
117
+ return async ({ role, issue, cwd, model, resume, system, prompt, readOnly = false, noTools = false, rereadNudge = false, maxTurns = null, agents = null, env = null, idleMs = 0, maxMs = 0, laneLimits = null, control = null, onSpawn = null, session = null, contextMax = 0, turnMax = 0, busy = null, busyMs = 0, onIdleExtend = null, bin: pinnedBin = null, fullSession = false }) => {
117
118
  // #5205: a rotation relaunch pins the real claude past the tokenbaton shim; absent, the usual resolution
118
119
  const bin = pinnedBin || resolveClaudeCliBinary(cwd) || "claude";
119
120
  const caps = getClaudeCliCapabilities(cwd);
120
121
  // #4391: custom subagents (the explorer) for the builder session; null leaves argv unchanged
121
- const flags = [...buildLeanSessionFlags(caps), ...(noTools ? noToolFlags(caps) : readOnly ? buildReadOnlyToolFlags(caps) : []), ...(agents ? ["--agents", JSON.stringify(agents)] : [])];
122
+ // #5516: fullSession keeps slash commands/Skill/Task (the release test gate invokes /test-gate); otherwise the lean minimal group
123
+ const flags = [...(fullSession ? [] : buildLeanSessionFlags(caps)), ...(noTools ? noToolFlags(caps) : readOnly ? buildReadOnlyToolFlags(caps) : []), ...(agents ? ["--agents", JSON.stringify(agents)] : [])];
122
124
  // #4843 owned models, in extraArgs so FORGEDOCK_FULL_SESSION=1 (which drops sessionFlags) keeps them (#4848 BUG-1);
123
125
  // #4456 re-read hooks: builder sessions only, and like the other session flags not in a full session
124
126
  const settings = leanSettingsFlags({ subagentModel, reread: rereadNudge && !readOnly && !noTools && process.env.FORGEDOCK_FULL_SESSION !== "1", guard: sandboxed });
@@ -295,25 +297,68 @@ export async function requiredChecksRead({ gh, repo, lane }) {
295
297
 
296
298
  export const requiredChecksFor = async (opts) => (await requiredChecksRead(opts)).checks;
297
299
 
300
+ /** #5592: stdout cap of a lane-path git/gh/docker call; output past it is cut, never an error. */
301
+ export const EXEC_CAPPED_BYTES = 100 * 1024 * 1024;
302
+ /**
303
+ * #5592: like `execFile` resolving stdout, but a child that prints more than `cap` bytes is stopped and its output
304
+ * truncated (marker appended) instead of failing with `stdout maxBuffer length exceeded`: a commit that removes a
305
+ * 485 MB archive made `git diff base...HEAD` kill the lane after it had pushed. A non-zero exit rejects with
306
+ * {stdout, stderr, code} like execFile, unless the exit came from our own stop (then the capped text is the result).
307
+ */
308
+ export function execCapped(bin, args, { cwd, env, timeout = 120000, cap = EXEC_CAPPED_BYTES, spawnFn = spawn } = {}) {
309
+ return new Promise((res, rej) => {
310
+ const child = spawnFn(bin, args, { cwd, ...(env ? { env } : {}), stdio: ["ignore", "pipe", "pipe"] });
311
+ const chunks = []; let size = 0, cut = false, err = "", timedOut = false;
312
+ const timer = timeout > 0 ? setTimeout(() => { timedOut = true; try { child.kill("SIGKILL"); } catch { /* gone */ } }, timeout) : null;
313
+ child.stdout.on("data", (b) => {
314
+ if (cut) return;
315
+ const room = cap - size;
316
+ if (b.length > room) { if (room > 0) chunks.push(b.subarray(0, room)); size = cap; cut = true; try { child.kill("SIGTERM"); } catch { /* gone */ } return; }
317
+ chunks.push(b); size += b.length;
318
+ });
319
+ child.stderr.on("data", (b) => { if (err.length < 64000) err += String(b); });
320
+ child.on("error", (e) => { if (timer) clearTimeout(timer); rej(e); });
321
+ child.on("close", (code, signal) => {
322
+ if (timer) clearTimeout(timer);
323
+ const out = Buffer.concat(chunks).toString("utf8") + (cut ? `\n[forgedock: output truncated at ${cap} bytes]\n` : "");
324
+ if (cut || code === 0) return res(out);
325
+ const e = new Error(`Command failed: ${bin} ${args.join(" ")}${timedOut ? " (timed out)" : ""}\n${err}`);
326
+ Object.assign(e, { code: timedOut ? null : code, signal, killed: timedOut, stdout: out, stderr: err });
327
+ rej(e);
328
+ });
329
+ });
330
+ }
331
+
298
332
  /** Combined stdout+stderr kept per declared check command (tail). */
299
333
  const CHECK_OUTPUT_CAP = 64000;
300
334
  /** #4240: run a forge.yaml declared check command locally (no gh, no Actions); {rc, output}, rc 124 on timeout. `env` (#4323) is merged over process.env. */
301
- export function runCheckCommand({ command, cwd, timeoutMs = 300000, env = null }) {
302
- return new Promise((done) => {
335
+ /** #5598: best-effort removal of the containers a check started (labelled by the docker shim); never throws. */
336
+ export async function reapContainers(label, { timeoutMs = 20000, env = process.env } = {}) {
337
+ try {
338
+ const ids = String((await pexec("docker", ["ps", "-aq", "--filter", `label=${label}`], { timeout: timeoutMs, env })).stdout ?? "").split(/\s+/).filter(Boolean);
339
+ if (ids.length) await pexec("docker", ["rm", "-f", ...ids], { timeout: timeoutMs, env });
340
+ return ids;
341
+ } catch { return []; }
342
+ }
343
+
344
+ export function runCheckCommand({ command, cwd, timeoutMs = 300000, env = null, graceMs = 2000 }) {
345
+ const reapLabel = `forgedock.reap=${randomBytes(8).toString("hex")}`;
346
+ const inner = new Promise((finish) => {
303
347
  let out = "", timedOut = false, child;
304
348
  const add = (b) => { out += String(b); if (out.length > 2 * CHECK_OUTPUT_CAP) out = out.slice(-CHECK_OUTPUT_CAP); };
305
- try { child = spawn("bash", ["-c", String(command)], { cwd, detached: true, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], ...(env ? { env: { ...process.env, ...env } } : {}) }); }
306
- catch (e) { done({ rc: 127, output: String(e?.message ?? e) }); return; }
307
- const kill = () => { try { process.kill(-child.pid, "SIGKILL"); } catch { try { child.kill("SIGKILL"); } catch { /* gone */ } } };
308
- const timer = setTimeout(() => { timedOut = true; kill(); }, timeoutMs);
349
+ try { child = spawn("bash", ["-c", String(command)], { cwd, detached: true, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, ...(env ?? {}), FORGE_REAP_LABEL: reapLabel } }); }
350
+ catch (e) { finish({ rc: 127, output: String(e?.message ?? e) }); return; }
351
+ const kill = (sig) => { try { process.kill(-child.pid, sig); } catch { try { child.kill(sig); } catch { /* gone */ } } };
352
+ const timer = setTimeout(() => { timedOut = true; kill("SIGTERM"); setTimeout(() => kill("SIGKILL"), graceMs).unref(); }, timeoutMs);
309
353
  child.stdout.on("data", add); child.stderr.on("data", add);
310
- child.on("error", (e) => { clearTimeout(timer); done({ rc: 127, output: `${out}${String(e?.message ?? e)}`.slice(-CHECK_OUTPUT_CAP) }); });
354
+ child.on("error", (e) => { clearTimeout(timer); finish({ rc: 127, output: `${out}${String(e?.message ?? e)}`.slice(-CHECK_OUTPUT_CAP) }); });
311
355
  child.on("close", (code) => {
312
356
  clearTimeout(timer);
313
357
  const tail = out.slice(-CHECK_OUTPUT_CAP);
314
- done(timedOut ? { rc: 124, output: `${tail}\n(timed out after ${Math.round(timeoutMs / 1000)}s)` } : { rc: Number.isInteger(code) ? code : 1, output: tail });
358
+ finish(timedOut ? { rc: 124, output: `${tail}\n(timed out after ${Math.round(timeoutMs / 1000)}s)` } : { rc: Number.isInteger(code) ? code : 1, output: tail });
315
359
  });
316
360
  });
361
+ return inner.then(async (r) => { await reapContainers(reapLabel, { env: { ...process.env, ...(env ?? {}) } }); return r; });
317
362
  }
318
363
 
319
364
  /**
@@ -344,7 +389,7 @@ export function makeGhCache({ root = null, tmp = tmpdir() } = {}) {
344
389
  export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
345
390
  const base = makeIo();
346
391
  const seqLeaseIo = makeSequenceLeaseIo(); // #5340: one instance: sequence leases, surface leases and declarations
347
- const run = (bin) => async (args, opts = {}) => (await pexec(bin, args, { cwd: opts.cwd, maxBuffer: 100 * 1024 * 1024, timeout: 120000, ...(opts.env ? { env: { ...process.env, ...opts.env } } : {}) })).stdout;
392
+ const run = (bin) => async (args, opts = {}) => execCapped(bin, args, { cwd: opts.cwd, timeout: 120000, ...(opts.env ? { env: { ...process.env, ...opts.env } } : {}) });
348
393
  /** #5235: paths the other open PRs on `lane` carry (gh only, no fetch); [] on any failure. */
349
394
  const openPrFiles = async (cwd, lane) => {
350
395
  try {
@@ -509,8 +554,8 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
509
554
  async redGreen({ cwd, base, command, timeoutSec = 300, env = null }) {
510
555
  const args = [script("acceptance-red-green.sh"), "--repo-path", cwd, "--base-ref", base, "--test-cmd", command, "--timeout", String(timeoutSec)];
511
556
  try {
512
- const m = /BASE=(\w+) HEAD=(\w+)/.exec(String((await pexec("bash", args, { cwd, timeout: (timeoutSec * 2 + 60) * 1000, maxBuffer: 4 * 1024 * 1024, ...(env ? { env: { ...process.env, ...env } } : {}) })).stdout ?? ""));
513
- return m ? { base: m[1], head: m[2] } : null;
557
+ const m = /BASE=(\w+) HEAD=(\w+)(?: PRISTINE=(\w+))?/.exec(String((await pexec("bash", args, { cwd, timeout: (timeoutSec * 2 + 60) * 1000, maxBuffer: 4 * 1024 * 1024, ...(env ? { env: { ...process.env, ...env } } : {}) })).stdout ?? ""));
558
+ return m ? { base: m[1], head: m[2], ...(m[3] ? { pristine: m[3] } : {}) } : null; // #5544: pristine only when the base's own test version failed
514
559
  } catch { return null; }
515
560
  },
516
561
  /**
@@ -317,23 +317,31 @@ export function sumWaits(text, waits = {}) {
317
317
  return { waits, queueMax };
318
318
  }
319
319
 
320
+ /** #5592: the real command a ForgeDock heavy shim (`exec node heavy.mjs run --name n -- 'real' "$@"`) was written for, or null when `text` is no shim. */
321
+ export function shimTarget(text) {
322
+ const t = String(text ?? "");
323
+ if (!t.startsWith(SHIM_HEADER)) return null;
324
+ const m = /--\s+'((?:[^']|'\\'')*)'\s+"\$@"/.exec(t);
325
+ return m ? m[1].replace(/'\\''/g, "'") : null;
326
+ }
327
+
320
328
  /**
321
- * Admission-time form of the guardChain loop (#4866): every PATH dir holding a pass-through wrapper for a heavy-shimmed tool
322
- * with no real binary behind it (so the wrapper's own `command -v` lands back on the shim). Returns [{name, dir}].
329
+ * Admission-time form of the guardChain loop (#4866): PATH dirs where a heavy shim of ours for a tool execs a pass-through
330
+ * wrapper (its own `command -v` lands back on the shim). Returns [{name, dir}].
331
+ * #5592: a pass-through wrapper with no real binary on PATH behind it is NOT a loop: writeHeavyShims writes no shim over such
332
+ * a wrapper (it skips the name with a warning), so the wrapper runs unshimmed. Only a shim that already points at one loops;
333
+ * a wrapper the shim already covers (real binary found past it, or a shim on PATH) never does.
323
334
  */
324
335
  export function findShimLoops(path, { names = HEAVY_BINS, find = which, read = head, skip = [] } = {}) {
325
336
  const out = [];
326
337
  const dirs = String(path ?? "").split(delimiter).filter(Boolean);
327
338
  for (const name of names) {
328
- const wrappers = [];
329
339
  for (const d of dirs) {
330
340
  if (skip.includes(d)) continue;
331
341
  const f = find(name, d, []);
332
- if (f && isPassThroughWrapper(read(f), name)) wrappers.push(d);
342
+ const target = f ? shimTarget(read(f)) : null;
343
+ if (target && isPassThroughWrapper(read(target), name)) out.push({ name, dir: d });
333
344
  }
334
- if (!wrappers.length) continue;
335
- const real = find(name, path, [...skip, ...wrappers]);
336
- if (!real) for (const dir of wrappers) out.push({ name, dir });
337
345
  }
338
346
  return out;
339
347
  }
@@ -364,6 +372,15 @@ export function guardChain(name, cmd, env, read = head) {
364
372
  return { cmd, env: { ...env, FORGE_HEAVY_DEPTH: String(depth + 1), FORGE_HEAVY_CHAIN: [...chain, `${name}:${cmd}`].join("|") } };
365
373
  }
366
374
 
375
+ /** #5598: `docker run|create` gets `--label <FORGE_REAP_LABEL>` so the validate runner can remove the container when it kills a timed-out step. */
376
+ export function labelDockerArgs(name, args, env = {}) {
377
+ const label = env.FORGE_REAP_LABEL;
378
+ if (!label || name !== "docker") return args;
379
+ const i = args.findIndex((a) => !a.startsWith("-"));
380
+ if (i < 0 || !(args[i] === "run" || args[i] === "create") || args.includes(label)) return args;
381
+ return [...args.slice(0, i + 1), "--label", label, ...args.slice(i + 1)];
382
+ }
383
+
367
384
  /**
368
385
  * CLI body: `run --name <n> -- <real> args...`. Pass-through when FORGE_HEAVY_HELD is set or the step is llm; else
369
386
  * acquire, run with FORGE_HEAVY_HELD=1 and FORGE_HOST_PARALLELISM from live holders, release, propagate the exit.
@@ -378,7 +395,7 @@ export async function runWrapped(argv, { env: env0 = process.env, open = openHea
378
395
  const c = heavyConfig({}, env);
379
396
  const g0 = guardChain(name, cmd, env);
380
397
  if (g0.error) { process.stderr.write(`${g0.error}\n`); return { code: 126, signal: null }; }
381
- cmd = g0.cmd; env = g0.env;
398
+ cmd = g0.cmd; env = g0.env; args = labelDockerArgs(name, args, env);
382
399
  if (env.FORGE_HEAVY_HELD || env.FORGE_HEAVY_DISABLED === "1" || classifyStep(name, args) === "llm") return run(cmd, args, env);
383
400
  const hostP = host ?? defaultHost();
384
401
  const h = open(env.FORGEDOCK_SCHED_DIR || schedDir(env), { env, host: hostP });
@@ -114,4 +114,32 @@ describe("#5174 hostload", () => {
114
114
  assert.deepEqual(out.map((r) => r.outcome), ["merged"]);
115
115
  assert.equal(probes, 0, "the remote placement never consults the overload gate");
116
116
  });
117
+
118
+ it("#5592: a pool capacity 503 never falls back to an overloaded host; the lane keeps retrying the pool", async () => {
119
+ const c = { t: 1_000_000 };
120
+ const csleep = async (ms) => { await new Promise((r) => setImmediate(r)); c.t += ms; };
121
+ const where = [];
122
+ let tries = 0;
123
+ const rows = await orchestrate({ issues: [1], parallel: 1, now: () => c.t, sleep: csleep, pollMs: 1, readBody: async () => "",
124
+ overload: () => ({ overloaded: true, perCore: 5, threshold: 2 }),
125
+ remote: { max: 1, isRemote: () => true, capacity: () => ({ free: null, online: 1, at: 1 }), offlineFallback: true, capacityFallbackAfter: 2, headroom: () => ({ ok: true }) },
126
+ runOne: async (n, _ln, ctx = {}) => {
127
+ where.push(ctx.placement?.where ?? "remote");
128
+ tries++;
129
+ return tries >= 6 ? { terminalReason: "merged", pr: 1 } : { terminalReason: "deferred", code: "sandbox.capacity", retryInSeconds: 1, detail: "HTTP 503 capacity" };
130
+ } });
131
+ assert.equal(rows[0].outcome, "merged");
132
+ assert.equal(tries, 6);
133
+ assert.ok(where.every((w) => w === "remote"), where.join());
134
+ });
135
+
136
+ it("#5592: a local issue held by host overload does not block a remote issue behind it", async () => {
137
+ const started = [], seen = [];
138
+ const rows = await orchestrate({ issues: [1, 2], parallel: 2, pollMs: 1, sleep, readBody: async () => "",
139
+ overload: () => { seen.push([...started]); return { overloaded: !started.includes(2), perCore: 5, threshold: 2 }; },
140
+ remote: { max: 2, isRemote: (n) => n === 2 },
141
+ runOne: async (n) => { started.push(n); return { terminalReason: "merged", pr: n }; } });
142
+ assert.deepEqual(started, [2, 1], "#2 (remote) starts while #1 (local) is held; #1 follows once the host clears");
143
+ assert.equal(rows.length, 2);
144
+ });
117
145
  });
@@ -0,0 +1,97 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Intake pause read from GitHub truth (#5555, epic #5549 Phase 0, invariant I18). `forgedock intake pause|resume|status`
5
+ * writes `_active.intake` on the ledger control branch (audit line in controls.jsonl) and the `forge:intake-paused` label on
6
+ * the tracker issue; the issue watch reads `_active`, the active ledger entry and the open `release/*|train/*|hotfix/*` PR
7
+ * heads, so every host honours the pause with no local state. Only used when forge.yaml `release.managed` is on.
8
+ */
9
+ import { updateActive, ACTIVE, LEDGER_PREFIX } from "./release-ledger.mjs";
10
+
11
+ export const INTAKE_LABEL = "forge:intake-paused";
12
+ export const RELEASE_HEAD_RE = /^(release|train|hotfix)\//;
13
+ const isMissing = (e) => e?.status === 404 || /HTTP 404|Not Found/i.test(String(e?.message ?? e));
14
+
15
+ /** `get(path)→parsed JSON` that returns null on a 404; `gh` is a runner `(args)→string`. */
16
+ export const ghGet = (gh) => async (path) => {
17
+ try { return JSON.parse(String(await gh(["api", path])) || "null"); } catch (e) { if (isMissing(e) || /HTTP 404|Not Found/i.test(String(e?.stderr ?? ""))) return null; throw e; }
18
+ };
19
+
20
+ async function readJsonFile(get, repo, branch, file) {
21
+ const r = await get(`repos/${repo}/contents/${file}?ref=${encodeURIComponent(branch)}`);
22
+ if (!r) return null;
23
+ try { return JSON.parse(Buffer.from(r.content ?? "", "base64").toString("utf8")); } catch { return null; }
24
+ }
25
+ /** `_active.active.json` or `{}` when the control branch does not exist. */
26
+ export const readActive = async (get, repo) => (await readJsonFile(get, repo, ACTIVE, "active.json")) ?? {};
27
+
28
+ /**
29
+ * Why claims must stop, from GitHub only: `{paused: false}` or `{paused: true, reason, source, resume?}`. Checks, in order,
30
+ * `_active.intake.paused`, an active ledger entry (the lease's release has a ledger without an end `status`) and an open PR
31
+ * whose head is `release/*|train/*|hotfix/*`. `resume` is set when the pause names a release whose ledger has ended and
32
+ * `autoResume` (freeze.intake_auto_resume) is on: the caller clears the pause (WAVE_DONE).
33
+ */
34
+ export async function githubPause({ get, repo, autoResume = false }) {
35
+ const active = await readActive(get, repo);
36
+ const ended = async (id) => { const st = await readJsonFile(get, repo, `${LEDGER_PREFIX}${id}`, "state.json"); return st ? !!st.status : null; };
37
+ const relId = active.lease?.release;
38
+ const live = relId ? (await ended(relId)) !== true : false;
39
+ if (active.intake?.paused) {
40
+ const rel = active.intake.release;
41
+ const done = autoResume && rel ? (await ended(rel)) === true : false;
42
+ if (!done) return { paused: true, source: "intake", reason: `intake paused${active.intake.reason ? `: ${active.intake.reason}` : ""}${active.intake.by ? ` (by ${active.intake.by})` : ""}` };
43
+ if (!live) return { paused: false, resume: true, reason: `release ${rel} ended` };
44
+ }
45
+ if (live) return { paused: true, source: "ledger", reason: `release ${relId} active in the ledger` };
46
+ const prs = (await get(`repos/${repo}/pulls?state=open&per_page=100`)) ?? [];
47
+ const pr = prs.find((p) => RELEASE_HEAD_RE.test(String(p?.head?.ref ?? "")));
48
+ if (pr) return { paused: true, source: "pr", reason: `open release PR #${pr.number} (${pr.head.ref})` };
49
+ return { paused: false };
50
+ }
51
+
52
+ /** Pause or resume intake: key-scoped `_active.intake` write with an audit entry, then the tracker label. */
53
+ export async function setIntake({ io, repo, paused, reason = null, by = null, tracker = null, release = null, now = Date.now() }) {
54
+ const at = new Date(now).toISOString();
55
+ const r = await updateActive({ io, repo, credential: "driver" }, ["intake"], () => ({
56
+ patch: { intake: paused ? { paused: true, reason, by, at, ...(release ? { release } : {}) } : { paused: false, by, at } },
57
+ control: { at, verb: paused ? "intake-pause" : "intake-resume", by, ...(reason ? { reason } : {}), ...(release ? { release } : {}) },
58
+ }));
59
+ if (!r.ok) return r;
60
+ let label = null;
61
+ if (tracker) {
62
+ try {
63
+ if (paused) await io.api("POST", `repos/${repo}/issues/${tracker}/labels`, { labels: [INTAKE_LABEL] });
64
+ else await io.api("DELETE", `repos/${repo}/issues/${tracker}/labels/${encodeURIComponent(INTAKE_LABEL)}`);
65
+ label = true;
66
+ } catch (e) { if (!(!paused && isMissing(e))) label = String(e?.message ?? e); }
67
+ }
68
+ return { ...r, label };
69
+ }
70
+
71
+ const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
72
+ const USAGE = "usage: forgedock intake pause|resume|status [--reason <text>] [--tracker <issue>] [--release <id>] [--repo owner/repo]";
73
+
74
+ /** `forgedock intake pause|resume|status`. */
75
+ export async function intakeFromCli(argv, deps = {}) {
76
+ const [op] = argv;
77
+ if (!["pause", "resume", "status"].includes(op)) throw new Error(USAGE);
78
+ const { readFileSync } = await import("node:fs"), { join } = await import("node:path");
79
+ const { readReleaseConfig, realReleaseIo } = await import("./release.mjs");
80
+ const cwd = deps.cwd ?? process.cwd(), print = deps.print ?? ((l) => console.log(l));
81
+ const io = deps.io ?? realReleaseIo({ env: deps.env ?? process.env, cwd });
82
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* defaults */ }
83
+ const config = readReleaseConfig(raw);
84
+ const repo = flag(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
85
+ const tracker = Number(String(flag(argv, "--tracker") ?? config.tracker ?? "").replace("#", "")) || null;
86
+ const get = async (path) => { try { return await io.api("GET", path); } catch (e) { if (isMissing(e)) return null; throw e; } };
87
+ if (op === "status") {
88
+ const a = (await readActive(get, repo)).intake, g = await githubPause({ get, repo, autoResume: config.intakeAutoResume });
89
+ print(`intake: ${g.paused ? "PAUSED" : "running"}${g.reason ? ` (${g.reason})` : ""}${a?.at ? ` last change ${a.at}` : ""}`);
90
+ return { ok: true, ...g };
91
+ }
92
+ const by = deps.by ?? (await io.gh(["api", "user", "-q", ".login"]).then((s) => String(s).trim()).catch(() => null));
93
+ const r = await setIntake({ io, repo, paused: op === "pause", reason: flag(argv, "--reason"), by, tracker, release: flag(argv, "--release"), now: io.now?.() ?? Date.now() });
94
+ if (!r.ok) throw new Error(`intake ${op} failed: ${r.refused ?? "lost the _active race"}`);
95
+ print(`intake ${op === "pause" ? "paused" : "resumed"}${tracker ? ` (label ${INTAKE_LABEL} on #${tracker}${typeof r.label === "string" ? `: ${r.label}` : ""})` : ""}`);
96
+ return { ok: true };
97
+ }
@@ -0,0 +1,105 @@
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 { tmpDir } from "../tests/_tmp.mjs";
6
+ import { githubPause, setIntake, readActive, intakeFromCli, INTAKE_LABEL } from "./intake.mjs";
7
+
8
+ const REPO = "o/r";
9
+ const err = (status) => Object.assign(new Error(`HTTP ${status}`), { status });
10
+
11
+ /** In-memory GitHub shared by every "host": _active branch files, ledger states, open PRs, issue labels. */
12
+ function fakeGh({ prs = [], ledgers = {} } = {}) {
13
+ const g = { files: {}, head: null, prs, ledgers, labels: new Set(), calls: [], n: 0, commits: {} };
14
+ const b64 = (t) => ({ content: Buffer.from(t).toString("base64") });
15
+ g.api = async (method, path, body) => {
16
+ g.calls.push(`${method} ${path}`);
17
+ let m;
18
+ if ((m = /git\/ref\/heads\/(.+)$/.exec(path))) { if (m[1] !== "_active" || !g.head) throw err(404); return { object: { sha: g.head } }; }
19
+ if ((m = /git\/commits\/(\w+)$/.exec(path))) return { tree: { sha: g.commits[m[1]] } };
20
+ if (method === "POST" && /git\/trees$/.test(path)) { const files = { ...(g.commits.__files ?? {}) }; for (const e of body.tree) files[e.path] = e.content; g.commits.__files = files; return { sha: `t${++g.n}` }; }
21
+ if (method === "POST" && /git\/commits$/.test(path)) { const sha = `c${++g.n}`; g.commits[sha] = body.tree; return { sha }; }
22
+ if (method === "POST" && /git\/refs$/.test(path)) { g.head = body.sha; g.files = { ...g.commits.__files }; return {}; }
23
+ if (method === "PATCH" && /git\/refs\//.test(path)) { g.head = body.sha; g.files = { ...g.commits.__files }; return {}; }
24
+ if ((m = /contents\/([^?]+)\?ref=(.+)$/.exec(path))) {
25
+ const br = decodeURIComponent(m[2]);
26
+ if (br === "_active") { if (g.files[m[1]] === undefined) throw err(404); return b64(g.files[m[1]]); }
27
+ const st = g.ledgers[br.replace("forge-ledger/", "")]; if (!st) throw err(404); return b64(JSON.stringify(st));
28
+ }
29
+ if (/pulls\?state=open/.test(path)) return g.prs;
30
+ if (method === "POST" && /issues\/\d+\/labels$/.test(path)) { body.labels.forEach((l) => g.labels.add(l)); return []; }
31
+ if (method === "DELETE" && /issues\/\d+\/labels\//.test(path)) { g.labels.delete(decodeURIComponent(path.split("/labels/")[1])); return []; }
32
+ throw new Error(`unrouted ${method} ${path}`);
33
+ };
34
+ g.get = async (p) => { try { return await g.api("GET", p); } catch (e) { if (e.status === 404) return null; throw e; } };
35
+ return g;
36
+ }
37
+
38
+ describe("intake pause from GitHub (#5555)", () => {
39
+ it("the 2026-11-12 case: an open release/* PR pauses with no local state or _active", async () => {
40
+ const g = fakeGh({ prs: [{ number: 9, head: { ref: "release/20261112-1" } }] });
41
+ const r = await githubPause({ get: g.get, repo: REPO });
42
+ assert.equal(r.paused, true); assert.equal(r.source, "pr"); assert.match(r.reason, /#9/);
43
+ });
44
+ it("train/*, hotfix/* heads pause; feature heads do not", async () => {
45
+ for (const ref of ["train/a", "hotfix/b"]) assert.equal((await githubPause({ get: fakeGh({ prs: [{ number: 1, head: { ref } }] }).get, repo: REPO })).paused, true);
46
+ assert.equal((await githubPause({ get: fakeGh({ prs: [{ number: 1, head: { ref: "feat/x" } }] }).get, repo: REPO })).paused, false);
47
+ });
48
+ it("intake pause on host A is honoured by host B, writes the label and an audit line; resume reverses", async () => {
49
+ const g = fakeGh();
50
+ const r = await setIntake({ io: { api: g.api }, repo: REPO, paused: true, reason: "freeze", by: "op", tracker: 7, now: 1_000 });
51
+ assert.ok(r.ok); assert.ok(g.labels.has(INTAKE_LABEL));
52
+ assert.equal((await readActive(g.get, REPO)).intake.paused, true);
53
+ assert.match(g.files["controls.jsonl"], /"verb":"intake-pause"/);
54
+ const hostB = await githubPause({ get: g.get, repo: REPO });
55
+ assert.equal(hostB.paused, true); assert.match(hostB.reason, /freeze/);
56
+ await setIntake({ io: { api: g.api }, repo: REPO, paused: false, by: "op", tracker: 7, now: 2_000 });
57
+ assert.equal(g.labels.has(INTAKE_LABEL), false);
58
+ assert.equal((await githubPause({ get: g.get, repo: REPO })).paused, false);
59
+ assert.equal(g.files["controls.jsonl"].trim().split("\n").length, 2);
60
+ });
61
+ it("an active ledger entry pauses; an ended one does not", async () => {
62
+ const g = fakeGh({ ledgers: { "r20261112-101500-1": { status: undefined } } });
63
+ g.files["active.json"] = JSON.stringify({ lease: { holder: "h", release: "r20261112-101500-1" } }); g.head = "x";
64
+ assert.equal((await githubPause({ get: g.get, repo: REPO })).source, "ledger");
65
+ g.ledgers["r20261112-101500-1"] = { status: "done" };
66
+ assert.equal((await githubPause({ get: g.get, repo: REPO })).paused, false);
67
+ });
68
+ it("auto-resume: a pause naming an ended release resumes only when enabled", async () => {
69
+ const g = fakeGh({ ledgers: { "r1": { status: "done" } } });
70
+ await setIntake({ io: { api: g.api }, repo: REPO, paused: true, release: "r1", now: 1 });
71
+ assert.equal((await githubPause({ get: g.get, repo: REPO })).paused, true);
72
+ const r = await githubPause({ get: g.get, repo: REPO, autoResume: true });
73
+ assert.equal(r.paused, false); assert.equal(r.resume, true);
74
+ });
75
+ it("CLI pause writes through io.api and status reports it", async () => {
76
+ const g = fakeGh(), out = [];
77
+ const io = { api: g.api, gh: async () => JSON.stringify({}), now: () => 5 };
78
+ await intakeFromCli(["pause", "--repo", REPO, "--reason", "why", "--tracker", "3"], { io, by: "me", print: (l) => out.push(l), cwd: "/nonexistent" });
79
+ const s = await intakeFromCli(["status", "--repo", REPO], { io, print: (l) => out.push(l), cwd: "/nonexistent" });
80
+ assert.equal(s.paused, true); assert.match(out.join("\n"), /PAUSED/);
81
+ await assert.rejects(intakeFromCli(["bogus"], { io }), /usage/);
82
+ });
83
+ });
84
+
85
+ describe("issue-watch pass reads GitHub intake (#5555)", () => {
86
+ const run = async (yaml, g) => {
87
+ const { writeFileSync } = await import("node:fs"), { join } = await import("node:path");
88
+ const { runWatch, validateWatch } = await import("./issuewatch.mjs");
89
+ const cwd = tmpDir("intake-"), dir = tmpDir("intake-w-");
90
+ writeFileSync(join(cwd, "forge.yaml"), yaml);
91
+ const gh = async (a) => { g.calls.push(`gh ${a.join(" ")}`); if (a[0] === "api") return JSON.stringify(await g.get(a[1])); throw new Error(`unexpected gh ${a.join(" ")}`); };
92
+ const io = { env: { FORGEDOCK_WATCH_DIR: dir, PATH: "" }, gh, now: () => 1_000, sleep: async () => {}, releaseInFlight: () => null };
93
+ return runWatch({ watch: validateWatch("w", { mode: "batch" }), repo: REPO, io, dir, branches: {}, defaults: [], once: true, cwd });
94
+ };
95
+ it("managed: an open release PR pauses the pass within one poll and nothing is claimed", async () => {
96
+ const g = fakeGh({ prs: [{ number: 9, head: { ref: "release/20261112-1" } }] });
97
+ const state = await run("release:\n managed: true\n", g);
98
+ assert.match(state.paused.reason, /release PR #9/); assert.equal(state.claimed.length, 0);
99
+ });
100
+ it("unmanaged (defaults): no GitHub call is made for the pause", async () => {
101
+ const g = fakeGh({ prs: [{ number: 9, head: { ref: "release/x" } }] });
102
+ await run("project: x\n", g).catch(() => {});
103
+ assert.equal(g.calls.filter((c) => /pulls|contents|git\/ref/.test(c)).length, 0);
104
+ });
105
+ });