forgedock 1.53.0 → 1.54.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 (185) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +6 -3
  12. package/bin/engine/telemetry-seam.mjs +8 -2
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +57 -20
  15. package/bin/first-run.mjs +122 -0
  16. package/bin/forgedock.mjs +128 -146
  17. package/bin/help-text.mjs +144 -0
  18. package/bin/hooks/pre-tool-use.mjs +7 -0
  19. package/bin/journey.mjs +82 -83
  20. package/bin/lean/acceptance.mjs +313 -0
  21. package/bin/lean/acceptance.test.mjs +215 -0
  22. package/bin/lean/activation.mjs +18 -0
  23. package/bin/lean/activation.test.mjs +23 -1
  24. package/bin/lean/batch-health.mjs +74 -1
  25. package/bin/lean/batch-health.test.mjs +54 -1
  26. package/bin/lean/batch.test.mjs +11 -9
  27. package/bin/lean/branchlock.mjs +54 -0
  28. package/bin/lean/branchlock.test.mjs +49 -0
  29. package/bin/lean/ceiling.mjs +72 -0
  30. package/bin/lean/ceiling.test.mjs +54 -0
  31. package/bin/lean/ci-budget.mjs +366 -0
  32. package/bin/lean/ci-budget.test.mjs +167 -0
  33. package/bin/lean/conformance.e2e.test.mjs +7 -0
  34. package/bin/lean/conformance.mjs +77 -19
  35. package/bin/lean/conformance.test.mjs +129 -3
  36. package/bin/lean/context.mjs +35 -6
  37. package/bin/lean/context.test.mjs +27 -1
  38. package/bin/lean/depcache.mjs +25 -1
  39. package/bin/lean/depcache.test.mjs +26 -0
  40. package/bin/lean/e2e.mjs +18 -2
  41. package/bin/lean/e2e.test.mjs +26 -1
  42. package/bin/lean/effects.mjs +40 -11
  43. package/bin/lean/execution.test.mjs +24 -0
  44. package/bin/lean/facts.mjs +3 -3
  45. package/bin/lean/facts.test.mjs +5 -0
  46. package/bin/lean/fixround.mjs +14 -0
  47. package/bin/lean/fixround.test.mjs +25 -2
  48. package/bin/lean/gh-assoc.test.mjs +2 -1
  49. package/bin/lean/integration.mjs +100 -9
  50. package/bin/lean/integration.test.mjs +98 -0
  51. package/bin/lean/issuewatch-parity.mjs +64 -0
  52. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  53. package/bin/lean/issuewatch-release.test.mjs +1 -1
  54. package/bin/lean/issuewatch.mjs +34 -5
  55. package/bin/lean/issuewatch.test.mjs +3 -2
  56. package/bin/lean/lean.mjs +316 -74
  57. package/bin/lean/lean.test.mjs +397 -24
  58. package/bin/lean/mechfix.mjs +124 -0
  59. package/bin/lean/mechfix.test.mjs +75 -0
  60. package/bin/lean/orchestrate.mjs +20 -2
  61. package/bin/lean/phaseledger.mjs +47 -5
  62. package/bin/lean/phaseledger.test.mjs +30 -1
  63. package/bin/lean/precheck.mjs +23 -4
  64. package/bin/lean/precheck.test.mjs +14 -1
  65. package/bin/lean/prereq.mjs +28 -0
  66. package/bin/lean/prereq.test.mjs +20 -0
  67. package/bin/lean/probe.mjs +4 -2
  68. package/bin/lean/prodparity.mjs +52 -0
  69. package/bin/lean/prodparity.test.mjs +67 -0
  70. package/bin/lean/prompts.mjs +69 -12
  71. package/bin/lean/recovery.test.mjs +1 -1
  72. package/bin/lean/release-io.test.mjs +42 -0
  73. package/bin/lean/release-postmerge.mjs +6 -0
  74. package/bin/lean/release-preflight.mjs +58 -0
  75. package/bin/lean/release-preflight.test.mjs +114 -0
  76. package/bin/lean/release-rehearsal.mjs +8 -7
  77. package/bin/lean/release-review.mjs +67 -11
  78. package/bin/lean/release-review.test.mjs +128 -1
  79. package/bin/lean/release-snapshot.mjs +188 -0
  80. package/bin/lean/release-snapshot.test.mjs +190 -0
  81. package/bin/lean/release.mjs +80 -12
  82. package/bin/lean/release.test.mjs +95 -0
  83. package/bin/lean/render.mjs +1 -1
  84. package/bin/lean/replan.mjs +184 -0
  85. package/bin/lean/replan.test.mjs +110 -0
  86. package/bin/lean/resume.mjs +9 -7
  87. package/bin/lean/resume.test.mjs +16 -0
  88. package/bin/lean/schedd.mjs +34 -1
  89. package/bin/lean/schedd.test.mjs +21 -1
  90. package/bin/lean/selfreview.mjs +94 -0
  91. package/bin/lean/selfreview.test.mjs +58 -1
  92. package/bin/lean/selftest-gate.mjs +22 -0
  93. package/bin/lean/selftest-gate.test.mjs +18 -1
  94. package/bin/lean/selftest-journey.mjs +234 -0
  95. package/bin/lean/selftest-journey.test.mjs +130 -0
  96. package/bin/lean/selftest-live.mjs +2 -1
  97. package/bin/lean/seqlease.mjs +35 -1
  98. package/bin/lean/seqlease.test.mjs +15 -0
  99. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  100. package/bin/lean/seqreserve.mjs +73 -0
  101. package/bin/lean/seqreserve.test.mjs +134 -0
  102. package/bin/lean/sequence.mjs +35 -6
  103. package/bin/lean/seqversioned.mjs +147 -0
  104. package/bin/lean/stagestamp.mjs +28 -0
  105. package/bin/lean/stagestamp.test.mjs +32 -0
  106. package/bin/lean/surfaces.mjs +75 -0
  107. package/bin/lean/surfaces.test.mjs +59 -0
  108. package/bin/lean/toolplace.mjs +28 -0
  109. package/bin/lean/toolplace.test.mjs +24 -0
  110. package/bin/lean/toolstats.mjs +3 -1
  111. package/bin/lean/toolstats.test.mjs +11 -0
  112. package/bin/lean/validatebest.mjs +28 -0
  113. package/bin/lean/validatebest.test.mjs +27 -0
  114. package/bin/pool/agent.mjs +9 -0
  115. package/bin/pool/docker.mjs +5 -0
  116. package/bin/pool/router.mjs +8 -4
  117. package/bin/prereqs.mjs +111 -0
  118. package/bin/replay-timelapse.mjs +149 -0
  119. package/bin/review-staging.mjs +100 -16
  120. package/bin/review-staging.test.mjs +18 -0
  121. package/bin/runner.mjs +43 -6
  122. package/bin/splash-install.mjs +157 -0
  123. package/bin/stats/aggregate.mjs +8 -1
  124. package/bin/stats/conformance-outcomes.mjs +100 -19
  125. package/bin/stats/conformance-outcomes.test.mjs +87 -1
  126. package/bin/stats/depth.mjs +88 -31
  127. package/bin/stats/depth.test.mjs +63 -38
  128. package/bin/stats/efficiency.mjs +26 -5
  129. package/bin/stats/efficiency.test.mjs +45 -1
  130. package/bin/stats/first-review.mjs +77 -0
  131. package/bin/stats/first-review.test.mjs +36 -0
  132. package/bin/stats/firstmerge.mjs +40 -0
  133. package/bin/stats/firstmerge.test.mjs +41 -0
  134. package/bin/stats/github-source.mjs +51 -13
  135. package/bin/stats/index.mjs +91 -15
  136. package/bin/stats/local-source.mjs +1 -0
  137. package/bin/stats/origin.mjs +80 -0
  138. package/bin/stats/origin.test.mjs +58 -0
  139. package/bin/stats/render.mjs +3 -1
  140. package/bin/stats/scoreboard.mjs +137 -0
  141. package/bin/stats/scoreboard.test.mjs +87 -0
  142. package/bin/stats/stats.test.mjs +80 -0
  143. package/bin/tui.mjs +3 -2
  144. package/commands/bootstrap.md +15 -14
  145. package/commands/deploy-pr.md +18 -3
  146. package/commands/forge-stats.md +1 -1
  147. package/commands/forgedock-ci-setup.md +28 -0
  148. package/commands/forgedock-init.md +4 -5
  149. package/commands/issue.md +2 -0
  150. package/commands/milestone.md +9 -1
  151. package/commands/replay.md +2 -0
  152. package/commands/review-pr-staging.md +4 -1
  153. package/commands/work-on/close.md +8 -0
  154. package/docs/CONFIG.md +105 -10
  155. package/docs/ISSUE-WATCH.md +23 -0
  156. package/docs/OUTCOME-CODES.md +1 -0
  157. package/docs/REPLAY.md +9 -0
  158. package/docs/SELFTEST.md +11 -0
  159. package/docs/STATS.md +19 -2
  160. package/docs/eval/README.md +6 -0
  161. package/docs/eval/adversarial-bench.md +68 -0
  162. package/docs/eval/corpus/adversarial-v1.json +285 -0
  163. package/docs/eval/feature-bench.md +42 -0
  164. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  165. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  166. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  167. package/docs/site/start-a-new-project.md +2 -1
  168. package/package.json +5 -2
  169. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  170. package/plugins/forgedock-splash/README.md +27 -0
  171. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  172. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  173. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  174. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  175. package/scripts/bench-adversarial.mjs +216 -0
  176. package/scripts/bench-feature.mjs +170 -0
  177. package/scripts/bench-lightlane.mjs +2 -2
  178. package/scripts/bootstrap-create.mjs +2 -2
  179. package/scripts/bootstrap-validate.mjs +35 -2
  180. package/scripts/check-spec-size.sh +4 -3
  181. package/scripts/check-spec-size.test.sh +3 -0
  182. package/scripts/plan-validate-live.mjs +40 -6
  183. package/scripts/review-pr-staging-scope.test.sh +1 -1
  184. package/scripts/review-staging-post.sh +23 -0
  185. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,67 @@
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 { spawnSync } from "node:child_process";
6
+ import { writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { parseProdParity, prodParityFailures, touchedSurfaces } from "./prodparity.mjs";
9
+ import { readEnvConfig } from "../engine-cli.mjs";
10
+ import { tmpDir } from "../tests/_tmp.mjs";
11
+
12
+ const run = async ({ command }) => { const r = spawnSync("bash", ["-c", command], { encoding: "utf8" }); return { rc: r.status ?? 127, output: `${r.stdout}${r.stderr}` }; };
13
+ const dir = tmpDir("prodparity-");
14
+ const fail = join(dir, "fail.sh"); writeFileSync(fail, "echo \"parity: $*\" >&2; exit 1\n");
15
+ const pass = join(dir, "pass.sh"); writeFileSync(pass, "exit 0\n");
16
+
17
+ // The four AlterLab defects (2026-10-11..11-10): each prod-only surface is declared; the PR's files touch it.
18
+ const RULES = parseProdParity({
19
+ "web/app/**": "note: exercise the page under the production ISR runtime (next start), including the not-found path",
20
+ "infra/traefik/**": `bash ${fail}`,
21
+ "db/migrations/**": `bash ${fail}`,
22
+ ".env.production": `bash ${fail}`,
23
+ });
24
+ const REPLAYS = [
25
+ ["#38270 /blog ISR", ["web/app/blog/[slug]/page.tsx"], "prod_parity_unjustified"],
26
+ ["#38241 Traefik routing", ["infra/traefik/api-router.yml"], "prod_parity_failed"],
27
+ ["#39108 migration role", ["db/migrations/0042_feedback.sql"], "prod_parity_failed"],
28
+ ["#36906 shared env", [".env.production"], "prod_parity_failed"],
29
+ ];
30
+
31
+ describe("prod_parity (#5284)", () => {
32
+ for (const [name, files, kind] of REPLAYS) {
33
+ it(`replay ${name} is flagged`, async () => {
34
+ const f = await prodParityFailures({ rules: RULES, changedFiles: files, result: {}, run });
35
+ assert.equal(f.length, 1);
36
+ assert.equal(f[0].kind, kind);
37
+ assert.equal(f[0].code, "conformance.unimplemented");
38
+ });
39
+ }
40
+ it("a passing command or a recorded justification clears the surface", async () => {
41
+ const ok = parseProdParity({ "db/migrations/**": `bash ${pass}` });
42
+ assert.deepEqual(await prodParityFailures({ rules: ok, changedFiles: ["db/migrations/1.sql"], result: {}, run }), []);
43
+ const result = { parity: [{ surface: "web/app/**", justification: "ran next start; /blog renders" }] };
44
+ assert.deepEqual(await prodParityFailures({ rules: RULES, changedFiles: ["web/app/blog/page.tsx"], result, run }), []);
45
+ const blank = { parity: [{ surface: "web/app/**", justification: " " }] };
46
+ assert.equal((await prodParityFailures({ rules: RULES, changedFiles: ["web/app/blog/page.tsx"], result: blank, run })).length, 1);
47
+ });
48
+ it("untouched surfaces and no rules are silent; the command gets only matching paths", async () => {
49
+ assert.deepEqual(await prodParityFailures({ rules: RULES, changedFiles: ["README.md"], result: {}, run }), []);
50
+ assert.deepEqual(await prodParityFailures({ rules: [], changedFiles: [".env.production"], result: {}, run }), []);
51
+ const f = await prodParityFailures({ rules: RULES, changedFiles: [".env.production", "README.md"], result: {}, run });
52
+ assert.match(f[0].detail, /parity: \.env\.production\b/);
53
+ assert.deepEqual(touchedSurfaces(RULES, ["README.md"]), []);
54
+ });
55
+ it("a command that cannot run is reported, not swallowed", async () => {
56
+ const f = await prodParityFailures({ rules: parseProdParity({ "a/**": "x" }), changedFiles: ["a/b"], result: {}, run: async () => { throw new Error("boom"); } });
57
+ assert.equal(f[0].kind, "prod_parity_failed");
58
+ assert.match(f[0].detail, /exited 127/);
59
+ });
60
+ it("forge.yaml topology.prod_parity is read; repos without it get no key", () => {
61
+ const withKey = tmpDir("pp-yaml-"), without = tmpDir("pp-yaml-");
62
+ writeFileSync(join(withKey, "forge.yaml"), "topology:\n prod_parity:\n \"db/migrations/**\": \"bash scripts/check-role.sh\"\n \".env.production\": \"note: confirm service env scope\"\n");
63
+ writeFileSync(join(without, "forge.yaml"), "project: x/y\n");
64
+ assert.deepEqual(parseProdParity(readEnvConfig(withKey).prodParity).map((r) => r.glob), ["db/migrations/**", ".env.production"]);
65
+ assert.equal("prodParity" in readEnvConfig(without), false);
66
+ });
67
+ });
@@ -5,9 +5,12 @@ import { fileURLToPath } from "node:url";
5
5
 
6
6
  import { reviewSkeleton } from "./conformance.mjs";
7
7
  import { seqNumber } from "./sequence.mjs";
8
- import { capText, FIX_CAPS, FIX_PROMPT_MAX } from "./fixround.mjs";
8
+ import { sequenceBuildNote } from "./seqreserve.mjs";
9
+ import { capText, FIX_CAPS, FIX_PROMPT_MAX, NARROW_CAPS, NARROW_PROMPT_MAX } from "./fixround.mjs";
9
10
  import { SPLIT_MIN_FILES, SPLIT_MIN_LINES } from "./decompose.mjs";
10
11
  import { relaxationBlock } from "./relaxation.mjs";
12
+ import { stampRule } from "./stagestamp.mjs";
13
+ import { FINDING_PITFALLS, PLANNER_TIGHTENING } from "./selfreview.mjs";
11
14
  import { isTrustedIssueComment } from "./prefilter.mjs"; // call-time use only: prefilter.mjs imports this module
12
15
 
13
16
  export const approxTokens = (s) => Math.ceil(String(s).length / 4);
@@ -23,11 +26,16 @@ export const CHECKS_CLI = fileURLToPath(new URL("./checks.mjs", import.meta.url)
23
26
  /** #4364: `forgedock check`, the engine's validate and pre-PR checks run in-session before the result is written. */
24
27
  export const FORGEDOCK_CLI = fileURLToPath(new URL("../forgedock.mjs", import.meta.url));
25
28
 
29
+ /** #5347: every turn re-sends the whole session context, so independent read-only calls go out together, not one per turn. */
30
+ const BATCH_RULE = `One turn, many calls: when several reads, greps, git show/log/blame or gh calls do not depend on each other, issue them all in the same turn as parallel tool calls (or one shell call). One call per turn re-sends the whole context each time.`;
31
+
26
32
  const HOST_RULES = `Host rules (many lanes share this machine): run only targeted tests (specific files or -k filters), never the full suite. Never create extra checkouts, copies or base clones of the repo; compare with git show or git diff origin/<base>. Never install browsers. Keep scratch files under $TMPDIR. Cap verification workers at $FORGE_HOST_PARALLELISM when set: turbo --concurrency, vitest/jest --maxWorkers, playwright --workers, node --test --test-concurrency (eslint via turbo). For any typecheck, lint or test you run, first run \`node ${CHECKS_CLI} --base origin/<base>\` after your edits and run the scoped commands it prints instead of the full tsc/eslint/test scripts (it widens itself when impact is unknown: lockfile, tsconfig, CI config); once they pass, rerun it with --publish to share the incremental caches. Lint changed packages only, never dependents (turbo ...[base], nx affected). node_modules/.venv may be hardlinked read-only from a shared cache: after changing a lockfile, or when an install fails with EACCES, delete that dir first (rm -rf is safe), then install; never chmod or edit files inside it.
27
- Quiet output (tool results are re-read every later turn): run tests quietly (-q or a dot/summary reporter); on failure read \`tail -40\` plus the failing test ids (grep FAILED / not ok / FAIL), never the whole log. Send output over 8 KB to a $TMPDIR file; tail or grep it. Issue independent read-only calls (reads, greps, git log/blame, gh) in the same turn or one shell call. Read each file's ranges once (sed -n a,bp or Read offset/limit, never a whole large file) and keep notes; don't re-read it.`;
33
+ Quiet output (tool results are re-read every later turn): run tests quietly (-q or a dot/summary reporter); on failure read \`tail -40\` plus the failing test ids (grep FAILED / not ok / FAIL), never the whole log. Send output over 8 KB to a $TMPDIR file; tail or grep it. Read each file's ranges once (sed -n a,bp or Read offset/limit, never a whole large file) and keep notes; don't re-read it.
34
+ Never use git stash (push, pop, apply, drop): the stash stack is shared by every lane of this repo and a pop can apply another lane's files. To set work aside, make a WIP commit (git commit -m wip) instead; git stash list and show stay allowed.
35
+ ${BATCH_RULE}`;
28
36
 
29
37
  /** #4450: the host-rules block of the builder prompts (toolchain, sparse and repo-facts lines included), reused by the light-lane prompt. */
30
- export const hostRules = ({ toolchain = null, sparse = null, facts = null } = {}) => `${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}`;
38
+ export const hostRules = ({ toolchain = null, sparse = null, facts = null, stamp = null } = {}) => `${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}${stampRule(stamp)}`;
31
39
 
32
40
  /** Verify-by-CI (#4167): in ci/hybrid mode the engine runs the repo's CI on GitHub runners; the host runs only light checks. */
33
41
  const LIGHT = "run only formatters and linters on the files you changed";
@@ -83,11 +91,22 @@ export function migrationGeneratorPrompt(problems, mode = "local") {
83
91
  /** #4390: byte cap of the diff hunks a context-ceiling restart carries (the stat is always kept). */
84
92
  export const RESTART_DIFF_MAX_BYTES = 40 * 1024;
85
93
 
94
+ /** #5346: what the stopped session had established (files read and edited, its last tool call), so the next one does not re-explore. */
95
+ function establishedBlock(e) {
96
+ if (!e || (!e.read?.length && !e.edited?.length && !e.last)) return "";
97
+ const list = (xs) => xs.map((x) => `- ${x}`).join("\n");
98
+ return `<established>
99
+ ${e.edited?.length ? `Files the previous session edited:\n${list(e.edited)}\n` : ""}${e.read?.length ? `Files it read (already understood; do not re-read them unless you must edit them):\n${list(e.read)}${e.readMore ? `\n- (+${e.readMore} more)` : ""}\n` : ""}${e.last ? `Its last tool call: ${e.last.name} ${e.last.input}\nThat call may not have completed: check the diff above, then do the next step of the contract.\n` : ""}</established>
100
+
101
+ `;
102
+ }
103
+
86
104
  /**
87
105
  * #4390: appended to the restart prompt when the engine stopped a builder session at the context ceiling: the fresh
88
106
  * session continues from the frozen contract, the branch (`git diff --stat` + bounded hunks) and the last validate result.
89
107
  */
90
- export function contextRestartPrompt({ stat = "", diff = "", base = "", check = "", ceiling = 0 } = {}) {
108
+ export function contextRestartPrompt({ stat = "", diff = "", base = "", check = "", ceiling = 0, established = null } = {}) {
109
+ const est = establishedBlock(established);
91
110
  const d = boundDiff(String(diff ?? ""), { stat, base, maxBytes: RESTART_DIFF_MAX_BYTES }).trim();
92
111
  const c = String(check ?? "").trim();
93
112
  return `\n\nContext restart: the previous session on this lane reached the ${ceiling}-token context ceiling and the engine stopped it. Its history is gone, its work is not: ${CONTRACT_FILE} is still the frozen authority, and the branch holds the committed work (uncommitted edits were saved in a \`wip(forge): checkpoint\` commit, already pushed to the lane branch: do not amend, reword, squash, reset or rebase commits already on the branch; add new commits on top). Continue from this state; do not start over, and do not re-read what the summary below already shows.
@@ -100,7 +119,7 @@ ${String(stat ?? "").trim() || "(no changes yet)"}
100
119
  ${d || "(no changes yet)"}
101
120
  </diff>
102
121
 
103
- Last validate result (${LEAN_DIR}/self-check.json, from \`forgedock check\`): ${c ? `\n${c.length > 4000 ? `${c.slice(0, 4000)}\n[truncated]` : c}` : "none recorded; run the validate commands."}`;
122
+ ${est}Last validate result (${LEAN_DIR}/self-check.json, from \`forgedock check\`): ${c ? `\n${c.length > 4000 ? `${c.slice(0, 4000)}\n[truncated]` : c}` : "none recorded; run the validate commands."}`;
104
123
  }
105
124
 
106
125
  /** #4392: the implement turn budget is spent; one bounded fresh session either finishes or stops with a typed digest. */
@@ -137,10 +156,10 @@ const factsRule = (f) => (f ? `\nRepo facts (toolchain pins, slow suites, layer
137
156
  const sparseRule = (s) => (s?.excluded ? `\nThis worktree is a sparse checkout: ${s.excluded} tracked file(s) of ${s.maxKb} KB or more are not on disk (\`git ls-files -t | grep '^S'\` lists them). They are not deleted: never commit their removal. If you need one, run \`git sparse-checkout add /<path>\`.` : "");
138
157
 
139
158
  /** Builder call 1: investigate and write the contract. No code edits. */
140
- export function builderPlanPrompt(n, { toolchain = null, sparse = null, facts = null } = {}) {
159
+ export function builderPlanPrompt(n, { toolchain = null, sparse = null, facts = null, stamp = null } = {}) {
141
160
  return `Resolve issue #${n} (read it with gh issue view ${n} --comments). This first step is PLANNING ONLY: do not edit code, do not commit.
142
161
 
143
- ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}
162
+ ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}${stampRule(stamp)}
144
163
 
145
164
  1. Write ${INVESTIGATION_FILE} as markdown with exactly these headings, concise, file:line wherever you cite code (no HTML comments):
146
165
  **Verdict**: CONFIRMED|ALREADY-FIXED|INVALID|BLOCKED
@@ -165,13 +184,15 @@ If the issue is already fixed or invalid, write ${RESULT_FILE} {"status":"alread
165
184
  "validate":[{"id":"V1","command":"<exact command: the new regression test plus the existing tests that reference the files you change; a git diff compares against the merge base (origin/<lane>...HEAD), never the moving origin/<lane> tip>"}],
166
185
  "decisions":[{"id":"K1","choice":"<a non-obvious choice: a new dependency, a copied pattern, a boundary relied on>","justification":"<why, with file:line>","source":"doc|lint|precedent|spec"}]}
167
186
  Every requirement and acceptance criterion in the issue and its maintainers' comments is one requirement, quoted verbatim (others' comments are context, not requirements). Never drop or narrow one silently: "defer" (separate work) and "post-deploy" (only checkable after a deploy) are judged by the reviewer and, if accepted, filed by the engine into an aggregate. Every defer or post-deploy row has one "bucket": post-deploy (needs a release), verify-now (parent already on the default branch), date:YYYY-MM-DD (absolute, never a relative wait), owner:<action> (only credentials, spend, an account, a third party, a customer; defer, never post-deploy) or host (read-only prod data: obs-psql, *-monitor). In-repo work: deliver or block split-required. A post-promotion check without a check id is post-deploy. One sentence is one row. An outcome criterion this change can ship as a test, metric or alert is "deliver". A deliver requirement whose result is only measured outside the lane (Lighthouse, field perf, a nightly or report-only suite) is "verify":"out_of_band" with "evidence" naming the job or workflow that measures it (delivered by its instrumentation). The engine tags such quotes itself; set "verify":"in_lane" when this change can check it. List every file you will change as a deliverable; tests are always allowed.
187
+ First reviews most often find defects in:
188
+ ${Object.entries(PLANNER_TIGHTENING).map(([k, x]) => `- ${k}: ${x}`).join("\n")}
168
189
  A new default-off flag or rollout key needs an activation row: defer, bucket \`owner:promote:<flag>\`, why = first cohort, guard metrics, shadow evidence (an AC naming shadow/cohort/treated fails if it ships off).
169
190
  A [type:e2e] requirement needs a validate that runs a real e2e check (repo e2e set, Playwright, live stack), not a stubbed unit test; else post-deploy.
170
191
  A validate or repro command must not read a $TMPDIR file it did not create: each run gets a fresh TMPDIR.
171
192
  Scope is enforced by the engine: it checks the changed files against the deliverables plus typed amendments itself, so do not write a file-allowlist or denylist validate (git diff --name-only | grep); the engine drops such a validate at freeze.
172
- A new dependency between workspace packages (a workspace package added to a package.json dependencies, devDependencies or peerDependencies) must be a deliverable on that package.json whose change names the package and gives the reason, citing the architecture doc where there is one; "the lint allows it" or "there is a precedent" is not a reason on its own. Record each non-obvious choice in "decisions" with where its justification comes from (doc, lint, precedent or spec); omit the field when none. Then stop.
193
+ A new dependency between workspace packages (a workspace package added to a package.json dependencies, devDependencies or peerDependencies) must be a deliverable on that package.json whose change names the package and gives the reason, citing the architecture doc where there is one; "the lint allows it" or "there is a precedent" is not a reason on its own. Record each non-obvious choice in "decisions" with where its justification comes from (doc, lint, precedent or spec); omit the field when none. Then stop. Finish your reply with "Build reads:", the files (with line ranges) and searches the build needs; the build opens by issuing them all in one turn.
173
194
 
174
- An added route needs its production ingress rule cited in ${INVESTIGATION_FILE}. No decision may swap e2e for mocked tests without a forge-probe.
195
+ An added route needs its production ingress rule, and a touched topology.prod_parity surface its check or parity entry, cited in ${INVESTIGATION_FILE}. No decision may swap e2e for mocked tests without a forge-probe.
175
196
 
176
197
  ${BLOCK_RULES}`;
177
198
  }
@@ -180,7 +201,7 @@ ${BLOCK_RULES}`;
180
201
  * #4374: the conformance rubric, one definition shared verbatim by `reviewerPrompt` and the builder's self-review in
181
202
  * `builderImplementPrompt`, so the two cannot drift. Each question is answered yes (OK) or no; codebase-agnostic.
182
203
  */
183
- export const REVIEW_RUBRIC = `1. Fixed: does the diff resolve the issue as written, delivering every requirement and acceptance criterion of the issue and every contract requirement with disposition deliver? An out-of-band requirement is delivered by its instrumentation (budget test or bench committed, job configured), not its result. A [type:e2e] requirement is delivered only by a real end-to-end validate, not a unit test with stubbed I/O. Swapping e2e for mocks without a forge-probe, or a route without ingress evidence, is not delivery.
204
+ export const REVIEW_RUBRIC = `1. Fixed: does the diff resolve the issue as written, delivering every requirement and acceptance criterion of the issue and every contract requirement with disposition deliver? An out-of-band requirement is delivered by its instrumentation (budget test or bench committed, job configured), not its result. A [type:e2e] requirement is delivered only by a real end-to-end validate, not a unit test with stubbed I/O. Swapping e2e for mocks without a forge-probe, a route without ingress evidence, or a topology.prod_parity surface without evidence, is not delivery.
184
205
  2. No regression: is the diff free of breakage of an existing caller, test or behaviour (a concrete path:line failure)?
185
206
  3. Contract: is every deliverable changed as described, every preserve item intact and every validate command passing?
186
207
  4. Scope: does the diff change only deliverable paths and tests?`;
@@ -195,11 +216,11 @@ export function investigationVerdict(md) {
195
216
  }
196
217
 
197
218
  /** Builder call 2, same session: implement the frozen contract. */
198
- export function builderImplementPrompt(mode = "local", { toolchain = null, sparse = null, facts = null } = {}) {
219
+ export function builderImplementPrompt(mode = "local", { toolchain = null, sparse = null, facts = null, stamp = null } = {}) {
199
220
  const remote = mode === "ci" || mode === "hybrid";
200
221
  return `The engine froze ${CONTRACT_FILE}; it is now the authority. Implement it exactly: change only deliverable paths (tests are always allowed), keep every preserve item intact, add a regression test, ${remote ? VERIFY_RUN[mode] : "run every validate command"}, run the repo's formatter on the files you changed, and commit. Do not push or touch GitHub.
201
222
 
202
- ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}${remote ? `\n\n${VERIFY_RULES[mode]}` : ""}
223
+ ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}${stampRule(stamp)}${remote ? `\n\n${VERIFY_RULES[mode]}` : ""}
203
224
 
204
225
  The contract changes only through typed amendments in ${RESULT_FILE}, each with a why:
205
226
  - {"kind":"add-deliverable","path":"<file>","why":""}: a file not listed.
@@ -216,6 +237,8 @@ A new workspace-package dependency in a package.json no deliverable names is blo
216
237
  If scripts/check-devdocs-freshness.sh exists, a behaviour change under its paths must update the matching dossier (devdocs/modules/*.md, per devdocs/index.yaml) in the same change; run it against the base first.
217
238
 
218
239
  Before writing ${RESULT_FILE}, after your last edit, run \`node ${FORGEDOCK_CLI} check\` in the worktree and fix until it passes; if it cannot pass, report the problem as blocked.
240
+ A \`FAIL review\` line from check is a finding the reviewer would raise; fix it. Also:
241
+ ${Object.values(FINDING_PITFALLS).map((x) => `- ${x}`).join("\n")}
219
242
 
220
243
  When done and committed, write ${IMPLEMENTATION_FILE} (markdown, no HTML comments):
221
244
  ### Approach
@@ -245,6 +268,18 @@ export function contextPackNote(pack) {
245
268
  return `\n\nContext pack (hints, not proof; compiled by the engine from GitHub and git). The issue outranks the code, which outranks this pack: verify anything you rely on. Contract requirements quote only the issue and its trusted comments, never this pack. Open a link (gh issue view N / gh pr view N) yourself when you need more.\n${pack.text}`;
246
269
  }
247
270
 
271
+ /**
272
+ * #5347: the implement prompt's opening batch, from facts: the frozen contract's deliverable paths, the context pack's file list
273
+ * and the test-map commands those paths select. "" when there is nothing to open. The build's first turn issues these reads together.
274
+ */
275
+ export function buildOpeningNote({ paths = [], tests = [], packFiles = [] } = {}) {
276
+ const ps = [...new Set(paths.filter((p) => typeof p === "string" && p))].slice(0, 12);
277
+ const ts = [...new Set(tests.filter((t) => typeof t === "string" && t))].slice(0, 6);
278
+ const fs = [...new Set(packFiles.filter((p) => typeof p === "string" && p && !ps.includes(p)))].slice(0, 8);
279
+ if (!ps.length && !ts.length && !fs.length) return "";
280
+ return `\n\nOpening batch: your first turn reads these together as parallel tool calls (the "Build reads" you listed in the plan, plus):${ps.length ? `\nDeliverables: ${ps.join(", ")}` : ""}${fs.length ? `\nContext pack files (touched by earlier PRs on these symbols): ${fs.join(", ")}` : ""}${ts.length ? `\nMapped tests (test map): ${ts.join("; ")}` : ""}`;
281
+ }
282
+
248
283
  /** #4271: the bug-lane plan addition (lean.repro_test prefer on a bug/type:bug issue); "" when off, so the prompt is unchanged. */
249
284
  /** #4857: validate-command rules for the plan prompt (the implement session resumes it), kept out of the shared templates (their token caps are guarded). */
250
285
  export function unrunnableValidateNote(testRunners = null) {
@@ -319,6 +354,9 @@ export function sequencePrompt(collisions, lane, mode = "local") {
319
354
  return `origin/${lane} already uses sequence numbers this change adds:\n${rows}\n\nFirst bring the branch up to date with \`git merge --no-edit origin/${lane}\` if it is not (already fetched; never rebase or force). ${RENUMBER_RULE} ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
320
355
  }
321
356
 
357
+ /** #5235: the builder-prompt paragraph naming the numbers reserved for this lane before the build ("" when none). */
358
+ export const sequenceBuildRule = (reservations) => sequenceBuildNote(reservations);
359
+
322
360
  /** #4322: the base-sync conflict addition when a conflicted file is a numbered migration or a journal; "" otherwise. */
323
361
  export function sequenceSyncNote(files) {
324
362
  const hit = (files ?? []).some((f) => seqNumber(f) || /(?:^|\/)_journal\.json$/.test(String(f)));
@@ -367,12 +405,31 @@ export function fixSessionPrompt({ task, diff = "", stat = "", base = "", contra
367
405
  return capText(p, FIX_PROMPT_MAX - 100);
368
406
  }
369
407
 
408
+ /** The frozen contract reduced to what a narrow fix needs: deliverable paths with their change, preserve items, validate commands. */
409
+ function contractExcerpt(contract) {
410
+ const c = typeof contract === "string" ? (() => { try { return JSON.parse(contract); } catch { return null; } })() : contract;
411
+ if (!c || typeof c !== "object") return capText(typeof contract === "string" ? contract : "", NARROW_CAPS.contract);
412
+ const pick = (xs, keys) => (Array.isArray(xs) ? xs.map((x) => Object.fromEntries(keys.filter((k) => x?.[k] != null).map((k) => [k, x[k]]))) : []);
413
+ return capText(JSON.stringify({ deliverables: pick(c.deliverables, ["path", "change"]), preserve: pick(c.preserve, ["what"]), validate: pick(c.validate, ["command"]) }), NARROW_CAPS.contract);
414
+ }
415
+
416
+ /**
417
+ * #5348: the narrow-fix prompt: a contract excerpt, the failing check output and the files it names. No diff, issue summary,
418
+ * context pack, structure delta or hotspot rules. Under NARROW_PROMPT_MAX characters.
419
+ */
420
+ export function narrowFixPrompt({ task, contract = null, files = [] }) {
421
+ const list = capText((files ?? []).map((f) => `- ${f}`).join("\n") || "- (none named: read what the failure cites)", NARROW_CAPS.files);
422
+ const p = `${HOST_RULES}\n\nYou are fixing one narrow, mechanical failure on an existing branch in this worktree. You have no earlier session. Edit only the files named below (and any file the failure output names), as a minimal diff.\n\n## Contract excerpt (${CONTRACT_FILE})\n${contractExcerpt(contract)}\n\n## Files named by the failure\n${list}\n\n## The failure to fix\n${capText(task, NARROW_CAPS.task)}\n\nRe-run the check that failed (the scoped command), commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
423
+ return capText(p, NARROW_PROMPT_MAX - 100);
424
+ }
425
+
370
426
  /** Human-only block reasons (#4124). Everything else agents resolve: a dependency, a split, prod data monitoring can read. */
371
427
  export const HUMAN_BLOCK_REASONS = Object.freeze(["credentials", "spend", "promotion", "customer", "product-decision"]);
372
428
 
373
429
  const BLOCK_RULES = `"blocked" needs a typed "block" in ${RESULT_FILE}, one of:
374
430
  - {"kind":"dependency","issues":[N]}: an open upstream issue must land first. The engine requeues this issue behind it.
375
431
  - {"kind":"split-required","subissues":[{"title":"","body":"","depends_on":[0],"files":["<path>"]}],"size":{"files":N,"lines":N}}: too big for one change. The engine files the sub-issues (depends_on = indexes of earlier sub-issues; files = the files or dirs each will edit, also accepted as "paths") only when every sub-issue's files are disjoint from the others' or the whole change's size estimate exceeds ${SPLIT_MIN_FILES} files or ${SPLIT_MIN_LINES} lines; otherwise keep one lane: an ordered checklist in the contract with a validate per item. In an admitted split, siblings editing the same hub (barrel or index export list, union type, shared fixture, index doc) get its slots pre-staged in the earliest sub-issue, which the others depend on, or their own per-feature files; the engine serialises sub-issues still sharing a file.
432
+ - {"kind":"design-invalidated","decision":"<what no longer holds>","why":"","epic":N}: the design is wrong; the engine files one amendment and holds open siblings.
376
433
  - {"kind":"human","why":"${HUMAN_BLOCK_REASONS.join("|")}"}: only an external action agents cannot take, or a product decision too critical for agents. Optional "remainder":[{"title","body"}]: the agent-doable rest, filed as its own issue.
377
434
  "An upstream issue must land first", "needs a split" and "needs prod data that read-only monitoring can read" are never "human".
378
435
  A check that times out (rc 124) is host load, never a block: run the narrowest targeted command for your changed files and say the full one could not finish.
@@ -409,7 +409,7 @@ describe("#4298 staging-review follow-ups: recovery", () => {
409
409
 
410
410
  it("run-issue rejects --recover on the legacy --path full", async () => {
411
411
  await assert.rejects(runFromCli(["7", "--lane", "staging", "--path", "full", "--recover", "ci.red"], { dir: tmpDir("core-rec-"), emitTelemetry: async () => {}, io: { gh: async () => "o/r\n" } }),
412
- /--recover is not supported with --path full/);
412
+ /--recover only works with the default pipeline/);
413
413
  });
414
414
 
415
415
  it("/orchestrate spec describes terminal non-human needs-human rows, --recover scope and the schedd resume scope", () => {
@@ -0,0 +1,42 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // realReleaseIo reads real batch dirs: runningLanes must use the batch's state store (it crashed with
4
+ // "Cannot read properties of undefined (reading 'load')" on any host with an unfinished batch).
5
+ import { describe, it } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { mkdirSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { spawn } from "node:child_process";
10
+ import { tmpDir } from "../tests/_tmp.mjs";
11
+ import { realReleaseIo } from "./release.mjs";
12
+
13
+ function seed(root, id, repo, lanes) {
14
+ const d = join(root, id);
15
+ mkdirSync(join(d, "lanes"), { recursive: true });
16
+ writeFileSync(join(d, "plan.json"), JSON.stringify({ repo }));
17
+ writeFileSync(join(d, "state.json"), JSON.stringify({ lanes }));
18
+ return d;
19
+ }
20
+
21
+ describe("realReleaseIo runningLanes", () => {
22
+ it("reads unfinished batches through the state store without throwing", () => {
23
+ const root = tmpDir("release-io");
24
+ seed(root, "b20261110-000000-1", "o/r", { 7: { pid: 2 ** 22 + 12345 } });
25
+ seed(root, "b20261110-000000-2", "o/other", { 8: { pid: process.pid } });
26
+ const io = realReleaseIo({ env: { ...process.env, FORGEDOCK_BATCH_DIR: root }, print: () => {} });
27
+ assert.deepEqual(io.runningLanes("o/r"), []);
28
+ });
29
+
30
+ it("reports a live lane of the repo whose result file is not written yet", async () => {
31
+ const root = tmpDir("release-io-live");
32
+ const d = seed(root, "b20261110-000000-3", "o/r", {});
33
+ const marker = join(d, "lanes", "9.json");
34
+ const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 30000)", marker], { stdio: "ignore" });
35
+ try {
36
+ await new Promise((r) => setTimeout(r, 200));
37
+ writeFileSync(join(d, "state.json"), JSON.stringify({ lanes: { 9: { pid: child.pid } } }));
38
+ const io = realReleaseIo({ env: { ...process.env, FORGEDOCK_BATCH_DIR: root }, print: () => {} });
39
+ assert.deepEqual(io.runningLanes("o/r"), [{ batch: "b20261110-000000-3", issue: "9" }]);
40
+ } finally { child.kill(); }
41
+ });
42
+ });
@@ -8,6 +8,8 @@
8
8
  * devdocs/decisions/5208-release-postmerge.md.
9
9
  */
10
10
 
11
+ import { cleanupSnapshot } from "./release-snapshot.mjs";
12
+
11
13
  const BOUNDS = {
12
14
  publishPolls: 6, publishPollMs: 10_000, // wait for a run to appear (bot merges never trigger one)
13
15
  runPolls: 90, runPollMs: 20_000, // wait for the run to finish
@@ -114,6 +116,10 @@ export async function postMergeStep(ctx) {
114
116
  sync = await versionSync(ctx, sha, b);
115
117
  if (sync.err) return blocked(sync.err);
116
118
  }
119
+ if (state.release?.branch) {
120
+ const gone = cleanupSnapshot({ git: io.git, branch: state.release.branch });
121
+ if (!gone.deleted) io.print(`release: could not delete ${state.release.branch} (${gone.why}); delete it by hand`);
122
+ }
117
123
  io.print(`release: published (run ${pub.run}${pub.dispatched ? ", dispatched" : ""})${art ? ", artifact confirmed" : ""}${sync ? `, version-sync PR #${sync.pr} merged` : ""}`);
118
124
  return { published: true, merge: sha, run: pub.run, dispatched: pub.dispatched, artifact: art?.ok ?? null, sync };
119
125
  }
@@ -0,0 +1,58 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Host preflight of `forgedock release` (#5277): forge.yaml `release.preflight_command` runs the repo's own suites on the host
5
+ * (not as Actions minutes) before the release PR is opened, again after each fix round, and once more on the final head before
6
+ * the draft PR is marked ready. A failing blocking preflight files one `release-blocker` issue per head and stops the job; `--resume`
7
+ * retries. With no command set every function here is a no-op. No model call. Effects go through `ctx.io`.
8
+ */
9
+ import { fileBlocker, tail } from "./release-rehearsal.mjs";
10
+
11
+ export const PREFLIGHT_TIMEOUT_MS = 20 * 60_000;
12
+ const json = (s) => JSON.parse(String(s || "null"));
13
+ const off = (v) => ["false", "off", "no", "0"].includes(String(v ?? "").trim().toLowerCase());
14
+
15
+ /** `release.preflight_command` / `_timeout` (seconds) / `_blocking` -> `{command, timeoutMs, blocking}`, or null when no command is set. */
16
+ export function parsePreflightConfig(r) {
17
+ const command = typeof r?.preflight_command === "string" ? r.preflight_command.trim() : "";
18
+ if (!command) return null;
19
+ const secs = Number(r.preflight_timeout);
20
+ return { command, timeoutMs: Number.isFinite(secs) && secs > 0 ? secs * 1000 : PREFLIGHT_TIMEOUT_MS, blocking: !off(r.preflight_blocking) };
21
+ }
22
+
23
+ /**
24
+ * Run the preflight at `head`; on failure file/comment the release-blocker issue.
25
+ * @returns {{ok, head, command, blocking, code, timedOut, issue?}}
26
+ */
27
+ export async function runHostPreflight(ctx, { head, pr }) {
28
+ const { io, repo, config } = ctx;
29
+ const cfg = config.preflight;
30
+ const run = await io.rehearse(cfg.command, { timeout: cfg.timeoutMs });
31
+ const res = { ok: !!run.ok, head, command: cfg.command, blocking: cfg.blocking, code: run.code ?? null, timedOut: !!run.timedOut, output: run.ok ? "" : tail(run.output) };
32
+ if (!res.ok) res.issue = await fileBlocker({ io, repo, pr, kind: "preflight" }, res);
33
+ const { output, ...kept } = res;
34
+ return kept;
35
+ }
36
+
37
+ const stopOf = (r) => ({ stopped: true, why: `release preflight failed at ${r.head} (release-blocker #${r.issue}); fix it, then resume`, ...r });
38
+
39
+ /** Step before `release-pr`: preflight on the staging head, so no release PR is opened on a failing head. */
40
+ export async function hostPreflightStep(ctx) {
41
+ const cfg = ctx.config.preflight;
42
+ if (!cfg) return { skipped: true };
43
+ const head = String(await ctx.io.gh(["api", `repos/${ctx.repo}/commits/${ctx.staging}`, "--jq", ".sha"])).trim();
44
+ const r = await runHostPreflight(ctx, { head });
45
+ return !r.ok && r.blocking ? stopOf(r) : r;
46
+ }
47
+
48
+ /** Step after `fixes`: preflight on the final head, then mark the draft release PR ready so Actions CI runs once on it. */
49
+ export async function markReadyStep(ctx) {
50
+ if (!ctx.config.preflight) return { skipped: true };
51
+ const { io, repo } = ctx;
52
+ const { pr } = ctx.state.steps["release-pr"].result;
53
+ const view = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "headRefOid,isDraft"]));
54
+ const r = await runHostPreflight(ctx, { head: view?.headRefOid, pr });
55
+ if (!r.ok && r.blocking) return stopOf(r);
56
+ if (view?.isDraft) await io.gh(["pr", "ready", String(pr), "--repo", repo]);
57
+ return { ...r, ready: true, wasDraft: !!view?.isDraft };
58
+ }
@@ -0,0 +1,114 @@
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 { runRelease, withStubs, readReleaseConfig, newReleaseId } from "./release.mjs";
7
+ import { parsePreflightConfig, markReadyStep } from "./release-preflight.mjs";
8
+ import { fixStep } from "./release-review.mjs";
9
+
10
+ const DISK = [{ mount: "/", type: "ext4" }];
11
+ const REPO = "o/r", HEAD = "a".repeat(40);
12
+ const ok = async () => ({ ok: true });
13
+
14
+ /** io fake: `preflightOk(n)` decides the n-th host command run; gh answers just what the preflight steps ask. */
15
+ function fakeIo({ preflightOk = () => true, draft = true } = {}) {
16
+ const calls = [], ran = [];
17
+ return {
18
+ calls, ran, now: () => 1_700_000_000_000, print() {}, sleep: async () => {},
19
+ runningLanes: async () => [], batches: async () => [], setParallel: async () => {},
20
+ rehearse: async (cmd) => { ran.push(cmd); return preflightOk(ran.length) ? { ok: true, code: 0, output: "" } : { ok: false, code: 1, output: "suite red" }; },
21
+ gh: async (a) => {
22
+ calls.push(a);
23
+ const j = a.join(" ");
24
+ if (a[0] === "api") return `${HEAD}\n`;
25
+ if (a[0] === "pr" && a[1] === "list" && a.includes("open") && a.includes("--head")) return "[]";
26
+ if (a[0] === "pr" && a[1] === "list") return "[]";
27
+ if (a[0] === "pr" && a[1] === "create") return "https://github.com/o/r/pull/9";
28
+ if (a[0] === "pr" && a[1] === "view") return JSON.stringify({ headRefOid: HEAD, isDraft: draft, state: "OPEN" });
29
+ if (a[0] === "pr" && a[1] === "ready") return "";
30
+ if (a[0] === "issue" && a[1] === "list") return "[]";
31
+ if (a[0] === "issue" && a[1] === "create") return "https://github.com/o/r/issues/50";
32
+ throw new Error(`unexpected gh ${j}`);
33
+ },
34
+ };
35
+ }
36
+ const run = (io, config, over = {}) => runRelease({ io, repo: REPO, root: tmpDir("rel-pf-"), mounts: DISK, id: newReleaseId(), opts: {}, config, branches: { staging: "staging", default: "main" }, steps: withStubs({ review: ok, fixes: ok, promotion: ok, "post-merge": ok, ...over }) });
37
+ const CFG = readReleaseConfig("release:\n preflight_command: npm test\n");
38
+
39
+ describe("release host preflight (#5277)", () => {
40
+ it("parses the flat keys and is null when unset", () => {
41
+ assert.equal(parsePreflightConfig({}), null);
42
+ assert.deepEqual(parsePreflightConfig({ preflight_command: " make t ", preflight_timeout: "30", preflight_blocking: "false" }), { command: "make t", timeoutMs: 30000, blocking: false });
43
+ assert.equal(CFG.preflight.command, "npm test");
44
+ assert.equal("preflight" in readReleaseConfig(""), false);
45
+ });
46
+
47
+ it("R6: a failing preflight opens no PR, files one release-blocker and stops the release", async () => {
48
+ const io = fakeIo({ preflightOk: () => false });
49
+ const out = await run(io, CFG);
50
+ assert.equal(out.status, "stopped");
51
+ assert.equal(out.step, "host-preflight");
52
+ assert.ok(!io.calls.some((a) => a[0] === "pr" && a[1] === "create"));
53
+ const create = io.calls.find((a) => a[0] === "issue" && a[1] === "create");
54
+ assert.ok(create.includes("release-blocker") && create.some((x) => x.includes("kind=preflight")));
55
+ });
56
+
57
+ it("R2/R6: a passing preflight opens the PR as a draft; unset opens it ready with no preflight work", async () => {
58
+ const on = fakeIo();
59
+ await run(on, CFG);
60
+ assert.ok(on.calls.find((a) => a[0] === "pr" && a[1] === "create").includes("--draft"));
61
+ const off = fakeIo();
62
+ const out = await run(off, readReleaseConfig(""));
63
+ assert.equal(out.status, "done");
64
+ assert.ok(!off.calls.find((a) => a[0] === "pr" && a[1] === "create").includes("--draft"));
65
+ assert.equal(off.ran.length, 0);
66
+ assert.ok(!off.calls.some((a) => a[0] === "pr" && a[1] === "ready"));
67
+ });
68
+
69
+ it("R4/R7: the final preflight passes, then the draft is marked ready once, after review and fixes", async () => {
70
+ const order = [];
71
+ const io = fakeIo();
72
+ const out = await run(io, CFG, { review: async () => { order.push("review"); return {}; }, fixes: async () => { order.push("fixes"); return {}; } });
73
+ assert.equal(out.status, "done");
74
+ assert.equal(io.calls.filter((a) => a[1] === "ready").length, 1);
75
+ assert.deepEqual(order, ["review", "fixes"]);
76
+ assert.ok(io.calls.findIndex((a) => a[1] === "create") < io.calls.findIndex((a) => a[1] === "ready"));
77
+ assert.equal(io.ran.length, 2); // before the PR and before ready
78
+ });
79
+
80
+ it("R6: a head whose final preflight fails is not marked ready", async () => {
81
+ const io = fakeIo({ preflightOk: (n) => n < 2 });
82
+ const out = await run(io, CFG);
83
+ assert.equal(out.step, "mark-ready");
84
+ assert.equal(out.status, "stopped");
85
+ assert.ok(!io.calls.some((a) => a[1] === "ready"));
86
+ });
87
+
88
+ it("an already-ready PR is not re-marked; non-blocking failures do not stop", async () => {
89
+ const io = fakeIo({ draft: false });
90
+ const r = await markReadyStep({ io, repo: REPO, config: CFG, state: { steps: { "release-pr": { result: { pr: 9 } } } } });
91
+ assert.equal(r.ready, true);
92
+ assert.ok(!io.calls.some((a) => a[1] === "ready"));
93
+ const nb = fakeIo({ preflightOk: () => false });
94
+ const r2 = await markReadyStep({ io: nb, repo: REPO, config: { preflight: { ...CFG.preflight, blocking: false } }, state: { steps: { "release-pr": { result: { pr: 9 } } } } });
95
+ assert.equal(r2.stopped, undefined);
96
+ assert.ok(nb.calls.some((a) => a[1] === "ready"));
97
+ });
98
+
99
+ it("R3: fixStep re-runs the preflight on the new head before the delta review, and a red one blocks", async () => {
100
+ const mk = (pfOk) => {
101
+ const io = fakeIo({ preflightOk: () => pfOk });
102
+ const seam = {
103
+ headOf: async () => HEAD, runLane: async () => ({ terminalReason: "merged" }), fileCiIssue: async () => 3,
104
+ calls: [],
105
+ };
106
+ return { io, seam, ctx: { io: Object.assign(io, { review: seam }), repo: REPO, def: "main", staging: "staging", config: CFG, save() {}, state: { steps: { review: { result: { pr: 9, marker: "FORGE:GATE_FAILURE", verdict: "X", head: "b".repeat(40), blocking: [11], ciFailing: 0 } } } } } };
107
+ };
108
+ const red = mk(false);
109
+ const out = await fixStep(red.ctx);
110
+ assert.equal(out.blocked, true);
111
+ assert.match(out.reason, /host preflight failed/);
112
+ assert.equal(red.io.ran.length, 1);
113
+ });
114
+ });
@@ -25,8 +25,9 @@ export function parseRehearsalConfig(r) {
25
25
  return { command, timeoutMs: Number.isFinite(secs) && secs > 0 ? secs * 1000 : REHEARSAL_TIMEOUT_MS, blocking: !off(r.rehearsal_blocking) };
26
26
  }
27
27
 
28
- const tail = (s) => { const t = String(s ?? ""); return t.length > OUTPUT_TAIL_CHARS ? `…${t.slice(-OUTPUT_TAIL_CHARS)}` : t; };
29
- const marker = (head) => `<!-- FORGE:RELEASE_BLOCKER head=${head} -->`;
28
+ export const tail = (s) => { const t = String(s ?? ""); return t.length > OUTPUT_TAIL_CHARS ? `…${t.slice(-OUTPUT_TAIL_CHARS)}` : t; };
29
+ // The rehearsal marker keeps its original form; other kinds (preflight, #5277) get their own so one head can hold both blockers.
30
+ const marker = (head, kind = "rehearsal") => `<!-- FORGE:RELEASE_BLOCKER head=${head}${kind === "rehearsal" ? "" : ` kind=${kind}`} -->`;
30
31
 
31
32
  const prSection = (res) => `${PR_START}\n**Rehearsal**: ${res.ok ? "PASS" : res.blocking ? "FAIL (promotion held)" : "FAIL (non-blocking)"} at \`${res.head}\` — \`${res.command}\`${res.issue ? ` (#${res.issue})` : ""}\n${PR_END}`;
32
33
 
@@ -37,13 +38,13 @@ async function recordInPr({ io, repo, pr }, res) {
37
38
  await io.gh(["pr", "edit", String(pr), "--repo", repo, "--body", `${base}\n\n${prSection(res)}\n`]);
38
39
  }
39
40
 
40
- /** One open release-blocker issue per head: comment on it when it exists, else create it. @returns the issue number. */
41
- async function fileBlocker({ io, repo, pr }, res) {
42
- const text = `Release rehearsal failed on PR #${pr} at head \`${res.head}\`.\n\nCommand: \`${res.command}\` (exit ${res.code ?? "?"}${res.timedOut ? ", timed out" : ""})\n\n\`\`\`\n${tail(res.output)}\n\`\`\`\n`;
41
+ /** One open release-blocker issue per head and kind: comment on it when it exists, else create it. @returns the issue number. */
42
+ export async function fileBlocker({ io, repo, pr, kind = "rehearsal" }, res) {
43
+ const text = `Release ${kind} failed${pr ? ` on PR #${pr}` : ""} at head \`${res.head}\`.\n\nCommand: \`${res.command}\` (exit ${res.code ?? "?"}${res.timedOut ? ", timed out" : ""})\n\n\`\`\`\n${tail(res.output)}\n\`\`\`\n`;
43
44
  const open = json(await io.gh(["issue", "list", "--repo", repo, "--label", BLOCKER_LABEL, "--state", "open", "--limit", "100", "--json", "number,body"])) ?? [];
44
- const found = open.find((i) => String(i.body ?? "").includes(marker(res.head)));
45
+ const found = open.find((i) => String(i.body ?? "").includes(marker(res.head, kind)));
45
46
  if (found) { await io.gh(["issue", "comment", String(found.number), "--repo", repo, "--body", text]); return found.number; }
46
- const url = String(await io.gh(["issue", "create", "--repo", repo, "--label", BLOCKER_LABEL, "--title", `release-blocker: rehearsal failed at ${res.head.slice(0, 12)}`, "--body", `${marker(res.head)}\n${text}`])).trim();
47
+ const url = String(await io.gh(["issue", "create", "--repo", repo, "--label", BLOCKER_LABEL, "--title", `release-blocker: ${kind} failed at ${res.head.slice(0, 12)}`, "--body", `${marker(res.head, kind)}\n${text}`])).trim();
47
48
  return Number(/\/issues\/(\d+)/.exec(url)?.[1]) || null;
48
49
  }
49
50