forgedock 1.52.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 (233) 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 +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -5,8 +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";
11
+ import { relaxationBlock } from "./relaxation.mjs";
12
+ import { stampRule } from "./stagestamp.mjs";
13
+ import { FINDING_PITFALLS, PLANNER_TIGHTENING } from "./selfreview.mjs";
10
14
  import { isTrustedIssueComment } from "./prefilter.mjs"; // call-time use only: prefilter.mjs imports this module
11
15
 
12
16
  export const approxTokens = (s) => Math.ceil(String(s).length / 4);
@@ -22,11 +26,16 @@ export const CHECKS_CLI = fileURLToPath(new URL("./checks.mjs", import.meta.url)
22
26
  /** #4364: `forgedock check`, the engine's validate and pre-PR checks run in-session before the result is written. */
23
27
  export const FORGEDOCK_CLI = fileURLToPath(new URL("../forgedock.mjs", import.meta.url));
24
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
+
25
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.
26
- 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}`;
27
36
 
28
37
  /** #4450: the host-rules block of the builder prompts (toolchain, sparse and repo-facts lines included), reused by the light-lane prompt. */
29
- 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)}`;
30
39
 
31
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. */
32
41
  const LIGHT = "run only formatters and linters on the files you changed";
@@ -82,14 +91,25 @@ export function migrationGeneratorPrompt(problems, mode = "local") {
82
91
  /** #4390: byte cap of the diff hunks a context-ceiling restart carries (the stat is always kept). */
83
92
  export const RESTART_DIFF_MAX_BYTES = 40 * 1024;
84
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
+
85
104
  /**
86
105
  * #4390: appended to the restart prompt when the engine stopped a builder session at the context ceiling: the fresh
87
106
  * session continues from the frozen contract, the branch (`git diff --stat` + bounded hunks) and the last validate result.
88
107
  */
89
- 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);
90
110
  const d = boundDiff(String(diff ?? ""), { stat, base, maxBytes: RESTART_DIFF_MAX_BYTES }).trim();
91
111
  const c = String(check ?? "").trim();
92
- 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). Continue from this state; do not start over, and do not re-read what the summary below already shows.
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.
93
113
 
94
114
  <diff_stat base="${base}">
95
115
  ${String(stat ?? "").trim() || "(no changes yet)"}
@@ -99,7 +119,7 @@ ${String(stat ?? "").trim() || "(no changes yet)"}
99
119
  ${d || "(no changes yet)"}
100
120
  </diff>
101
121
 
102
- 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."}`;
103
123
  }
104
124
 
105
125
  /** #4392: the implement turn budget is spent; one bounded fresh session either finishes or stops with a typed digest. */
@@ -136,10 +156,10 @@ const factsRule = (f) => (f ? `\nRepo facts (toolchain pins, slow suites, layer
136
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>\`.` : "");
137
157
 
138
158
  /** Builder call 1: investigate and write the contract. No code edits. */
139
- export function builderPlanPrompt(n, { toolchain = null, sparse = null, facts = null } = {}) {
159
+ export function builderPlanPrompt(n, { toolchain = null, sparse = null, facts = null, stamp = null } = {}) {
140
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.
141
161
 
142
- ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}
162
+ ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}${stampRule(stamp)}
143
163
 
144
164
  1. Write ${INVESTIGATION_FILE} as markdown with exactly these headings, concise, file:line wherever you cite code (no HTML comments):
145
165
  **Verdict**: CONFIRMED|ALREADY-FIXED|INVALID|BLOCKED
@@ -158,19 +178,21 @@ ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}
158
178
  If the issue is already fixed or invalid, write ${RESULT_FILE} {"status":"already-fixed|invalid","summary":"one line","evidence":["file:line ..."]} and stop. If it is blocked, write {"status":"blocked","summary":"",...} with a typed "block" (rules below) and stop.
159
179
 
160
180
  2. Otherwise write ${CONTRACT_FILE}, the frozen hand-off: a developer who never saw the issue must be able to implement and verify from this file alone.
161
- {"requirements":[{"id":"R1","quote":"<verbatim sentence or checklist item from the issue>","disposition":"deliver|defer|post-deploy|not-applicable","why":"<defer, post-deploy>","bucket":"<defer, post-deploy: post-deploy|verify-now|date:YYYY-MM-DD|owner:<action>|new-issue|host>","check":"<post-deploy: id in .forge/post-deploy-checks.json>","evidence":"<file:line, required for not-applicable>","verify":"<optional: in_lane|out_of_band>"}],
181
+ {"requirements":[{"id":"R1","quote":"<verbatim sentence or checklist item from the issue>","disposition":"deliver|defer|post-deploy|not-applicable","why":"<defer, post-deploy>","bucket":"<defer, post-deploy: post-deploy|verify-now|date:YYYY-MM-DD|owner:<action>|host>","check":"<post-deploy: id in .forge/post-deploy-checks.json>","evidence":"<file:line, required for not-applicable>","verify":"<optional: in_lane|out_of_band>"}],
162
182
  "deliverables":[{"id":"D1","path":"<file to change>","change":"<what>","requirements":["R1"]}],
163
183
  "preserve":[{"id":"P1","what":"<caller, contract or behaviour that must not change, with its path>"}],
164
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>"}],
165
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"}]}
166
- 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 as a tracked follow-up issue. 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), host (read-only prod data: obs-psql, *-monitor) or new-issue (future work). 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.
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")}
167
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).
168
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.
169
191
  A validate or repro command must not read a $TMPDIR file it did not create: each run gets a fresh TMPDIR.
170
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.
171
- 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.
172
194
 
173
- 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.
174
196
 
175
197
  ${BLOCK_RULES}`;
176
198
  }
@@ -179,7 +201,7 @@ ${BLOCK_RULES}`;
179
201
  * #4374: the conformance rubric, one definition shared verbatim by `reviewerPrompt` and the builder's self-review in
180
202
  * `builderImplementPrompt`, so the two cannot drift. Each question is answered yes (OK) or no; codebase-agnostic.
181
203
  */
182
- 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.
183
205
  2. No regression: is the diff free of breakage of an existing caller, test or behaviour (a concrete path:line failure)?
184
206
  3. Contract: is every deliverable changed as described, every preserve item intact and every validate command passing?
185
207
  4. Scope: does the diff change only deliverable paths and tests?`;
@@ -194,11 +216,11 @@ export function investigationVerdict(md) {
194
216
  }
195
217
 
196
218
  /** Builder call 2, same session: implement the frozen contract. */
197
- 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 } = {}) {
198
220
  const remote = mode === "ci" || mode === "hybrid";
199
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.
200
222
 
201
- ${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]}` : ""}
202
224
 
203
225
  The contract changes only through typed amendments in ${RESULT_FILE}, each with a why:
204
226
  - {"kind":"add-deliverable","path":"<file>","why":""}: a file not listed.
@@ -215,6 +237,8 @@ A new workspace-package dependency in a package.json no deliverable names is blo
215
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.
216
238
 
217
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")}
218
242
 
219
243
  When done and committed, write ${IMPLEMENTATION_FILE} (markdown, no HTML comments):
220
244
  ### Approach
@@ -244,16 +268,28 @@ export function contextPackNote(pack) {
244
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}`;
245
269
  }
246
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
+
247
283
  /** #4271: the bug-lane plan addition (lean.repro_test prefer on a bug/type:bug issue); "" when off, so the prompt is unchanged. */
248
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). */
249
285
  export function unrunnableValidateNote(testRunners = null) {
250
286
  const map = testRunners && typeof testRunners === "object" ? Object.entries(testRunners).map(([k, v]) => `${k}/ -> ${v}`).join("; ") : "";
251
- return `\n\nValidate and repro commands must pass bash -n (no prose notes), select tests that exist, and run from the right cwd${map ? ` (forge.yaml verification.test_runners: ${map})` : ""}. An unrunnable validate (missing tool, wrong cwd, no tests selected) is never a block or "human" product-decision: run an equivalent through the repo's toolchain and record {"kind":"substitute-validate","validate":"V#","command":"<runnable equivalent>","why":""} in ${RESULT_FILE} amendments. A post-deploy requirement needs a registered check id; one that is a manual or production-credential action with no runnable check is disposition "defer" with bucket "owner:<action>" only when it needs credentials, spend, an account, a third party or a customer; read-only prod data is "host". forge.yaml validate.recipes rewrite matching commands at freeze.`;
287
+ return `\n\nValidate and repro commands must pass bash -n (no prose notes), select tests that exist, and run from the right cwd (never combine \`poetry -C <dir>\` or \`uv run --project <dir>\` with repo-root-relative paths: use \`cd <dir> && poetry run pytest <dir-relative paths>\`)${map ? ` (forge.yaml verification.test_runners: ${map})` : ""}. An unrunnable validate (missing tool, wrong cwd, no tests selected) is never a block or "human" product-decision: run an equivalent through the repo's toolchain and record {"kind":"substitute-validate","validate":"V#","command":"<runnable equivalent>","why":""} in ${RESULT_FILE} amendments. A post-deploy requirement needs a registered check id; one that is a manual or production-credential action with no runnable check is disposition "defer" with bucket "owner:<action>" only when it needs credentials, spend, an account, a third party or a customer; read-only prod data is "host". forge.yaml validate.recipes rewrite matching commands at freeze.`;
252
288
  }
253
289
 
254
290
  export function reproPlanNote(on) {
255
291
  if (!on) return "";
256
- return `\n\nThis issue is a bug. When it is testable, ${CONTRACT_FILE} must also carry "repro_test":{"path":"<test file>","id":"<test name>","command":"<exact command that runs only that test>"}: a test that fails on the base and passes after the fix. The engine proves it with scripts/acceptance-red-green.sh (head's changed test files are overlaid on the base) and fails the run if it is not red on base and green on head. When it is not testable (specs, docs, workflows, environment), write "repro_test":"none","repro_test_reason":"<one line why>" instead.`;
292
+ return `\n\nThis issue is a bug. When it is testable, ${CONTRACT_FILE} must also carry "repro_test":{"path":"<test file>","id":"<test name>","command":"<exact command that runs only that test>"}: a test that fails on the base and passes after the fix. The command's environment must come from the repo's own lockfile or toolchain (its project runner, a lockfile export fed to uv run --with-requirements, or a forge.yaml validate.recipes entry); never a hand-picked --with package list with --offline, which cannot import the module under test (env.repro_unrunnable). The engine proves it with scripts/acceptance-red-green.sh (head's changed test files are overlaid on the base) and fails the run if it is not red on base and green on head. When it is not testable (specs, docs, workflows, environment), write "repro_test":"none","repro_test_reason":"<one line why>" instead.`;
257
293
  }
258
294
 
259
295
  /** forge#4519: the repo's generated, bot-owned globs (forge.yaml maintenance.generated_paths via hotspots.sh); "" when none. */
@@ -318,6 +354,9 @@ export function sequencePrompt(collisions, lane, mode = "local") {
318
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.`;
319
355
  }
320
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
+
321
360
  /** #4322: the base-sync conflict addition when a conflicted file is a numbered migration or a journal; "" otherwise. */
322
361
  export function sequenceSyncNote(files) {
323
362
  const hit = (files ?? []).some((f) => seqNumber(f) || /(?:^|\/)_journal\.json$/.test(String(f)));
@@ -366,12 +405,31 @@ export function fixSessionPrompt({ task, diff = "", stat = "", base = "", contra
366
405
  return capText(p, FIX_PROMPT_MAX - 100);
367
406
  }
368
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
+
369
426
  /** Human-only block reasons (#4124). Everything else agents resolve: a dependency, a split, prod data monitoring can read. */
370
427
  export const HUMAN_BLOCK_REASONS = Object.freeze(["credentials", "spend", "promotion", "customer", "product-decision"]);
371
428
 
372
429
  const BLOCK_RULES = `"blocked" needs a typed "block" in ${RESULT_FILE}, one of:
373
430
  - {"kind":"dependency","issues":[N]}: an open upstream issue must land first. The engine requeues this issue behind it.
374
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.
375
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.
376
434
  "An upstream issue must land first", "needs a split" and "needs prod data that read-only monitoring can read" are never "human".
377
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.
@@ -476,12 +534,12 @@ export function domainChecksBlock(domains = []) {
476
534
  return `\n<domain_checks>\nThis diff touches these review domains. Report every finding below as a regressions row with path:line (it blocks the merge).\n${lines.join("\n")}\n</domain_checks>`;
477
535
  }
478
536
 
479
- export function reviewerPrompt({ issue, comments = [], contract, result, files = [], diff, stat = "", base = "", structure = "", ignore = [`${LEAN_DIR}/`], skeleton = null, investigationVerdict = null, domains = [] }) {
537
+ export function reviewerPrompt({ issue, comments = [], contract, result, files = [], diff, stat = "", base = "", structure = "", ignore = [`${LEAN_DIR}/`], skeleton = null, investigationVerdict = null, domains = [], relaxations = [] }) {
480
538
  const notes = comments.map((c) => String(c?.body ?? "")).filter((b) => !/^<!-- FORGE:/.test(b.trim()));
481
539
  const decisions = comments.filter((c) => isDecision(c?.body) && isTrustedIssueComment(c)).map((c) => String(c.body)); // #4901: operator decisions bind the review; other FORGE: records stay out
482
540
  notes.push(...decisions);
483
541
  const sk = JSON.stringify(skeleton ?? reviewSkeleton(contract ?? {}, files, ignore), null, 1);
484
- return `Issue #${issue.number}: ${issue.title}\n\n<issue_body>\n${cap(issue.body ?? "", 20000)}\n</issue_body>\n\n<issue_comments>\n${cap(notes.join("\n---\n"), 8000)}\n</issue_comments>\n\n<contract>\n${cap(JSON.stringify(contract ?? {}, null, 1), 12000)}\n</contract>\n\n<builder_result>\n${cap(JSON.stringify(result ?? {}, null, 1), 6000)}\n</builder_result>\n\n${investigationVerdict ? `<investigation_verdict>${investigationVerdict}</investigation_verdict>\n${VERDICT_RULE}\n\n` : ""}<changed_files>\n${files.join("\n")}\n</changed_files>\n\n<rubric>\n${REVIEW_RUBRIC}\n</rubric>\n\n<row_skeleton>\n${cap(sk, 30000)}\n</row_skeleton>\n\n<diff>\n${boundDiff(diff, { stat, base })}\n</diff>${structure ? `\n<structure>${String(structure).replace(/[\r\n]+/g, " ")}</structure>` : ""}${domainChecksBlock(domains)}`;
542
+ return `Issue #${issue.number}: ${issue.title}\n\n<issue_body>\n${cap(issue.body ?? "", 20000)}\n</issue_body>\n\n<issue_comments>\n${cap(notes.join("\n---\n"), 8000)}\n</issue_comments>\n\n<contract>\n${cap(JSON.stringify(contract ?? {}, null, 1), 12000)}\n</contract>\n\n<builder_result>\n${cap(JSON.stringify(result ?? {}, null, 1), 6000)}\n</builder_result>\n\n${investigationVerdict ? `<investigation_verdict>${investigationVerdict}</investigation_verdict>\n${VERDICT_RULE}\n\n` : ""}<changed_files>\n${files.join("\n")}\n</changed_files>\n\n<rubric>\n${REVIEW_RUBRIC}\n</rubric>\n\n<row_skeleton>\n${cap(sk, 30000)}\n</row_skeleton>\n\n<diff>\n${boundDiff(diff, { stat, base })}\n</diff>${structure ? `\n<structure>${String(structure).replace(/[\r\n]+/g, " ")}</structure>` : ""}${domainChecksBlock(domains)}${relaxationBlock(relaxations)}`;
485
543
  }
486
544
 
487
545
  /**
@@ -0,0 +1,39 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Account-pool exhaustion for a lane (#5236). When the rotator reports no account with room, a lane must not spawn
5
+ * through the tokenbaton shim (which would fall back to the default profile and fail `backend.auth`), nor sleep on a
6
+ * far reset: it ends `deferred` with `quota.exhausted` carrying the earliest reset, which the batch holds until.
7
+ */
8
+ import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
9
+
10
+ /** Wait (s) when no reset is known. */
11
+ export const QUOTA_RETRY_SECONDS = 900;
12
+
13
+ /**
14
+ * `{earliestReset}` (epoch ms or null) when `rotator.pick` finds no account outside `exclude`; null when one has room,
15
+ * or there is no smart rotator. A pick that fails (throws) counts as exhausted: never spawn through the shim, which would fall back to the default profile.
16
+ */
17
+ export function poolExhausted(rotator, exclude) {
18
+ try {
19
+ if (!rotator || typeof rotator.pick !== "function") return null;
20
+ const p = rotator.pick({ exclude });
21
+ if (!p || p.account !== null || p.account === undefined) return null;
22
+ return { earliestReset: Number.isFinite(p.earliestReset) && p.earliestReset > 0 ? p.earliestReset : null };
23
+ } catch { return { earliestReset: null }; }
24
+ }
25
+
26
+ /** `e` marked as a `quota.exhausted` deferral (handled through `deferCode`); `backendId` keys the batch's account hold. */
27
+ export function exhaustedDeferral(e, { earliestReset, backendId, now }) {
28
+ const at = Number.isFinite(earliestReset) && earliestReset > now ? earliestReset : null;
29
+ return Object.assign(e, {
30
+ deferCode: OUTCOME_CODES.QUOTA_EXHAUSTED,
31
+ retryInSeconds: at ? Math.max(1, Math.ceil((at - now) / 1000)) : QUOTA_RETRY_SECONDS,
32
+ backendId,
33
+ ...(at ? { resetAtEpochMs: at, resetAt: new Date(at).toISOString() } : {}),
34
+ deferDetail: `quota exhausted: no account has capacity${at ? `; earliest reset ${new Date(at).toISOString()}` : ""}`,
35
+ });
36
+ }
37
+
38
+ /** Extra result facts of a `quota.exhausted` deferral: the earliest reset, so the batch holds until then. */
39
+ export const quotaFacts = (e) => (e?.deferCode === OUTCOME_CODES.QUOTA_EXHAUSTED && Number.isFinite(e.resetAtEpochMs) ? { resetAtEpochMs: e.resetAtEpochMs, resetAt: e.resetAt } : {});
@@ -33,6 +33,16 @@ describe("in-batch recovery of mechanical needs-human (#4267)", () => {
33
33
  const NH = (code, detail = `ended ${code}`, more = {}) => ({ terminalReason: "needs-human", code, detail, ...more });
34
34
  const byIssue = (rows) => Object.fromEntries(rows.map((r) => [r.issue, r]));
35
35
 
36
+ it("#5232: a recovery attempt repeating the same env.repro_unrunnable is not rebuilt again; a different signature still recovers", async () => {
37
+ const same = NH("env.repro_unrunnable", "repro test t (`uv run --with x pytest t.py`): could not run");
38
+ const r = await batch({ 1: [same, same] }, {}, { recovery: { maxAttempts: 1, mechanicalMaxAttempts: 3 } });
39
+ assert.deepEqual(r.calls.map((c) => c.recover?.attempt ?? 0), [0, 1]);
40
+ assert.match(byIssue(r.rows)[1].detail, /Environment defect.*uv run --with x pytest/s);
41
+ assert.ok(r.decisions.some((d) => /no further recovery for env\.repro_unrunnable/.test(d.what)));
42
+ const d = await batch({ 2: [NH("env.repro_unrunnable", "cmd A"), NH("env.repro_unrunnable", "cmd B"), { terminalReason: "merged" }] }, {}, { recovery: { maxAttempts: 1, mechanicalMaxAttempts: 3 } });
43
+ assert.deepEqual(d.calls.map((c) => c.recover?.attempt ?? 0), [0, 1, 2]);
44
+ });
45
+
36
46
  it("#4725: mechanical codes get their own budget (2), apart from the conformance one; an open-PR base conflict is not parked while it remains", async () => {
37
47
  const { rows, calls } = await batch({ 1: [NH("base.conflict", "conflicts", { pr: 50 }), NH("base.conflict", "conflicts", { pr: 50 }), { terminalReason: "merged", pr: 50 }] },
38
48
  {}, { recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 } });
@@ -399,7 +409,7 @@ describe("#4298 staging-review follow-ups: recovery", () => {
399
409
 
400
410
  it("run-issue rejects --recover on the legacy --path full", async () => {
401
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" } }),
402
- /--recover is not supported with --path full/);
412
+ /--recover only works with the default pipeline/);
403
413
  });
404
414
 
405
415
  it("/orchestrate spec describes terminal non-human needs-human rows, --recover scope and the schedd resume scope", () => {
@@ -0,0 +1,73 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Relaxation gate (#5237). A change that relaxes a detector, validator, gate or classifier inside a declared
5
+ * `review.risk_paths` glob (a new accept/rescue/allow branch, a removed deny) is reviewed adversarially: it needs at least
6
+ * one added negative test per relaxed file (`conformance.unimplemented`, kind `relaxation_untested`), the reviewer and the
7
+ * independent verifier get the relaxed hunks with a counterexample brief. Deterministic, 0 LLM calls for the detection.
8
+ * The match is syntactic: the verifier covers what a pattern cannot.
9
+ */
10
+ import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
11
+ import { riskPathHits } from "./review-trigger.mjs";
12
+
13
+ const TEST_PATH = /(^|\/)(tests?|__tests__|specs?|e2e)\/|\.(test|spec)\.[a-z0-9]+$|(^|\/)test_[^/]*$|_test\.[a-z0-9]+$|(^|\/)conftest\.py$/i;
14
+ const COMMENT = /^\s*(#|\/\/|\*|\/\*|--)/;
15
+ const ACCEPT_RETURN = /\b(?:return|=>)\s*\(?\s*(?:true|True|ok|allow(?:ed)?|accept(?:ed)?|benign|valid|pass(?:ed)?)\b/;
16
+ const ACCEPT_NAME = /\b\w*(?:rescue|allowlist|whitelist|safelist|benign|exempt|bypass|allow|accept)\w*\b/i;
17
+ const DENY = /\b(?:raise|throw)\b|\breturn\s+(?:false|False|deny|denied|block|blocked|reject|rejected)\b|\b(?:deny|reject|blocked)\w*\s*[=(]/;
18
+ const NEGATIVE = /assertFalse|assert\s+not\b|assert_not|\.not\.|toBe\(false\)|toBeFalsy|toThrow|rejects|pytest\.raises|assert_raises|assert\.(?:throws|rejects|ok\(!|equal\(.*,\s*false\))|\b(?:must|should)(?:\s+still)?\s+(?:be\s+)?(?:detect|block|reject|deny|refuse|fail)|not[ _](?:accept|allow|benign|rescue)|negative|counterexample|still[ _](?:detected|blocked|rejected)/i;
19
+
20
+ export const isRelaxationTestPath = (p) => TEST_PATH.test(String(p));
21
+
22
+ /** Per-file added/removed lines of a unified diff: [{file, added: [{line, text}], removed: [text]}]. */
23
+ function parseDiff(diff) {
24
+ const out = [];
25
+ let cur = null, n = 0;
26
+ for (const l of String(diff ?? "").split("\n")) {
27
+ const f = /^diff --git a\/.* b\/(.*)$/.exec(l);
28
+ if (f) { cur = { file: f[1], added: [], removed: [] }; out.push(cur); continue; }
29
+ if (!cur) continue;
30
+ const h = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(l);
31
+ if (h) { n = Number(h[1]); continue; }
32
+ if (l.startsWith("+++") || l.startsWith("---")) continue;
33
+ if (l.startsWith("+")) cur.added.push({ line: n++, text: l.slice(1) });
34
+ else if (l.startsWith("-")) cur.removed.push(l.slice(1));
35
+ }
36
+ return out;
37
+ }
38
+
39
+ const excerpt = (t) => String(t).trim().replace(/\s+/g, " ").slice(0, 160);
40
+
41
+ /**
42
+ * `{relaxations: [{file, line, class, excerpt}], negatives}` for a `git diff -U0 base...HEAD`. Only non-test files matching a
43
+ * declared review.risk_paths glob count; `negatives` is the number of negative assertions added in changed test files.
44
+ */
45
+ export function analyzeRelaxations({ diff = "", riskPaths = [] } = {}) {
46
+ const files = parseDiff(diff);
47
+ const risky = new Set(riskPathHits(files.map((f) => f.file).filter((f) => !isRelaxationTestPath(f)), riskPaths));
48
+ const relaxations = [];
49
+ let negatives = 0;
50
+ for (const f of files) {
51
+ if (isRelaxationTestPath(f.file)) { negatives += f.added.filter((a) => NEGATIVE.test(a.text)).length; continue; }
52
+ if (!risky.has(f.file)) continue;
53
+ const code = f.added.filter((a) => !COMMENT.test(a.text));
54
+ for (const a of code) if (ACCEPT_RETURN.test(a.text) || ACCEPT_NAME.test(a.text)) relaxations.push({ file: f.file, line: a.line, class: "accept", excerpt: excerpt(a.text) });
55
+ const removedDeny = f.removed.filter((t) => !COMMENT.test(t) && DENY.test(t));
56
+ if (removedDeny.length > code.filter((a) => DENY.test(a.text)).length) relaxations.push({ file: f.file, line: code[0]?.line ?? 1, class: "deny_removed", excerpt: excerpt(removedDeny[0]) });
57
+ }
58
+ return { relaxations, negatives };
59
+ }
60
+
61
+ /** One blocking failure when the diff has fewer added negative assertions than relaxed files; [] otherwise. */
62
+ export function relaxationFailures({ relaxations = [], negatives = 0 } = {}) {
63
+ const files = [...new Set(relaxations.map((r) => r.file))];
64
+ if (!files.length || negatives >= files.length) return [];
65
+ return [{ code: OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, kind: "relaxation_untested", detail: `${files.slice(0, 3).join(", ")} relax${files.length === 1 ? "es" : ""} a rule in a declared review.risk_paths path (${relaxations.slice(0, 2).map((r) => `${r.file}:${r.line} ${r.class}`).join("; ")}) but the diff adds ${negatives} negative test(s) for ${files.length} relaxed file(s): add a test that the inputs the relaxed rule must still reject are rejected` }];
66
+ }
67
+
68
+ /** The <relaxation_checks> block for the reviewer and the verifier prompts; "" when nothing was relaxed. */
69
+ export function relaxationBlock(relaxations = []) {
70
+ if (!relaxations.length) return "";
71
+ const rows = relaxations.slice(0, 20).map((r) => `- ${r.file}:${r.line} (${r.class}): ${r.excerpt}`).join("\n");
72
+ return `\n<relaxation_checks>\nThis diff relaxes a rule in a declared risk path (a new accept/rescue/allow branch or a removed deny):\n${rows}\nPositive cases passing is not evidence. For each relaxation: (1) name the inputs the relaxed rule now accepts that it must not (for a detector: the project's challenge, block or negative-corpus pages and fixtures), (2) trace or run them through the changed code, (3) check a negative test exists for the new accept class. Report each accepted counterexample and each missing negative test as a regressions row with path:line (it blocks the merge).\n</relaxation_checks>`;
73
+ }
@@ -0,0 +1,54 @@
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 { analyzeRelaxations, relaxationFailures, relaxationBlock, isRelaxationTestPath } from "./relaxation.mjs";
6
+ import { reviewerPrompt } from "./prompts.mjs";
7
+ import { verifierPrompt } from "./verifier.mjs";
8
+
9
+ const hunk = (file, lines, start = 10) => `diff --git a/${file} b/${file}\n@@ -1,0 +${start},${lines.length} @@\n${lines.map((l) => `+${l}`).join("\n")}\n`;
10
+ const removal = (file, lines) => `diff --git a/${file} b/${file}\n@@ -3,${lines.length} +3,0 @@\n${lines.map((l) => `-${l}`).join("\n")}\n`;
11
+ // modelled on AlterLab #39954: a "thin stub" rescue whose script_redirect class accepts JS cookie challenges
12
+ const RESCUE = hunk("shared/detection/antibot.py", ["def thin_stub_rescue(html):", " if SCRIPT_REDIRECT.search(html): # document.cookie=...; location.href=...", " return True"]);
13
+ const NEG = hunk("tests/test_antibot.py", ["def test_cookie_challenge_not_benign():", " assert not thin_stub_rescue(COOKIE_CHALLENGE)"]);
14
+ const GLOBS = ["shared/detection/**"];
15
+
16
+ describe("#5237 relaxation detector", () => {
17
+ it("replay of #39954: the cookie-challenge acceptance is flagged and blocks without a negative test", () => {
18
+ const a = analyzeRelaxations({ diff: RESCUE, riskPaths: GLOBS });
19
+ assert.ok(a.relaxations.length >= 1);
20
+ assert.equal(a.relaxations[0].file, "shared/detection/antibot.py");
21
+ assert.ok(a.relaxations.some((r) => /return True/.test(r.excerpt)));
22
+ const f = relaxationFailures(a);
23
+ assert.equal(f.length, 1); assert.equal(f[0].code, "conformance.unimplemented"); assert.equal(f[0].kind, "relaxation_untested");
24
+ });
25
+ it("a positive-only test does not satisfy the requirement; a negative test does", () => {
26
+ const pos = hunk("tests/test_antibot.py", ["def test_thin_page_ok():", " assert thin_stub_rescue(THIN_PAGE) is True"]);
27
+ assert.equal(relaxationFailures(analyzeRelaxations({ diff: RESCUE + pos, riskPaths: GLOBS })).length, 1);
28
+ const a = analyzeRelaxations({ diff: RESCUE + NEG, riskPaths: GLOBS });
29
+ assert.ok(a.negatives >= 1); assert.deepEqual(relaxationFailures(a), []);
30
+ });
31
+ it("a removed deny is a relaxation", () => {
32
+ const a = analyzeRelaxations({ diff: removal("shared/detection/rules.py", [" if challenge(html):", " raise Blocked()"]), riskPaths: GLOBS });
33
+ assert.deepEqual(a.relaxations.map((r) => r.class), ["deny_removed"]);
34
+ });
35
+ it("ignores files outside the declared globs, test files, comments, and an empty glob list", () => {
36
+ assert.deepEqual(analyzeRelaxations({ diff: RESCUE, riskPaths: ["billing/**"] }).relaxations, []);
37
+ assert.deepEqual(analyzeRelaxations({ diff: RESCUE, riskPaths: [] }).relaxations, []);
38
+ assert.deepEqual(analyzeRelaxations({ diff: hunk("shared/detection/x.py", ["# return True when benign"]), riskPaths: GLOBS }).relaxations, []);
39
+ assert.deepEqual(analyzeRelaxations({ diff: hunk("shared/detection/test_x.py", [" return True"]), riskPaths: GLOBS }).relaxations, []);
40
+ assert.ok(isRelaxationTestPath("tests/a.py") && isRelaxationTestPath("src/a.test.ts") && !isRelaxationTestPath("src/a.ts"));
41
+ assert.deepEqual(analyzeRelaxations({ diff: "", riskPaths: GLOBS }), { relaxations: [], negatives: 0 });
42
+ });
43
+ it("prompts carry the relaxed hunks; unchanged without relaxations", () => {
44
+ const { relaxations } = analyzeRelaxations({ diff: RESCUE, riskPaths: GLOBS });
45
+ const blk = relaxationBlock(relaxations);
46
+ assert.match(blk, /<relaxation_checks>[\s\S]*antibot\.py:\d+[\s\S]*negative-corpus/);
47
+ const base = { issue: { number: 1, title: "t", body: "b" }, contract: {}, diff: "d", files: ["a"] };
48
+ assert.doesNotMatch(verifierPrompt(base), /relaxation_checks/);
49
+ assert.match(verifierPrompt({ ...base, relaxations }), /<relaxation_checks>/);
50
+ assert.doesNotMatch(reviewerPrompt({ ...base, result: {} }), /relaxation_checks/);
51
+ assert.match(reviewerPrompt({ ...base, result: {}, relaxations }), /<relaxation_checks>/);
52
+ assert.equal(relaxationBlock([]), "");
53
+ });
54
+ });
@@ -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
+ });