forgedock 1.51.0 → 1.53.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 (103) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -0
  2. package/bin/engine/telemetry-seam.mjs +4 -2
  3. package/bin/engine-cli.mjs +61 -17
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +25 -1
  7. package/bin/lean/account-watch.mjs +28 -0
  8. package/bin/lean/account-watch.test.mjs +30 -0
  9. package/bin/lean/activation.mjs +20 -0
  10. package/bin/lean/activation.test.mjs +14 -1
  11. package/bin/lean/basered.mjs +115 -0
  12. package/bin/lean/basered.test.mjs +66 -0
  13. package/bin/lean/batch-health.mjs +40 -6
  14. package/bin/lean/batch-health.test.mjs +34 -1
  15. package/bin/lean/batch.mjs +41 -2
  16. package/bin/lean/batch.test.mjs +104 -2
  17. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  18. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  19. package/bin/lean/conformance.e2e.test.mjs +1 -1
  20. package/bin/lean/conformance.mjs +205 -23
  21. package/bin/lean/conformance.test.mjs +164 -3
  22. package/bin/lean/context.mjs +27 -17
  23. package/bin/lean/context.test.mjs +15 -0
  24. package/bin/lean/effects.mjs +11 -7
  25. package/bin/lean/execution.mjs +19 -3
  26. package/bin/lean/execution.test.mjs +39 -0
  27. package/bin/lean/findinglabel.mjs +16 -0
  28. package/bin/lean/findinglabel.test.mjs +39 -0
  29. package/bin/lean/heavy.mjs +6 -3
  30. package/bin/lean/hostload.mjs +78 -0
  31. package/bin/lean/hostload.test.mjs +117 -0
  32. package/bin/lean/hotspots-remote.e2e.test.mjs +71 -0
  33. package/bin/lean/issuewatch-release.mjs +6 -2
  34. package/bin/lean/issuewatch-release.test.mjs +16 -0
  35. package/bin/lean/issuewatch.mjs +11 -1
  36. package/bin/lean/lanelock.mjs +14 -0
  37. package/bin/lean/lean.mjs +171 -36
  38. package/bin/lean/lean.test.mjs +302 -10
  39. package/bin/lean/light.mjs +48 -7
  40. package/bin/lean/light.test.mjs +37 -3
  41. package/bin/lean/limits.test.mjs +142 -9
  42. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  43. package/bin/lean/orchestrate.mjs +110 -26
  44. package/bin/lean/postdeploy-check.test.mjs +39 -0
  45. package/bin/lean/prompts.mjs +8 -7
  46. package/bin/lean/quota.mjs +39 -0
  47. package/bin/lean/recovery.test.mjs +10 -0
  48. package/bin/lean/relaxation.mjs +73 -0
  49. package/bin/lean/relaxation.test.mjs +54 -0
  50. package/bin/lean/release-postmerge.mjs +119 -0
  51. package/bin/lean/release-rehearsal.mjs +63 -0
  52. package/bin/lean/release-rehearsal.test.mjs +93 -0
  53. package/bin/lean/release-review.e2e.test.mjs +77 -0
  54. package/bin/lean/release-review.mjs +198 -0
  55. package/bin/lean/release-review.test.mjs +180 -0
  56. package/bin/lean/release.mjs +228 -0
  57. package/bin/lean/release.test.mjs +292 -0
  58. package/bin/lean/rotator.mjs +150 -31
  59. package/bin/lean/rotator.test.mjs +105 -2
  60. package/bin/lean/sandbox-remote.mjs +9 -2
  61. package/bin/lean/schedd.mjs +56 -6
  62. package/bin/lean/schedd.test.mjs +108 -6
  63. package/bin/lean/verifier.mjs +3 -2
  64. package/bin/lean/verify.mjs +2 -1
  65. package/bin/lean/verify.test.mjs +6 -0
  66. package/bin/pool/agent.mjs +18 -4
  67. package/bin/pool/router.mjs +68 -25
  68. package/bin/review-staging.mjs +23 -0
  69. package/bin/stats/conformance-outcomes.mjs +208 -0
  70. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  71. package/bin/stats/depth.mjs +218 -0
  72. package/bin/stats/depth.test.mjs +133 -0
  73. package/bin/stats/experiment.mjs +7 -5
  74. package/bin/stats/github-source.mjs +2 -2
  75. package/bin/stats/index.mjs +64 -2
  76. package/bin/stats/local-source.mjs +11 -0
  77. package/bin/stats/query.mjs +69 -0
  78. package/bin/stats/selffiled.mjs +52 -0
  79. package/bin/stats/selffiled.test.mjs +71 -0
  80. package/commands/orchestrate.md +1 -1
  81. package/commands/review-pr-agents/security.md +4 -0
  82. package/commands/review-pr-staging.md +2 -0
  83. package/commands/work-on/build.md +4 -6
  84. package/docs/CONFIG.md +66 -8
  85. package/docs/ISSUE-WATCH.md +2 -0
  86. package/docs/OUTCOME-CODES.md +3 -0
  87. package/docs/STATS.md +44 -0
  88. package/docs/TELEMETRY.md +1 -1
  89. package/package.json +1 -1
  90. package/pool/README.md +1 -1
  91. package/pool/image/cs-cred +14 -1
  92. package/pool/install/install-agent.ps1 +6 -2
  93. package/scripts/backfill-finding-labels.mjs +50 -0
  94. package/scripts/backfill-finding-labels.test.mjs +36 -0
  95. package/scripts/doctor-pipeline-state.sh +21 -6
  96. package/scripts/file-deferred-followups.sh +60 -238
  97. package/scripts/file-deferred-followups.test.sh +99 -187
  98. package/scripts/followup-route.mjs +12 -0
  99. package/scripts/hotspots.sh +12 -8
  100. package/scripts/hotspots.test.sh +22 -0
  101. package/scripts/owner-route-parity.test.sh +17 -1
  102. package/scripts/prior-attempts.test.mjs +1 -1
  103. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -21,7 +21,7 @@
21
21
  * before scheduling, so a live lane does not hold up the others.
22
22
  * `deferred` is a scheduling fact, not an end: each typed code is requeued with its retry-at (`deferPolicy`), a usage
23
23
  * limit (and #5168 a claude login failure, `backend.auth`) holds admissions for that account until its reset, and deferrals other than a wait (`host.busy`,
24
- * `sandbox.capacity`, #4528; `sandbox.unreachable`, #4788; `rate_limited`, #4784; `backend.auth`, #5168) stop after `maxDeferrals`.
24
+ * `sandbox.capacity`, #4528; `sandbox.unreachable`, #4788; `rate_limited`, #4784; `backend.auth`, #5168; `quota.exhausted`, #5236) stop after `maxDeferrals`.
25
25
  * #5161: an engine-error whose detail is a transport/gateway failure (`isTransientEngineError`) is requeued with backoff
26
26
  * (`transientRetryDelayMs`) up to `transientRetries` times, not counted against `ENGINE_ERROR_RELAUNCHES`; then it ends engine-error.
27
27
  * #5112: with `remote.offlineFallback` (`execution.fallback_local`), an issue deferred `remote.capacityFallbackAfter` times (default
@@ -30,7 +30,10 @@
30
30
  * host; in memory when absent): admission checks the hold of `identity()`, the account the next lane would use. While held, the
31
31
  * batch re-reads the store every `pollMs` (#4446), so `forgedock limits clear` admits on the next poll, not at the reset.
32
32
  * #5095: `remote.identity()` names the pool's account (execution.mjs `remoteHoldId`); while it is held, a remote-placed lane
33
- * runs local in hybrid (`fallbackLocal`, local account not held) or waits for the reset; admission is not held. An `engine-error` is
33
+ * runs local in hybrid (`fallbackLocal`, local account not held) or waits for the reset; admission is not held. #5203: under a
34
+ * rotator with headroom a pool usage limit reruns at once (`quotaRequeue` `poolId`) and records no pool hold; with no headroom the
35
+ * hold lasts until `rotator.resumeAt()` (the earliest reset). `--requeue` of a quota-paused pending issue clears its notBefore
36
+ * and the pool hold (`drainRequeues`). An `engine-error` is
34
37
  * relaunched once; `breaker` ({errors, window_min}) stops admissions after a burst and lets running lanes finish, the
35
38
  * rest stay pending (outcome `held`) for a resume. `getParallel()` is read on every pass, so K can change live.
36
39
  * #5138: `remote.max`, `remote.fallbackLocal` and `remote.place` are read on every grant too (engine-cli puts live getters on
@@ -87,6 +90,8 @@
87
90
  * With `remote.fallbackLocal`, a lane placed remote runs on the host path instead of waiting when `max` remote lanes run,
88
91
  * and instead of stopping when the budget refuses. The final `{where, reason}` is kept on the run record and the row as
89
92
  * `placement` and passed to `runOne` as `ctx.placement` (the lane records it in its FORGE:STATE).
93
+ * #5174: `overload() -> {overloaded, ...}` (hostload.mjs `liveOverload`) holds every new non-remote admission while the
94
+ * host is overloaded (retry after `pollMs`), with one `host-overloaded` row per episode; remote placements are never held.
90
95
  *
91
96
  * In-batch recovery (#4267), on by default: this module recovers only when `recovery: {maxAttempts}` is passed, and the
92
97
  * CLI always passes it (forge.yaml `orchestration.recovery.max_attempts`, default 1; 0 disables): a row `classifyNeedsHuman` calls
@@ -127,6 +132,7 @@ import { makeCapWait } from "./capwait.mjs";
127
132
  import { mapLimit } from "./pmap.mjs";
128
133
  import { quotaRequeue } from "./rotator.mjs";
129
134
  import { joinsDecomposed, addsEpicChildren, selectChildren, edgeText, DEFAULT_POLL_S } from "./autochildren.mjs";
135
+ import { formatOverload } from "./hostload.mjs";
130
136
 
131
137
  // A dependency that finished like this no longer blocks its dependents.
132
138
  const SATISFIED = new Set(["merged", "invalid"]);
@@ -232,7 +238,7 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
232
238
  const code = r?.code ?? null;
233
239
  if (UNCAPPED_DEFERRALS.has(code)) return { delayMs: (posNum(r?.retryInSeconds) ?? HOST_BUSY_RETRY_S) * 1000, host: true };
234
240
  // #4784: a usage limit is a known-time wait gated by the account hold, never capped.
235
- if (code === "rate_limited") {
241
+ if (code === "rate_limited" || code === "quota.exhausted") { // #5236: no account has capacity: held until the earliest reset
236
242
  const at = posNum(r?.resetAtEpochMs) && r.resetAtEpochMs > now ? r.resetAtEpochMs : now + (posNum(r?.retryInSeconds) ?? RATE_LIMIT_FALLBACK_S) * 1000;
237
243
  return { delayMs: at - now, hold: true };
238
244
  }
@@ -248,6 +254,10 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
248
254
  return { delayMs: Math.min(DEFER_BACKOFF_S * 2 ** (k - 1), DEFER_BACKOFF_MAX_S) * 1000 };
249
255
  }
250
256
 
257
+ // #5241: a cancel re-sends a stop that was not accepted every STOP_RETRY_MS and reports a lane still running after STOP_TIMEOUT_MS.
258
+ const STOP_RETRY_MS = 15 * 1000;
259
+ const STOP_TIMEOUT_MS = 120 * 1000;
260
+
251
261
  const cancellableSleep = (ms, signal) => new Promise((res) => {
252
262
  const t = setTimeout(res, ms);
253
263
  signal?.addEventListener("abort", () => { clearTimeout(t); res(); }, { once: true });
@@ -299,9 +309,9 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
299
309
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), onUpdate = () => {}, onCrossLane = () => {},
300
310
  store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000,
301
311
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
302
- recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, getBlocked = null, trusted = null, getGates = null, stopLane = null,
312
+ recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
303
313
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
304
- getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES }) {
314
+ getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null }) {
305
315
  const saved = store?.load?.() ?? null;
306
316
  const order = saved ? [...saved.order] : [];
307
317
  const set = new Set(order);
@@ -327,10 +337,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
327
337
  let errorTimes = [...(saved?.errorTimes ?? [])];
328
338
  // A legacy batch-local `holdUntil` (pre-#4190) names no account and is ignored: a same-account lane re-sets the hold.
329
339
  const holds = limits ?? memoryLimits(now);
340
+ // #5205: accounts lanes reported limited (account -> until ms), persisted with the batch, excluded from headroom until then.
341
+ const limitedAccounts = toMap(saved?.limitedAccounts);
342
+ const excluded = () => { for (const [k, u] of limitedAccounts) if (!(Number(u) > now())) limitedAccounts.delete(k); return limitedAccounts; };
343
+ const noteLimited = (r) => { for (const l of Array.isArray(r?.limited) ? r.limited : []) { const a = Number(l?.account), u = Number(l?.until); if (Number.isInteger(a) && a > 0 && Number.isFinite(u)) limitedAccounts.set(a, Math.max(u, Number(limitedAccounts.get(a)) || 0)); } };
330
344
  // #5094: with an account rotator, admissions stop only when no account has headroom, and resume when the first one resets.
331
345
  const rotatorHold = () => {
332
346
  if (!rotator) return undefined;
333
- try { if (rotator.headroom()) return null; const u = rotator.resumeAt(); return Number.isFinite(u) && u > now() ? u : undefined; } catch { return undefined; }
347
+ try { if (rotator.headroom(excluded())) return null; const u = rotator.resumeAt(excluded()); return Number.isFinite(u) && u > now() ? u : undefined; } catch { return undefined; }
334
348
  };
335
349
  const heldUntil = () => {
336
350
  const r = rotatorHold();
@@ -388,6 +402,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
388
402
  const recoveryMax = Number.isInteger(recovery?.maxAttempts) && recovery.maxAttempts > 0 ? recovery.maxAttempts : 0;
389
403
  // #4725: mechanical/env codes recover on their own budget (>= the conformance one); 0 maxAttempts still turns recovery off.
390
404
  const mechMax = recoveryMax && Number.isInteger(recovery?.mechanicalMaxAttempts) && recovery.mechanicalMaxAttempts > 0 ? Math.max(recovery.mechanicalMaxAttempts, recoveryMax) : recoveryMax;
405
+ const REPEAT_ENV_CODES = [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, OUTCOME_CODES.ENV_TOOL_MISSING]; // #5232: deterministic for a frozen command (a timeout is load, not listed)
406
+ const sigOf = (d) => String(d ?? "").replace(/\s+/g, " ").trim();
391
407
  const maxFor = (cls) => (cls === "mechanical" ? mechMax : recoveryMax);
392
408
  const classUsed = toMap(saved?.recoveryClasses); // `${issue}:${class}` -> recovery lanes launched in that class
393
409
  const recoveries = toMap(saved?.recoveries); // issue -> recovery lanes launched (#4267)
@@ -404,8 +420,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
404
420
  let halted = false; // #4454: stopped by `signal`; the batch's state is no longer this process's to write
405
421
  const save = () => {
406
422
  if (!store || halted) return;
407
- store.save({ v: 1, ...(setup ? { phase: "setup", setup: { ...setup } } : {}), order, deps: toObj(deps), lanes: toObj(lanes), crossSeen: [...crossSeen], results: toObj(results), running: toObj(runRecs),
408
- pending, notBefore: toObj(notBefore), requeues: toObj(requeues), deferrals: toObj(deferrals), engineErrors: toObj(engineErrors), ...(transients.size ? { transientRetries: toObj(transients) } : {}), ...(quota.size ? { quota: toObj(quota) } : {}), ...(capDefers.size ? { capDeferrals: toObj(capDefers) } : {}),
423
+ store.save({ v: 1, ...(setup ? { phase: "setup", setup: { ...setup } } : {}), engineVersion: version, order, deps: toObj(deps), lanes: toObj(lanes), crossSeen: [...crossSeen], results: toObj(results), running: toObj(runRecs),
424
+ pending, notBefore: toObj(notBefore), requeues: toObj(requeues), deferrals: toObj(deferrals), engineErrors: toObj(engineErrors), ...(transients.size ? { transientRetries: toObj(transients) } : {}), ...(quota.size ? { quota: toObj(quota) } : {}), ...(limitedAccounts.size ? { limitedAccounts: toObj(limitedAccounts) } : {}), ...(capDefers.size ? { capDeferrals: toObj(capDefers) } : {}),
409
425
  prefilter: toObj(checked), errorTimes, breaker: tripped, ...(budget ? { classes: toObj(classes), dispatch: { ...dispatch } } : {}),
410
426
  ...(reg ? { priorities: toObj(priorities) } : {}), ...(sandboxUse.size ? { sandbox: toObj(sandboxUse) } : {}),
411
427
  ...(recoveries.size || recovering.size ? { recoveries: toObj(recoveries), recovering: toObj(recovering), recoveryClasses: toObj(classUsed) } : {}),
@@ -594,6 +610,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
594
610
  };
595
611
  // A host slot for `n` (a lane-refused issue runs nothing and needs none); refused: `n` stays queued in the registry.
596
612
  // true: start it; false: no capacity now; "busy" (#4481): another batch runs `n`, try the next issue.
613
+ let overloadNoted = false; // #5174: one host-overloaded row per overload episode
597
614
  const grant = (n, wanted) => {
598
615
  if (lanes.get(n)?.ok === false) return true;
599
616
  let p = placeOf(n);
@@ -653,6 +670,16 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
653
670
  p = { where: "local", reason: `fallback to local: execution budget: ${adm.reason}` };
654
671
  }
655
672
  }
673
+ if (p?.where !== "remote" && overload) {
674
+ let snap = null;
675
+ try { snap = overload(); } catch { snap = null; }
676
+ if (snap?.overloaded) {
677
+ if (!overloadNoted) { overloadNoted = true; update({ issue: null, outcome: "host-overloaded", detail: formatOverload(snap) }); }
678
+ notBefore.set(n, now() + Math.max(pollMs, 1));
679
+ return false;
680
+ }
681
+ overloadNoted = false;
682
+ }
656
683
  if (!reg) { if (p) placed.set(n, p); return true; }
657
684
  const r = reg.tryAcquire(keyOf(n), entryOf(n), liveCap());
658
685
  if (!r?.ok && r?.conflict != null) return busy(n, r.conflict, wanted);
@@ -691,6 +718,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
691
718
  // Apply one lane's result: requeue it (deferred, dependency-open, engine-error) or record its final row.
692
719
  const settle = async (n, r, rec, pf) => {
693
720
  if (halted) return; // #4454: a resume adopts the lane and settles it
721
+ if (cancelled && releaseLease) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } } // #5241: the lane ended: its lease goes with it
694
722
  // #4304: the pre-filter runs once per issue; a recovery pass's row adds the earlier attempt's cost, which already holds it.
695
723
  const pfCost = recovering.has(n) ? 0 : (pf?.cost_usd ?? 0);
696
724
  const row = { issue: n, outcome: r?.terminalReason ?? "engine-error", pr: r?.pr ?? null, cost_usd: (r?.cost_usd ?? 0) + pfCost, minutes: Math.round((now() - rec.startedAt) / 6000) / 10, detail: r?.detail, ...(r?.code ? { code: r.code } : {}), ...(pf ? { prefilter: pf } : {}),
@@ -703,7 +731,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
703
731
  ...(r?.turns && typeof r.turns === "object" ? { turns: r.turns } : {}), // #4392
704
732
  ...(r?.conformance && typeof r.conformance === "object" ? { conformance: r.conformance } : {}), // #4398
705
733
  ...(rec?.placement ? { placement: rec.placement } : {}), ...(estimates.has(n) ? { est_minutes: Math.round(estimates.get(n) * 10) / 10 } : {}) }; // #4409
706
- const quotaPause = row.outcome === "deferred" && r?.code === "rate_limited" && !cancelled;
734
+ noteLimited(r); // #5205
735
+ const quotaPause = row.outcome === "deferred" && (r?.code === "rate_limited" || r?.code === "quota.exhausted") && !cancelled;
707
736
  if (!quotaPause && quota.has(n)) { // #5094: the paused attempts' cost, added once
708
737
  const q = quota.get(n); quota.delete(n);
709
738
  row.cost_usd = Math.round(((Number(row.cost_usd) || 0) + (Number(q.cost_usd) || 0)) * 1e6) / 1e6;
@@ -783,21 +812,33 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
783
812
  let delayMs = pol.delayMs;
784
813
  if (pol.hold) {
785
814
  // #5094: an account rotator with headroom means another account runs the next call, so no host hold is recorded.
786
- const rq = quotaRequeue({ rotator, r, prior: quota.get(n), delayMs: pol.delayMs });
815
+ // #5203: a usage limit on the pool account rotates like a rotator account (the router hands the next sandbox the
816
+ // lowest-usage login, #5165), so it sets no pool hold and no batch-wide notBefore while any account has headroom.
817
+ const usage = r?.code === "rate_limited" || r?.code === "quota.exhausted";
818
+ let poolId = null;
819
+ if (usage) { try { poolId = remote?.identity?.() ?? null; } catch { poolId = null; } }
820
+ const rq = quotaRequeue({ rotator, r, prior: quota.get(n), delayMs: pol.delayMs, exclude: excluded(), poolId });
821
+ // #5205: no account with room: hold until the rotator's earliest reset (tokenbaton's, over every account), not now+delay
822
+ let rotAt = null;
823
+ if (!rq && rotator && (!r?.backendId || (poolId && r.backendId === poolId) || (() => { try { return rotator.isAccount(r.backendId); } catch { return false; } })())) { // a remote credential keeps its own reset
824
+ try { const p = typeof rotator.pick === "function" ? rotator.pick({ exclude: excluded() }) : null; rotAt = p && p.account === null && Number.isFinite(p.earliestReset) ? p.earliestReset : rotator.resumeAt(excluded()); } catch { rotAt = null; }
825
+ if (!(Number.isFinite(rotAt) && rotAt > now())) rotAt = null;
826
+ }
827
+ // #5203: no account has headroom: the hold lasts until the earliest reset across accounts, not this lane's own reset.
828
+ const holdMs = usage && rotAt !== null ? rotAt - now() : pol.delayMs;
787
829
  if (rq) {
788
830
  delayMs = rq.delayMs;
789
831
  // #5095 + #5094: the pool account's own hold (not the host's) still routes hybrid lanes local until its reset.
790
832
  try { const pool = remote?.identity?.(); if (!rq.rotated && pool && r?.backendId === pool) holds.set(pool, now() + pol.delayMs, `batch ${batchId ?? "?"} #${n}`); } catch { /* fail-open */ }
791
- } else try { holds.set(r?.backendId ?? identity(), now() + pol.delayMs, `batch ${batchId ?? "?"} #${n}`); delayMs = 0; } catch { /* fail-open */ }
833
+ } else try { holds.set(r?.backendId ?? identity(), rotAt ?? now() + holdMs, `batch ${batchId ?? "?"} #${n}`); delayMs = 0; } catch { /* fail-open */ }
792
834
  const q = quota.get(n) ?? { cost_usd: 0, minutes: 0, rotations: 0 };
793
- let rotAt = null;
794
- if (!rq && rotator) { try { rotAt = rotator.resumeAt(); } catch { rotAt = null; } }
795
- const resumeAt = Math.max(now() + (rq ? rq.delayMs : pol.delayMs), Number.isFinite(rotAt) ? rotAt : 0);
835
+ const resumeAt = usage ? now() + (rq ? rq.delayMs : holdMs) : Math.max(now() + (rq ? rq.delayMs : pol.delayMs), rotAt ?? 0);
796
836
  quota.set(n, { cost_usd: Math.round(((Number(q.cost_usd) || 0) + (Number(row.cost_usd) || 0)) * 1e6) / 1e6, minutes: Math.round(((Number(q.minutes) || 0) + (Number(row.minutes) || 0)) * 10) / 10,
797
- resumeAt, rotations: (q.rotations ?? 0) + (rq?.rotated ? 1 : 0) });
837
+ resumeAt, rotations: (q.rotations ?? 0) + (rq?.rotated ? 1 : 0) + (Number(r?.rotations) || 0) }); // #5205: plus the lane's own in-phase rotations
798
838
  requeue(n, delayMs); done(); save();
799
839
  const iso = new Date(resumeAt).toISOString();
800
840
  update({ ...row, outcome: "paused", quota: { resumeAt: iso }, detail: `paused (${r?.code === "backend.auth" ? "backend.auth" : "quota"}) until ${iso}: ${r?.code ?? "deferred"}${r?.detail ? ` ${r.detail}` : ""}` });
841
+ if (r?.code === "quota.exhausted") { const ev = { event: "quota.exhausted", issue: n, batch: batchId ?? null, resumeAt: iso, detail: `quota.exhausted: no account has capacity; resuming ${iso}` }; try { store?.log?.(ev); } catch { /* best effort */ } onUpdate(ev); } // #5236: batch-level event supervisors see
801
842
  return;
802
843
  }
803
844
  requeue(n, capGated ? 0 : delayMs); done(); save();
@@ -861,7 +902,13 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
861
902
  const facts = { ...row, issueEdited: r?.issueEdited === true, quoteMismatch: r?.quoteMismatch === true, conflicting: isConflicting };
862
903
  if (prior) { const pk = `${n}:${recoveryClassOf({ code: prior.code })}`; classUsed.set(pk, Math.max(classUsed.get(pk) ?? 0, prior.attempt)); } // state saved before #4725 has no class counts
863
904
  const cls = recoveryClassOf(facts), max = maxFor(cls), used = classUsed.get(`${n}:${cls}`) ?? 0;
864
- if (classifyNeedsHuman(facts) === "recoverable" && used < max) {
905
+ // #5232: a deterministic env defect of the frozen command that a recovery attempt repeated verbatim is not rebuilt again
906
+ const repeatEnv = prior && REPEAT_ENV_CODES.includes(row.code) && prior.code === row.code && sigOf(prior.detail) === sigOf(row.detail);
907
+ if (repeatEnv) {
908
+ row.detail = `Environment defect: the recovery attempt failed with the same \`${row.code}\` as the run before it, so no further rebuild is spent; run the command below on the host with the project's real dependencies.\n${String(row.detail ?? "")}`;
909
+ decided({ issue: n, what: `no further recovery for ${row.code}: the same failure repeated`, why: firstLine(row.detail), alternative: "requeue another recovery lane that rebuilds against the same frozen command" });
910
+ }
911
+ if (!repeatEnv && classifyNeedsHuman(facts) === "recoverable" && used < max) {
865
912
  const code = recoveryCodeOf(facts), attempt = used + 1;
866
913
  classUsed.set(`${n}:${cls}`, attempt);
867
914
  // #4315: the full lane detail is kept (never firstLine) for the relabel when the batch stops before this attempt
@@ -963,12 +1010,24 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
963
1010
  // Lanes launched by an earlier dispatcher: re-attach to the live ones, queue the rest again (no result was recorded).
964
1011
  // #4504: every adopt starts at once and races its `onLive` signal, so a live lane never holds up the others: one that
965
1012
  // already ended is settled from its result (or requeued without one) before scheduling; a live one is awaited in the background.
966
- const requeueLost = (n) => { runRecs.delete(n); if (!pending.includes(n) && !results.has(n)) { pending.unshift(n); enqueued.set(n, now()); } };
1013
+ // #5204: a requeue is never silent: one `deferred`/`run.interrupted` row names the cause (an upgrade or a plain restart)
1014
+ // and `onInterrupted` reconciles the issue's labels. It consumes no deferral, engine-error or recovery attempt.
1015
+ const interruptCause = saved?.engineVersion && version && saved.engineVersion !== version ? `upgrade v${saved.engineVersion}→v${version}` : "dispatcher restart";
1016
+ const requeueLost = (n, why) => {
1017
+ runRecs.delete(n);
1018
+ if (pending.includes(n) || results.has(n)) return;
1019
+ pending.unshift(n); enqueued.set(n, now());
1020
+ update({ issue: n, outcome: "deferred", code: "run.interrupted", pr: null, cost_usd: 0, minutes: 0, detail: `interrupted: ${interruptCause}; ${why}; requeued` });
1021
+ decided({ issue: n, what: "requeued (interrupted)", why, alternative: "leave it pending silently" });
1022
+ try { Promise.resolve(onInterrupted?.(n, { cause: interruptCause, why })).catch(() => {}); } catch { /* best effort */ }
1023
+ };
1024
+ const adoptErrors = new Map(); // #5204: issue -> adopt error message, kept for the interrupted row
967
1025
  const adopting = [...runRecs].map(([n, rec]) => {
968
- if (!adopt || !(rec?.pid || rec?.handle)) return { n, rec, live: false, p: Promise.resolve(null) };
1026
+ // #5204: a remote record that lost its handle still adopts: the remote seam finds the sandbox through its ledger.
1027
+ if (!adopt || !(rec?.pid || rec?.handle || rec?.remote)) return { n, rec, live: false, p: Promise.resolve(null) };
969
1028
  let onLive;
970
1029
  const isLive = new Promise((r) => { onLive = () => r(true); });
971
- const p = Promise.resolve().then(() => adopt(n, rec, { onLive })).catch(() => null);
1030
+ const p = Promise.resolve().then(() => adopt(n, rec, { onLive })).catch((e) => { adoptErrors.set(n, `adopt failed: ${firstLine(e?.message ?? e)}`); return null; });
972
1031
  return { n, rec, p, first: Promise.race([p.then(() => false), isLive]) };
973
1032
  });
974
1033
  for (const a of adopting) a.live = a.first ? await a.first : false;
@@ -979,12 +1038,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
979
1038
  track(n, p.then((r) => {
980
1039
  if (r) return settle(n, r, rec, checked.get(n) ?? null);
981
1040
  if (halted) return; // #4454: kept for the next resume
982
- running.delete(n); releaseSlot(n); endRemote(n); requeueLost(n); save(); // ended without a result after all
1041
+ running.delete(n); releaseSlot(n); endRemote(n); requeueLost(n, "the adopted lane ended without a result"); save(); // ended without a result after all
983
1042
  }));
984
1043
  continue;
985
1044
  }
986
1045
  const r = await p;
987
- if (!r) { requeueLost(n); continue; }
1046
+ if (!r) {
1047
+ const why = adoptErrors.get(n) ?? (!adopt || !(rec?.pid || rec?.handle || rec?.remote) ? "no adoptable pid or handle" : "the lane ended without a result");
1048
+ requeueLost(n, why); continue;
1049
+ }
988
1050
  if (rec.remote) { remoteRun.add(n); noteRemote(n, rec.handle); }
989
1051
  else if (reg) { reg.adoptSlot(keyOf(n), { ...entryOf(n), lanePid: rec.pid }); slotted.add(n); } // released by the settle
990
1052
  track(n, Promise.resolve(r).then((x) => settle(n, x, rec, checked.get(n) ?? null)));
@@ -1087,6 +1149,17 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1087
1149
  for (const e of fresh) {
1088
1150
  requeueApplied.add(requeueKey(e));
1089
1151
  const row = results.get(e.issue);
1152
+ // #5203: a quota-paused issue (pending, no row) is released: its notBefore and the pool hold go, so the next grant admits it.
1153
+ // #5241: so is an issue waiting out a deferral (e.g. lease-held by a cancelled batch's lane): the next pass admits it.
1154
+ if (!row && pending.includes(e.issue) && (quota.has(e.issue) || notBefore.has(e.issue)) && !running.has(e.issue)) {
1155
+ notBefore.delete(e.issue);
1156
+ if (!quota.has(e.issue)) { deferrals.delete(e.issue); update({ issue: e.issue, outcome: "requeued", detail: `${e.reason || "operator decision"} (deferral released)` }); n++; continue; }
1157
+ try { const pool = remote?.identity?.(); if (pool) holds.clear(pool); } catch { /* fail-open */ }
1158
+ decided({ issue: e.issue, what: `released quota pause of #${e.issue} by ${e.by ?? "operator"} (forgedock orchestrate --requeue)`, why: e.reason || "operator decision", alternative: "wait for the account reset" });
1159
+ update({ issue: e.issue, outcome: "requeued", detail: `${e.reason || "operator decision"} (quota pause released)` });
1160
+ n++;
1161
+ continue;
1162
+ }
1090
1163
  if (!row || !REQUEUABLE(row.outcome) || running.has(e.issue)) continue;
1091
1164
  const moved = [e.issue], priors = new Map([[e.issue, row]]);
1092
1165
  results.delete(e.issue);
@@ -1126,11 +1199,21 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1126
1199
  return n;
1127
1200
  };
1128
1201
  // #4376: one SIGTERM per running local lane (their teardown saves the work); remote lanes run to their result unless the cancel carries `stopRemote` (#4612).
1129
- const stopSent = new Set();
1202
+ // #5241: a stop not accepted is retried and, once the lane outlives the teardown timeout, reported (never silent).
1203
+ const stopSent = new Map(); // issue -> {at, accepted, since, reported}
1130
1204
  function stop(n, rec) {
1131
- if (!stopLane || (rec?.remote && cancelled?.stopRemote !== true) || stopSent.has(n)) return; // #4612: remote lanes only when the cancel asked for it
1132
- stopSent.add(n);
1133
- try { Promise.resolve(stopLane(n, rec)).catch(() => {}); } catch { /* best effort */ }
1205
+ if (!stopLane || (rec?.remote && cancelled?.stopRemote !== true)) return; // #4612: remote lanes only when the cancel asked for it
1206
+ const t = now(), s = stopSent.get(n) ?? { at: null, accepted: false, since: t, reported: false };
1207
+ stopSent.set(n, s);
1208
+ if (!s.reported && t - s.since >= stopTimeoutMs) {
1209
+ s.reported = true;
1210
+ const why = rec?.stopNote ?? (s.accepted ? "stop sent, the lane has not exited" : "stop not accepted");
1211
+ update({ issue: null, outcome: "cancelled", detail: `#${n} not confirmed stopped after ${Math.round(stopTimeoutMs / 1000)}s: ${why}; its lease stays held until it exits` });
1212
+ decided({ issue: n, what: `#${n} not confirmed stopped by the cancel`, why, alternative: "stop the lane by hand" });
1213
+ }
1214
+ if (s.accepted || (s.at !== null && t - s.at < stopRetryMs)) return;
1215
+ s.at = t;
1216
+ try { Promise.resolve(stopLane(n, rec)).then((ok) => { if (ok !== false) s.accepted = true; }, () => {}); } catch { /* best effort */ }
1134
1217
  }
1135
1218
  // #4592: re-read the hold set; one decision and one row when it changes.
1136
1219
  const refreshHeld = () => {
@@ -1448,6 +1531,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1448
1531
  if (offered.size && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // a slot another batch frees
1449
1532
  if (pending.some((n) => remoteCapped.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5138: a live --set-max-remote raise
1450
1533
  if ((getAdded || getRequeued || (getChildren && addsEpicChildren(autoChildren?.mode))) && running.size) wake = Math.min(wake ?? pollMs, pollMs); // #4408/#4550: an add or requeue while only lanes run
1534
+ if (getRequeued && pending.some((n) => quota.has(n) || notBefore.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5203: a --requeue releasing a quota pause
1451
1535
  if ((pfAll || pfRemote) && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #4866
1452
1536
  if (baseWait && pending.length && baseHeld.size) wake = Math.min(wake ?? pollMs, pollMs); // #5031: a landed commit releases on the next tick
1453
1537
  if (getBlocked && pending.length && blockedHit.size) wake = Math.min(wake ?? pollMs, pollMs); // #4773: a removed label releases on the next tick
@@ -1455,7 +1539,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1455
1539
  if (syncParked && running.size && parkedPrs().length) wake = Math.min(wake ?? syncEveryMs, Math.max(0, syncEveryMs - (t - (lastParkedSync ?? t)))); // #4525
1456
1540
  if (running.size && watchable()) wake = Math.min(wake ?? WATCH_EVERY_MS, WATCH_EVERY_MS); // #4595: re-check the blockers of skipped rows
1457
1541
  if (tripped) wake = null;
1458
- if (getCancelled && running.size && !cancelled) wake = Math.min(wake ?? pollMs, pollMs); // #4376: notice a cancel while lanes run
1542
+ if (getCancelled && running.size && (!cancelled || [...running.keys()].some((n) => { const x = stopSent.get(n); return x && !(x.accepted && x.reported); }))) wake = Math.min(wake ?? pollMs, pollMs); // #5241: a cancel keeps polling a lane whose stop is unconfirmed // #4376: notice a cancel while lanes run
1459
1543
  if (running.size) {
1460
1544
  if (wake === null) await race(running.values());
1461
1545
  else { const ac = new AbortController(); await race([...running.values(), sleep(wake, ac.signal)]); ac.abort(); }
@@ -6,6 +6,10 @@ import { parseChecks, itemCheckIds, measureFollowup, monitorRecord, CHECK_ID_RE,
6
6
  import { postDeployOnly } from "./prefilter.mjs";
7
7
  import { validateContract, applyAmendments, precheck, followupItems } from "./conformance.mjs";
8
8
  import { PROBE_MARKER } from "./probe.mjs";
9
+ import { readFileSync, writeFileSync } from "node:fs";
10
+ import { tmpDir } from "../tests/_tmp.mjs";
11
+ import { join } from "node:path";
12
+ import { spawnSync } from "node:child_process";
9
13
 
10
14
  const item = (id, why) => `- [ ] \`${id}: some quote here\` — post-deploy: ${why}`;
11
15
  const body = (items) => `## Acceptance Criteria\n\n${items.join("\n")}\n\n<!-- FORGE:DEFERRED_FROM: #40 -->\n`;
@@ -284,3 +288,38 @@ describe("rollout-blocked rows raise one owner ask per flag (#4769)", () => {
284
288
  assert.equal(r.state, "fail"); assert.equal(asks(w).length, 0);
285
289
  });
286
290
  });
291
+
292
+ describe("R2-remote-hotspot-config check command (#5198)", () => {
293
+ const cmd = JSON.parse(readFileSync(new URL("../../.forge/post-deploy-checks.json", import.meta.url), "utf8"))["R2-remote-hotspot-config"].run;
294
+ // Stub gh: applies the --jq filter's two selects to the comments in comments.json and prints the per-page count.
295
+ const runCheck = (comments) => {
296
+ const dir = tmpDir("r2chk-");
297
+ writeFileSync(join(dir, "comments.json"), JSON.stringify(comments));
298
+ writeFileSync(join(dir, "gh"), `#!/usr/bin/env node
299
+ const fs = require("fs"); const a = process.argv.slice(2);
300
+ fs.appendFileSync(${JSON.stringify(join(dir, "argv.log"))}, a.join(" ") + "\\n");
301
+ if (a[0] !== "api") process.exit(2);
302
+ const jq = a[a.indexOf("--jq") + 1];
303
+ const start = (jq.match(/startswith\\("([^"]*)"\\)/) || [])[1];
304
+ const has = (jq.match(/contains\\("([^"]*)"\\)/) || [])[1];
305
+ const cs = JSON.parse(fs.readFileSync(${JSON.stringify(join(dir, "comments.json"))}, "utf8"));
306
+ console.log(cs.filter((c) => c.body.startsWith(start) && c.body.includes(has)).length);
307
+ `, { mode: 0o755 });
308
+ const r = spawnSync("bash", ["-c", cmd], { env: { ...process.env, PATH: `${dir}:${process.env.PATH}` }, encoding: "utf8" });
309
+ return { code: r.status, argv: readFileSync(join(dir, "argv.log"), "utf8") };
310
+ };
311
+ const traj = (anoms) => ({ id: 1, body: `<!-- FORGE:TRAJECTORY -->\n## Pipeline Trajectory\n\n**Anomalies**\n${anoms}\n` });
312
+
313
+ it("is repo-scoped (comments API, no gh search)", () => {
314
+ assert.doesNotMatch(cmd, /gh search/);
315
+ const r = runCheck([]);
316
+ assert.match(r.argv, /^api repos\/\{owner\}\/\{repo\}\/issues\/comments\?since=\d{4}-\d\d-\d\dT/);
317
+ });
318
+ it("passes with no comments", () => assert.equal(runCheck([]).code, 0));
319
+ it("fails on a trajectory comment carrying the anomaly bullet", () => {
320
+ assert.equal(runCheck([traj("- hotspot_config_missing: no forge.yaml readable")]).code, 1);
321
+ });
322
+ it("ignores prose that quotes the token", () => {
323
+ assert.equal(runCheck([{ id: 2, body: "Release notes: the `hotspot_config_missing` anomaly is recorded" }, traj("- none")]).code, 0);
324
+ });
325
+ });
@@ -7,6 +7,7 @@ import { reviewSkeleton } from "./conformance.mjs";
7
7
  import { seqNumber } from "./sequence.mjs";
8
8
  import { capText, FIX_CAPS, FIX_PROMPT_MAX } from "./fixround.mjs";
9
9
  import { SPLIT_MIN_FILES, SPLIT_MIN_LINES } from "./decompose.mjs";
10
+ import { relaxationBlock } from "./relaxation.mjs";
10
11
  import { isTrustedIssueComment } from "./prefilter.mjs"; // call-time use only: prefilter.mjs imports this module
11
12
 
12
13
  export const approxTokens = (s) => Math.ceil(String(s).length / 4);
@@ -89,7 +90,7 @@ export const RESTART_DIFF_MAX_BYTES = 40 * 1024;
89
90
  export function contextRestartPrompt({ stat = "", diff = "", base = "", check = "", ceiling = 0 } = {}) {
90
91
  const d = boundDiff(String(diff ?? ""), { stat, base, maxBytes: RESTART_DIFF_MAX_BYTES }).trim();
91
92
  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.
93
+ 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
94
 
94
95
  <diff_stat base="${base}">
95
96
  ${String(stat ?? "").trim() || "(no changes yet)"}
@@ -158,12 +159,12 @@ ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}
158
159
  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
160
 
160
161
  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>"}],
162
+ {"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
163
  "deliverables":[{"id":"D1","path":"<file to change>","change":"<what>","requirements":["R1"]}],
163
164
  "preserve":[{"id":"P1","what":"<caller, contract or behaviour that must not change, with its path>"}],
164
165
  "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
166
  "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.
167
+ 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.
167
168
  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
169
  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
170
  A validate or repro command must not read a $TMPDIR file it did not create: each run gets a fresh TMPDIR.
@@ -248,12 +249,12 @@ export function contextPackNote(pack) {
248
249
  /** #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
250
  export function unrunnableValidateNote(testRunners = null) {
250
251
  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.`;
252
+ 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
253
  }
253
254
 
254
255
  export function reproPlanNote(on) {
255
256
  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.`;
257
+ 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
258
  }
258
259
 
259
260
  /** forge#4519: the repo's generated, bot-owned globs (forge.yaml maintenance.generated_paths via hotspots.sh); "" when none. */
@@ -476,12 +477,12 @@ export function domainChecksBlock(domains = []) {
476
477
  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
478
  }
478
479
 
479
- export function reviewerPrompt({ issue, comments = [], contract, result, files = [], diff, stat = "", base = "", structure = "", ignore = [`${LEAN_DIR}/`], skeleton = null, investigationVerdict = null, domains = [] }) {
480
+ export function reviewerPrompt({ issue, comments = [], contract, result, files = [], diff, stat = "", base = "", structure = "", ignore = [`${LEAN_DIR}/`], skeleton = null, investigationVerdict = null, domains = [], relaxations = [] }) {
480
481
  const notes = comments.map((c) => String(c?.body ?? "")).filter((b) => !/^<!-- FORGE:/.test(b.trim()));
481
482
  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
483
  notes.push(...decisions);
483
484
  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)}`;
485
+ 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
486
  }
486
487
 
487
488
  /**
@@ -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 } });
@@ -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
+ }