forgedock 1.66.0 → 1.68.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 (173) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +2 -0
  3. package/bin/engine-cli.mjs +193 -27
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +24 -1
  6. package/bin/help-text.mjs +4 -3
  7. package/bin/introspect-schedule.mjs +98 -0
  8. package/bin/introspect-schedule.test.mjs +67 -0
  9. package/bin/lean/admission.mjs +21 -0
  10. package/bin/lean/admission.test.mjs +30 -0
  11. package/bin/lean/advisory.test.mjs +64 -0
  12. package/bin/lean/amendment-schema.mjs +30 -0
  13. package/bin/lean/attempts.mjs +162 -0
  14. package/bin/lean/attempts.test.mjs +141 -0
  15. package/bin/lean/basered.mjs +81 -0
  16. package/bin/lean/basered.test.mjs +68 -1
  17. package/bin/lean/batch-health.mjs +20 -12
  18. package/bin/lean/batch-health.test.mjs +55 -11
  19. package/bin/lean/batch.mjs +45 -0
  20. package/bin/lean/batch.test.mjs +105 -5
  21. package/bin/lean/capwait.mjs +14 -3
  22. package/bin/lean/capwait.test.mjs +20 -0
  23. package/bin/lean/ci-gate.mjs +2 -90
  24. package/bin/lean/ci-gate.test.mjs +1 -127
  25. package/bin/lean/ci-precheck.mjs +25 -8
  26. package/bin/lean/ci-precheck.test.mjs +24 -0
  27. package/bin/lean/clear-breaker.mjs +14 -0
  28. package/bin/lean/clear-breaker.test.mjs +4 -3
  29. package/bin/lean/commentstate.mjs +46 -0
  30. package/bin/lean/commentstate.test.mjs +43 -0
  31. package/bin/lean/concurrency.mjs +89 -0
  32. package/bin/lean/concurrency.test.mjs +113 -0
  33. package/bin/lean/conformance.e2e.test.mjs +13 -8
  34. package/bin/lean/conformance.mjs +73 -181
  35. package/bin/lean/conformance.test.mjs +61 -345
  36. package/bin/lean/depcache.mjs +100 -10
  37. package/bin/lean/depcache.test.mjs +105 -0
  38. package/bin/lean/docsgate.mjs +0 -32
  39. package/bin/lean/docsgate.test.mjs +2 -23
  40. package/bin/lean/effects-cap.test.mjs +9 -1
  41. package/bin/lean/effects-killtree.test.mjs +35 -0
  42. package/bin/lean/effects.mjs +42 -24
  43. package/bin/lean/efficiency.mjs +162 -0
  44. package/bin/lean/efficiency.test.mjs +79 -0
  45. package/bin/lean/engine-readmit.test.mjs +35 -0
  46. package/bin/lean/envgap.mjs +93 -0
  47. package/bin/lean/envgap.test.mjs +53 -0
  48. package/bin/lean/execution.mjs +41 -17
  49. package/bin/lean/execution.test.mjs +58 -0
  50. package/bin/lean/failure-census.mjs +170 -0
  51. package/bin/lean/failure-census.test.mjs +59 -0
  52. package/bin/lean/failure-stop.mjs +46 -0
  53. package/bin/lean/failure-stop.test.mjs +45 -0
  54. package/bin/lean/fixtures/capacity-storm.json +609 -0
  55. package/bin/lean/guardgate.test.mjs +2 -3
  56. package/bin/lean/heavy.mjs +33 -4
  57. package/bin/lean/heavy.test.mjs +38 -6
  58. package/bin/lean/hotarea.mjs +0 -36
  59. package/bin/lean/hotarea.test.mjs +1 -22
  60. package/bin/lean/issuewatch-verify.mjs +19 -4
  61. package/bin/lean/issuewatch.mjs +21 -4
  62. package/bin/lean/issuewatch.test.mjs +48 -1
  63. package/bin/lean/lane-audit-gap.mjs +66 -0
  64. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  65. package/bin/lean/lane-audit-llm.mjs +5 -0
  66. package/bin/lean/lane-audit-query.mjs +47 -0
  67. package/bin/lean/lane-audit-query.test.mjs +44 -0
  68. package/bin/lean/lane-audit-signatures.mjs +33 -0
  69. package/bin/lean/lane-audit.mjs +110 -0
  70. package/bin/lean/lane-audit.test.mjs +97 -0
  71. package/bin/lean/lane-recovery.test.mjs +33 -0
  72. package/bin/lean/lanecheck.mjs +5 -3
  73. package/bin/lean/lanecheck.test.mjs +6 -0
  74. package/bin/lean/lean.mjs +311 -154
  75. package/bin/lean/lean.test.mjs +530 -223
  76. package/bin/lean/limits.mjs +17 -0
  77. package/bin/lean/limits.test.mjs +15 -1
  78. package/bin/lean/live-execution.mjs +21 -2
  79. package/bin/lean/live-execution.test.mjs +39 -0
  80. package/bin/lean/liveness.mjs +37 -0
  81. package/bin/lean/liveness.test.mjs +33 -0
  82. package/bin/lean/orchestrate-attempts.test.mjs +82 -0
  83. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  84. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  85. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  86. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  87. package/bin/lean/orchestrate-pause.test.mjs +76 -1
  88. package/bin/lean/orchestrate-reconcile.test.mjs +164 -0
  89. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  90. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  91. package/bin/lean/orchestrate.mjs +344 -45
  92. package/bin/lean/phaseledger.mjs +6 -0
  93. package/bin/lean/phaseledger.test.mjs +13 -1
  94. package/bin/lean/postdeploy-check.test.mjs +1 -3
  95. package/bin/lean/precheck.mjs +20 -0
  96. package/bin/lean/preflight.mjs +100 -11
  97. package/bin/lean/preflight.test.mjs +44 -4
  98. package/bin/lean/prompts.mjs +13 -28
  99. package/bin/lean/reconcile.mjs +90 -0
  100. package/bin/lean/recurrence.mjs +6 -112
  101. package/bin/lean/recurrence.test.mjs +11 -92
  102. package/bin/lean/release-flakes.mjs +14 -2
  103. package/bin/lean/release-flakes.test.mjs +17 -1
  104. package/bin/lean/release-ledger.mjs +19 -1
  105. package/bin/lean/release-ledger.test.mjs +23 -0
  106. package/bin/lean/release-preflight.mjs +28 -0
  107. package/bin/lean/release-preflight.test.mjs +42 -1
  108. package/bin/lean/release-review.mjs +40 -5
  109. package/bin/lean/release-review.test.mjs +43 -2
  110. package/bin/lean/release.mjs +43 -14
  111. package/bin/lean/release.test.mjs +32 -0
  112. package/bin/lean/retry.mjs +1 -1
  113. package/bin/lean/retry.test.mjs +6 -1
  114. package/bin/lean/rotator.mjs +9 -0
  115. package/bin/lean/rotator.test.mjs +11 -1
  116. package/bin/lean/sandbox-remote.mjs +49 -11
  117. package/bin/lean/sched.mjs +19 -0
  118. package/bin/lean/sched.test.mjs +11 -1
  119. package/bin/lean/schedd-health.mjs +4 -4
  120. package/bin/lean/schedd-health.test.mjs +8 -4
  121. package/bin/lean/schedd.mjs +45 -8
  122. package/bin/lean/schedd.test.mjs +120 -7
  123. package/bin/lean/selfreview.mjs +1 -1
  124. package/bin/lean/slo.mjs +126 -0
  125. package/bin/lean/slo.test.mjs +112 -0
  126. package/bin/lean/statuscomment.mjs +40 -0
  127. package/bin/lean/statuscomment.test.mjs +48 -1
  128. package/bin/lean/validate-catalog.mjs +108 -0
  129. package/bin/lean/validate-catalog.test.mjs +46 -1
  130. package/bin/lean/verify.mjs +3 -2
  131. package/bin/pool/affinity.test.mjs +91 -0
  132. package/bin/pool/agent.mjs +144 -10
  133. package/bin/pool/cache-sweep.mjs +31 -10
  134. package/bin/pool/ci-autoscale.mjs +160 -0
  135. package/bin/pool/cli.mjs +53 -9
  136. package/bin/pool/docker.mjs +3 -0
  137. package/bin/pool/engine-placement.test.mjs +94 -0
  138. package/bin/pool/lane-target.mjs +41 -0
  139. package/bin/pool/lane-tools.mjs +26 -0
  140. package/bin/pool/lane-tools.test.mjs +9 -0
  141. package/bin/pool/mirror-seed.mjs +15 -11
  142. package/bin/pool/router.mjs +88 -32
  143. package/bin/pool/version.mjs +29 -2
  144. package/bin/review-staging.mjs +11 -3
  145. package/bin/runner.mjs +59 -11
  146. package/bin/stats/attempts.mjs +54 -0
  147. package/bin/stats/attempts.test.mjs +30 -0
  148. package/bin/stats/churn.mjs +49 -0
  149. package/bin/stats/churn.test.mjs +31 -0
  150. package/bin/stats/index.mjs +11 -3
  151. package/bin/stats/release.mjs +7 -0
  152. package/bin/stats/release.test.mjs +20 -0
  153. package/bin/stats/scorecard.mjs +187 -0
  154. package/bin/stats/scorecard.test.mjs +89 -0
  155. package/commands/orchestrate.md +21 -18
  156. package/docs/CONFIG.md +41 -0
  157. package/docs/OUTCOME-CODES.md +2 -0
  158. package/docs/STATS.md +17 -0
  159. package/package.json +1 -1
  160. package/pool/image/Dockerfile +14 -2
  161. package/pool/image/manifest.json +25 -0
  162. package/pool/image/mirror.sh +11 -2
  163. package/pool/install/install-agent.ps1 +11 -4
  164. package/scripts/check-devdocs-freshness.sh +1 -1
  165. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  166. package/scripts/ci-local/cli.mjs +1 -1
  167. package/scripts/ci-local/plan.mjs +3 -2
  168. package/scripts/ci-local.test.sh +11 -0
  169. package/scripts/failure-census.mjs +67 -0
  170. package/scripts/review-finalize.sh +5 -5
  171. package/scripts/review-finalize.test.sh +8 -1
  172. package/scripts/verify-phase-trail.sh +11 -0
  173. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -7,6 +7,7 @@ import { mkdirSync, writeFileSync, existsSync, readFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { tmpDir } from "../tests/_tmp.mjs";
9
9
  import { renderContract } from "./render.mjs";
10
+ import { sandboxBudgetKey } from "./liveness.mjs";
10
11
  import { parseExecution, hostFallbackAllowed, SANDBOX_PROVIDERS, detectNeeds, hostCapabilityBlock, placementText, contractHostNeeds, placement, placeLane, validationWeight, hostHeadroom, scopedEnv, providerLanes, remoteHoldId, usageLimitInTail, isTransportError, isCloneFailure, isEgressTimeout, SANDBOX_EGRESS_TIMEOUT_CODE, containerProvider, providerByName, openExecutionBudget, poolCredential, remoteTransportFor, resolveDefaultExecution, repoIsPublic } from "./execution.mjs";
11
12
  import * as executionModule from "./execution.mjs";
12
13
  import { remoteProvider } from "./sandbox-remote.mjs";
@@ -126,6 +127,35 @@ describe("providerLanes: an unreachable provider is retried, then deferred witho
126
127
  assert.deepEqual(ledgerFor(7).entries("sandbox").map((e) => e.value), ["fake-7"]);
127
128
  });
128
129
 
130
+ it("#5991 transport failure with the agent answering ends sandbox.unreachable within 90 s; agent down keeps the window", async () => {
131
+ const run = async (agentOnline) => {
132
+ const prov = flaky(1e9); prov.start = async () => ({ provider: "fake", id: "fake-7", issue: 7 }); let total = 0;
133
+ const r = await providerLanes({ provider: prov, laneArgs: () => [], ledgerFor: ledgerIn(tmpDir("exec-up-")), pollMs: 5000, unreachableWindowMs: 300000, agentOnline, sleep: async (ms) => { total += ms; } }).runOne(7, "staging");
134
+ return { r, total };
135
+ };
136
+ const up = await run(async () => true);
137
+ assert.deepEqual([up.r.terminalReason, up.r.code], ["deferred", "sandbox.unreachable"]);
138
+ assert.ok(up.total <= 90000, `waited ${up.total}`);
139
+ for (const a of [async () => false, async () => { throw new Error("router down"); }, null]) {
140
+ const down = await run(a);
141
+ assert.equal(down.r.code, "sandbox.unreachable");
142
+ assert.ok(down.total >= 300000, `waited ${down.total}`);
143
+ }
144
+ });
145
+
146
+ it("#5991 24 replayed attempts of one sandbox leave one budget row within 5% of the real minutes", () => {
147
+ const file = join(tmpDir("exec-budget-"), "execution-budget.json");
148
+ const b = openExecutionBudget({ file, now: () => 0 });
149
+ for (let i = 1; i <= 24; i++) b.record(sandboxBudgetKey("b1", "fdrsbx-9"), { minutes: i * 5, cost_usd: 0 });
150
+ const rows = Object.values(JSON.parse(readFileSync(file, "utf8")).days).flatMap((d) => Object.keys(d));
151
+ assert.deepEqual(rows, ["b1#fdrsbx-9"]);
152
+ assert.ok(Math.abs(b.dayTotals().minutes - 120) / 120 <= 0.05);
153
+ assert.equal(b.record(sandboxBudgetKey("b1", "fdrsbx-9"), { minutes: 10 }), false); // a smaller replay changes nothing
154
+ const before = b.dayTotals().minutes;
155
+ b.record(sandboxBudgetKey("b1", "fdrsbx-9", 99), { minutes: 7 }); // #6023: a rerun reusing the sandbox id adds its own usage
156
+ assert.equal(b.dayTotals().minutes, before + 7);
157
+ });
158
+
129
159
  it("#5053 a 401 on status/result of a launched sandbox is retried, then ends sandbox.auth (capped), never engine-error", async () => {
130
160
  const e401 = () => Object.assign(new Error("sandbox status: HTTP 401 (agent a1 auth)"), { status: 401, hop: "agent", transient: true });
131
161
  const mk = (failPolls) => { const prov = flaky(0); let polls = 0; prov.start = async () => ({ provider: "fake", id: "fake-7", issue: 7 });
@@ -642,6 +672,13 @@ describe("execution budget and sandbox cost (#4255)", () => {
642
672
  const a = openExecutionBudget({ budget: { dayMinutes: 15 }, file, now });
643
673
  assert.equal(a.record("b1#fdsbx-1#100", { minutes: 10, cost_usd: 1 }), true);
644
674
  assert.equal(a.record("b1#fdsbx-1#100", { minutes: 10, cost_usd: 1 }), false);
675
+ // #5987: cumulative samples of one sandbox are one entry holding the latest usage; the day sum tracks the log's minutes
676
+ const u = openExecutionBudget({ budget: {}, file: join(tmpDir("exec-up-"), "b.json"), now });
677
+ for (const m of [1, 2, 3, 5, 8, 10]) u.record("b2#fdsbx-2", { minutes: m, cost_usd: m / 10 });
678
+ u.record("b2#fdsbx-3", { minutes: 20, cost_usd: 2 });
679
+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(u.file, "utf8")).days["2026-10-20"]).sort(), ["b2#fdsbx-2", "b2#fdsbx-3"]);
680
+ const logMinutes = 10 + 20;
681
+ assert.ok(Math.abs(u.dayTotals().minutes - logMinutes) <= logMinutes * 0.05);
645
682
  const b = openExecutionBudget({ budget: { dayMinutes: 15 }, file, now }); // a fresh daemon
646
683
  assert.deepEqual(b.dayTotals(), { ok: true, day: "2026-10-20", minutes: 10, cost_usd: 1 });
647
684
  assert.equal(b.admit({ minutes: 0, cost_usd: 0, running: { minutes: 0, cost_usd: 0 } }).ok, true);
@@ -1150,6 +1187,15 @@ describe("#5095: launch 5xx and a pool usage limit are deferred, never needs-hum
1150
1187
  assert.equal((await lanesFor(prov).runOne(7, null)).code, "sandbox.capacity");
1151
1188
  });
1152
1189
 
1190
+ it("a pool refusal code and live figures ride the sandbox.capacity deferral row as reason/live (#5985)", async () => {
1191
+ const prov = fakeProvider();
1192
+ prov.start = async () => { throw Object.assign(new Error("sandbox launch: HTTP 503"), { status: 503, retryable: true, poolCode: "pool.host_load", live: { load_per_core: 2.1, mem_available_gb: 8 }, retryInSeconds: 60 }); };
1193
+ const r = await lanesFor(prov).runOne(7, null);
1194
+ assert.deepEqual([r.code, r.reason, r.live.load_per_core, r.retryInSeconds], ["sandbox.capacity", "host_load", 2.1, 60]);
1195
+ prov.start = async () => { throw Object.assign(new Error("x"), { status: 503, retryable: true, poolCode: "pool.disk_low" }); };
1196
+ assert.equal((await lanesFor(prov).runOne(7, null)).reason, "disk");
1197
+ });
1198
+
1153
1199
  it("usageLimitInTail reads the lean finish line and the CLI's own limit message", () => {
1154
1200
  assert.deepEqual(usageLimitInTail("x\n[lane] deferred: usage limit hit; resets at 3:20pm (UTC)\n"), { resetAt: "3:20pm (UTC)" });
1155
1201
  assert.equal(usageLimitInTail("sandbox exited 1\nclone ok"), null);
@@ -1363,6 +1409,18 @@ describe("providerLanes: a halted batch keeps its sandbox for adopt (#5669)", ()
1363
1409
  });
1364
1410
  });
1365
1411
 
1412
+ describe("#5746 remote-mode host fallback and max_remote 0", () => {
1413
+ it("hostFallbackAllowed: remote unset false, hybrid true, explicit true wins", () => {
1414
+ assert.equal(hostFallbackAllowed({ mode: "remote" }), false);
1415
+ assert.equal(hostFallbackAllowed({ mode: "hybrid" }), true);
1416
+ assert.equal(hostFallbackAllowed({ mode: "remote", hostFallback: true }), true);
1417
+ });
1418
+ it("placeLane: remote mode with max_remote 0 stays remote (#5933 pauses starts, never the host)", () => {
1419
+ assert.equal(placeLane({ exec: { mode: "remote", maxRemote: 0 } }).where, "remote");
1420
+ assert.equal(placeLane({ exec: { mode: "remote", maxRemote: 2 } }).reason, "mode remote");
1421
+ });
1422
+ });
1423
+
1366
1424
  describe("public-repo default placement (#5748)", () => {
1367
1425
  const OPT = parseExecution({ public_default: "actions" }); // #5900: the actions default is opt-in
1368
1426
  it("actions is a known provider; plan, job_limit, ci_reserve and dispatcher parse", () => {
@@ -0,0 +1,170 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Failure census (2026-11-26): classify why lanes did not take the happy path, from the register itself, so an agent
5
+ * working on a pipeline fix reads measured failure classes instead of guessing. Pure functions only (no I/O): the CLI
6
+ * (scripts/failure-census.mjs) feeds issue comments and batch log rows in.
7
+ *
8
+ * Inputs it understands (all ForgeDock annotations on issues):
9
+ * - FORGE:NEEDS_HUMAN / FORGE:PARKED bodies: one park each, classified into a bucket and normalised failure rows;
10
+ * - FORGE:AMENDMENT-STATE JSON: the last state per issue gives the distinct amendments (kind + why class);
11
+ * - FORGE:BASE_SYNC bodies: conflicted files.
12
+ * Batch log rows (`~/.forge/batches/<id>/log.jsonl`): outcome/code counts and per-phase timing.
13
+ */
14
+
15
+ /** Ordered: the first matching bucket wins. Patterns match the park body (rows and prose). */
16
+ export const PARK_BUCKETS = Object.freeze([
17
+ ["sandbox_tool_gap", /Remote sandbox lacks|lane_tools recipe|sandbox is missing/i],
18
+ ["recurrence_design", /recurrence\.design_missing/],
19
+ ["post_deploy_check_id", /post-deploy check (id|'[^']*') is neither/],
20
+ ["amendment_syntax", /unknown or incomplete amendment|amendment kind '|amendment not accepted/],
21
+ ["substitute_validate", /substituted `|substitute-validate|substitute_unverified/],
22
+ ["deferral", /unjustified_deferral|untracked_deferral|reported "deferred"/],
23
+ ["no_status", /reported "no status"/],
24
+ ["omission_narrowed", /conformance\.omission|requirement narrowed/],
25
+ ["scope_creep", /scope_creep|outside the contract's deliverables/],
26
+ ["validate_failed", /validate [A-Z]?\d+ .*failed|frozen command runs and fails|Declared check command\(s\) failing/],
27
+ ["ci_red", /Required check\(s\) failed|ci\.red|CI verification failed/],
28
+ ["env_setup", /Environment error|env\.(setup_failed|tool_missing|validate_timeout|validate_placement|repro_unrunnable|capability_remote)/],
29
+ ["builder_blocked", /Builder is blocked|builder\.(blocked|no_commit)|Builder made no commit/],
30
+ ["review_incomplete", /review\.(incomplete|failed|unparseable)|Review FAIL/],
31
+ ["e2e_unverified", /e2e_unverified|e2e_placement/],
32
+ ["design_spec", /design\.spec_required|FORGE:DESIGN_SPEC|Design gate/],
33
+ ["contract_invalid", /contract is still invalid|contract\.invalid/],
34
+ ]);
35
+
36
+ /** Bucket of one park body; "other" when no pattern matches. */
37
+ export function parkBucket(body) {
38
+ const b = String(body ?? "");
39
+ for (const [name, re] of PARK_BUCKETS) if (re.test(b)) return name;
40
+ return "other";
41
+ }
42
+
43
+ /** The `- code: detail` rows of a NEEDS_HUMAN/PARKED body, normalised so repeats across issues group together. */
44
+ export function parkRows(body) {
45
+ return String(body ?? "").split("\n").filter((l) => /^- [a-z_]+\.[a-z_]+:/.test(l)).map(normalizeRow);
46
+ }
47
+
48
+ /** Collapse ids, numbers, quotes and code spans so identical defects compare equal. */
49
+ export function normalizeRow(row) {
50
+ return String(row).replace(/^- /, "").replace(/\bR\d+\b/g, "R#").replace(/\b[GV]\d+\b/g, "V#").replace(/#\d+/g, "#N")
51
+ .replace(/`[^`]*`/g, "`…`").replace(/\("[^]*$/, "").replace(/"[^"]{40,}"/g, "\"…\"").replace(/\d+/g, "N").trim().slice(0, 140);
52
+ }
53
+
54
+ const AMENDMENT_STATE_RE = /FORGE:AMENDMENT-STATE (\{.*\}) -->/;
55
+ /** The distinct amendments of the LAST amendment state on an issue (earlier states are replayed into it). */
56
+ export function lastAmendments(comments) {
57
+ let last = null;
58
+ for (const c of comments ?? []) {
59
+ const m = AMENDMENT_STATE_RE.exec(String(c?.body ?? ""));
60
+ if (!m) continue;
61
+ try { last = JSON.parse(m[1]); } catch { /* a malformed state is skipped */ }
62
+ }
63
+ return Array.isArray(last?.amendments) ? last.amendments : [];
64
+ }
65
+
66
+ /** Why-class of one amendment: broken frozen command, post-deploy measurement, naming, or other. */
67
+ export function amendmentWhyClass(a) {
68
+ const w = String(a?.why ?? "");
69
+ if (/on the (unchanged )?base|origin\/staging|fails before|not on the .*path|ModuleNotFound|cannot import|not installed|command not found|timed out|sandbox|lacks/i.test(w)) return "frozen_command_broken_or_env";
70
+ if (/requirement|post-deploy|measur|production|after deploy/i.test(w)) return "post_deploy_or_measurement";
71
+ if (/duplicate|rename|name/i.test(w)) return "naming_or_decision";
72
+ if (/docs freshness|dossier|registry|check id/i.test(w)) return "forced_by_another_gate";
73
+ return "other";
74
+ }
75
+
76
+ /** Conflicted files listed by a FORGE:BASE_SYNC body ("conflicts in `a`, `b`"). */
77
+ export function baseSyncConflicts(body) {
78
+ const m = /\*\*Result:\*\* conflicts in ([^\n]+)/.exec(String(body ?? ""));
79
+ return m ? [...m[1].matchAll(/`([^`]+)`/g)].map((x) => x[1]) : [];
80
+ }
81
+
82
+ const inc = (o, k, by = 1) => { o[k] = (o[k] ?? 0) + by; return o; };
83
+ const top = (o, n) => Object.entries(o).sort((a, b) => b[1] - a[1]).slice(0, n);
84
+
85
+ /**
86
+ * Census over issues: `issues` = [{number, title, comments: [{body, createdAt, author}]}]. Returns plain data:
87
+ * parks by bucket (+ issues), by day x bucket, top normalised rows, repeat parks (identical rows back to back),
88
+ * amendments by kind x why class, conflict hotspots, and the most-parked issues.
89
+ */
90
+ export function censusIssues(issues) {
91
+ const out = { issues: 0, withParks: 0, parks: 0, repeats: 0, buckets: {}, bucketIssues: {}, byDay: {}, rows: {}, amendments: {}, amendmentIssues: {}, conflicts: {}, baseSyncs: 0, mostParked: [] };
92
+ const perIssue = [];
93
+ for (const iss of issues ?? []) {
94
+ out.issues++;
95
+ let parks = 0, prev = null;
96
+ for (const c of iss.comments ?? []) {
97
+ const body = String(c?.body ?? "");
98
+ if (/FORGE:BASE_SYNC/.test(body)) { out.baseSyncs++; for (const f of baseSyncConflicts(body)) inc(out.conflicts, f); }
99
+ if (!/FORGE:(NEEDS_HUMAN|PARKED)/.test(body)) continue;
100
+ const rows = parkRows(body), bucket = parkBucket(body), key = rows.slice().sort().join("|");
101
+ parks++; out.parks++;
102
+ inc(out.buckets, bucket);
103
+ (out.bucketIssues[bucket] ??= new Set()).add(iss.number);
104
+ const day = String(c?.createdAt ?? "").slice(0, 10) || "unknown";
105
+ inc((out.byDay[day] ??= {}), bucket);
106
+ if (prev !== null && rows.length && key === prev) out.repeats++;
107
+ prev = key;
108
+ for (const r of new Set(rows)) inc(out.rows, r);
109
+ }
110
+ for (const a of lastAmendments(iss.comments)) {
111
+ const k = `${a?.kind ?? "?"} :: ${amendmentWhyClass(a)}`;
112
+ inc(out.amendments, k);
113
+ (out.amendmentIssues[k] ??= new Set()).add(iss.number);
114
+ }
115
+ if (parks) { out.withParks++; perIssue.push({ number: iss.number, title: String(iss.title ?? "").slice(0, 80), parks }); }
116
+ }
117
+ out.mostParked = perIssue.sort((a, b) => b.parks - a.parks).slice(0, 15);
118
+ for (const k of ["bucketIssues", "amendmentIssues"]) for (const b of Object.keys(out[k])) out[k][b] = out[k][b].size;
119
+ return out;
120
+ }
121
+
122
+ /** Census over batch log rows ({outcome, code, phases:{name:{ms}}}): outcome/code counts and per-phase median/p90 (merged lanes). */
123
+ export function censusBatchRows(rows) {
124
+ const outcomes = {}, deferred = {}, needsHuman = {}, phases = {};
125
+ for (const r of rows ?? []) {
126
+ if (!r || r.outcome == null) continue;
127
+ inc(outcomes, r.outcome);
128
+ if (r.outcome === "deferred") inc(deferred, r.code ?? "null");
129
+ if (r.outcome === "needs-human") inc(needsHuman, r.code ?? "null");
130
+ if (r.outcome === "merged" && r.phases && typeof r.phases === "object") {
131
+ for (const [k, v] of Object.entries(r.phases)) if (Number.isFinite(v?.ms)) (phases[k] ??= []).push(v.ms);
132
+ }
133
+ }
134
+ const q = (xs, p) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.min(s.length - 1, Math.floor(s.length * p))] : null; };
135
+ const phaseStats = Object.fromEntries(Object.entries(phases).map(([k, xs]) => [k, { n: xs.length, median_min: Math.round(q(xs, 0.5) / 6000) / 10, p90_min: Math.round(q(xs, 0.9) / 6000) / 10 }]));
136
+ return { outcomes, deferred, needsHuman, phases: phaseStats };
137
+ }
138
+
139
+ /** Markdown report of both censuses. */
140
+ export function renderCensus({ repo, since, issues, batches }) {
141
+ const L = [`# Failure census: ${repo}${since ? ` (since ${since})` : ""}`, ""];
142
+ if (issues) {
143
+ L.push(`Issues scanned: ${issues.issues}; with parks: ${issues.withParks}; parks (NEEDS_HUMAN/PARKED): ${issues.parks}; identical back-to-back repeats: ${issues.repeats}`, "", "## Parks by class", "", "| class | parks | issues |", "|---|---|---|");
144
+ for (const [b, n] of top(issues.buckets, 30)) L.push(`| ${b} | ${n} | ${issues.bucketIssues[b] ?? 0} |`);
145
+ const days = Object.keys(issues.byDay).sort(), cls = top(issues.buckets, 6).map(([b]) => b);
146
+ if (days.length) {
147
+ L.push("", "## Parks per day (top classes)", "", `| day | ${cls.join(" | ")} | other |`, `|---|${cls.map(() => "---").join("|")}|---|`);
148
+ for (const d of days) { const row = issues.byDay[d]; const rest = Object.entries(row).filter(([k]) => !cls.includes(k)).reduce((s, [, v]) => s + v, 0); L.push(`| ${d} | ${cls.map((c) => row[c] ?? 0).join(" | ")} | ${rest} |`); }
149
+ }
150
+ L.push("", "## Most frequent failure rows (normalised)", "", "| count | row |", "|---|---|");
151
+ for (const [r, n] of top(issues.rows, 20)) L.push(`| ${n} | ${r.replace(/\\/g, "\\\\").replace(/\|/g, "\\|")} |`);
152
+ L.push("", "## Amendments (last state per issue): kind :: why class", "", "| amendment | count | issues |", "|---|---|---|");
153
+ for (const [k, n] of top(issues.amendments, 20)) L.push(`| ${k} | ${n} | ${issues.amendmentIssues[k] ?? 0} |`);
154
+ L.push("", `## Base-sync conflict hotspots (${issues.baseSyncs} base syncs)`, "", "| file | conflicts |", "|---|---|");
155
+ for (const [f, n] of top(issues.conflicts, 15)) L.push(`| \`${f}\` | ${n} |`);
156
+ L.push("", "## Most-parked issues", "", "| issue | parks | title |", "|---|---|---|");
157
+ for (const i of issues.mostParked) L.push(`| #${i.number} | ${i.parks} | ${i.title.replace(/\\/g, "\\\\").replace(/\|/g, "\\|")} |`);
158
+ }
159
+ if (batches) {
160
+ L.push("", "## Batch logs", "", "| outcome | rows |", "|---|---|");
161
+ for (const [k, n] of top(batches.outcomes, 15)) L.push(`| ${k} | ${n} |`);
162
+ L.push("", "| deferred code | rows |", "|---|---|");
163
+ for (const [k, n] of top(batches.deferred, 10)) L.push(`| ${k} | ${n} |`);
164
+ L.push("", "| needs-human code | rows |", "|---|---|");
165
+ for (const [k, n] of top(batches.needsHuman, 12)) L.push(`| ${k} | ${n} |`);
166
+ L.push("", "| phase (merged lanes) | n | median min | p90 min |", "|---|---|---|---|");
167
+ for (const [k, v] of Object.entries(batches.phases).sort((a, b) => b[1].median_min - a[1].median_min)) L.push(`| ${k} | ${v.n} | ${v.median_min} | ${v.p90_min} |`);
168
+ }
169
+ return L.join("\n") + "\n";
170
+ }
@@ -0,0 +1,59 @@
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 { parkBucket, parkRows, normalizeRow, lastAmendments, amendmentWhyClass, baseSyncConflicts, censusIssues, censusBatchRows, renderCensus } from "./failure-census.mjs";
6
+
7
+ const nh = (rows, prose = "") => `<!-- FORGE:NEEDS_HUMAN -->\n## Needs human\n${prose}\n${rows.map((r) => `- ${r}`).join("\n")}`;
8
+
9
+ describe("failure census", () => {
10
+ it("buckets parks by the first matching class", () => {
11
+ assert.equal(parkBucket("Remote sandbox lacks yaml, and no lane_tools recipe exists for it."), "sandbox_tool_gap");
12
+ assert.equal(parkBucket(nh(["recurrence.design_missing: recurring issue routed to a design lane: no design block"])), "recurrence_design");
13
+ assert.equal(parkBucket(nh(["conformance.unimplemented: R13 post-deploy check id is neither on the default branch nor added by this PR (.forge/post-deploy-checks.json)"])), "post_deploy_check_id");
14
+ assert.equal(parkBucket(nh(["conformance.unimplemented: unknown or incomplete amendment: amendment kind 'supersedes' needs guard"])), "amendment_syntax");
15
+ assert.equal(parkBucket(nh(['conformance.unimplemented: R4 reported "no status" ("x")'])), "no_status");
16
+ assert.equal(parkBucket("Required check(s) failed on PR #6011 (Spec-size budget) and the builder made no new commit for it"), "ci_red");
17
+ assert.equal(parkBucket("something new"), "other");
18
+ });
19
+ it("normalises rows so the same defect on different issues groups together", () => {
20
+ const a = normalizeRow('- conformance.unimplemented: R13 post-deploy check id is neither on the default branch nor added by this PR (.forge/post-deploy-checks.json) ("quote one")');
21
+ const b = normalizeRow('- conformance.unimplemented: R7 post-deploy check id is neither on the default branch nor added by this PR (.forge/post-deploy-checks.json) ("another")');
22
+ assert.equal(a, b);
23
+ assert.deepEqual(parkRows(nh(["a.b: one", "c.d: two"], "prose line")).length, 2);
24
+ });
25
+ it("uses only the last amendment state and classifies why", () => {
26
+ const st = (am) => ({ body: `<!-- FORGE:AMENDMENT-STATE ${JSON.stringify({ contract: "x", amendments: am })} -->` });
27
+ const am = lastAmendments([st([{ kind: "decision", why: "rename" }]), { body: "noise" }, st([{ kind: "substitute-validate", why: "fails on the unchanged base too" }, { kind: "add-deliverable", path: "devdocs/x.md", why: "docs freshness rule" }])]);
28
+ assert.deepEqual(am.map((a) => a.kind), ["substitute-validate", "add-deliverable"]);
29
+ assert.equal(amendmentWhyClass(am[0]), "frozen_command_broken_or_env");
30
+ assert.equal(amendmentWhyClass(am[1]), "forced_by_another_gate");
31
+ assert.deepEqual(lastAmendments([{ body: "<!-- FORGE:AMENDMENT-STATE {broken -->" }]), []);
32
+ });
33
+ it("reads base-sync conflict files", () => {
34
+ assert.deepEqual(baseSyncConflicts("## Base Sync\n**Result:** conflicts in `devdocs/modules/lean.md`, `.forge/post-deploy-checks.json`\n"), ["devdocs/modules/lean.md", ".forge/post-deploy-checks.json"]);
35
+ assert.deepEqual(baseSyncConflicts("**Result:** clean merge"), []);
36
+ });
37
+ it("counts parks, identical back-to-back repeats, amendments and hotspots per issue", () => {
38
+ const row = "conformance.unimplemented: unknown or incomplete amendment: amendment kind 'supersedes' needs guard";
39
+ const c = censusIssues([
40
+ { number: 1, title: "one", comments: [{ body: nh([row]), createdAt: "2026-11-24T01:00:00Z" }, { body: nh([row]), createdAt: "2026-11-24T02:00:00Z" }, { body: "<!-- FORGE:BASE_SYNC -->\n## Base Sync\n**Result:** conflicts in `a.md`" }] },
41
+ { number: 2, title: "two", comments: [{ body: nh([], "Remote sandbox lacks bash, and no lane_tools recipe exists for it."), createdAt: "2026-11-25T01:00:00Z" }] },
42
+ { number: 3, title: "clean", comments: [{ body: "hello" }] },
43
+ ]);
44
+ assert.equal(c.issues, 3); assert.equal(c.withParks, 2); assert.equal(c.parks, 3); assert.equal(c.repeats, 1);
45
+ assert.equal(c.buckets.amendment_syntax, 2); assert.equal(c.bucketIssues.amendment_syntax, 1);
46
+ assert.equal(c.byDay["2026-11-25"].sandbox_tool_gap, 1);
47
+ assert.equal(c.conflicts["a.md"], 1); assert.equal(c.mostParked[0].number, 1);
48
+ assert.match(renderCensus({ repo: "o/r", issues: c }), /\| amendment_syntax \| 2 \| 1 \|/);
49
+ });
50
+ it("summarises batch rows: outcomes, deferral codes and merged-lane phase timing", () => {
51
+ const b = censusBatchRows([
52
+ { outcome: "merged", phases: { implement: { ms: 300000 }, ci_wait: { ms: 600000 } } },
53
+ { outcome: "merged", phases: { implement: { ms: 420000 } } },
54
+ { outcome: "deferred", code: "sandbox.capacity" }, { outcome: "needs-human", code: "ci.red" }, { issue: 1 },
55
+ ]);
56
+ assert.equal(b.outcomes.merged, 2); assert.equal(b.deferred["sandbox.capacity"], 1); assert.equal(b.needsHuman["ci.red"], 1);
57
+ assert.equal(b.phases.implement.n, 2); assert.equal(b.phases.ci_wait.median_min, 10);
58
+ });
59
+ });
@@ -0,0 +1,46 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5979: identical-failure stop. A lane that ends needs-human with the same (code, normalised detail) as an earlier NEEDS_HUMAN
5
+ * or PARKED comment of the issue is parked with one consolidated comment instead of being recovered or relaunched. Pure.
6
+ */
7
+ import { createHash } from "node:crypto";
8
+
9
+ export const SIG_RE = /\bsig=([0-9a-f]{12})\b/;
10
+ const MARKER_RE = /<!--\s*FORGE:(NEEDS_HUMAN|PARKED)(?![A-Za-z0-9_])/;
11
+
12
+ /** Detail without what differs between two runs of the same failure: shas, timestamps, numbers (costs, counts, ids), whitespace. */
13
+ export function normalizeDetail(detail) {
14
+ return String(detail ?? "")
15
+ .replace(/\b\d{4}-\d{2}-\d{2}T[\d:.]+Z?\b/g, "")
16
+ .replace(/\b[0-9a-f]{7,40}\b/g, "")
17
+ .replace(/\$\d+(\.\d+)?/g, "")
18
+ .replace(/\d+/g, "")
19
+ .replace(/\s+/g, " ")
20
+ .trim()
21
+ .toLowerCase();
22
+ }
23
+
24
+ /** 12 hex characters of sha256(code + normalised detail): a repeat fingerprint, not a security hash (sha256 keeps CodeQL js/weak-cryptographic-algorithm quiet). */
25
+ export function repeatSignature(code, detail) {
26
+ return createHash("sha256").update(`${code ?? ""}\n${normalizeDetail(detail)}`).digest("hex").slice(0, 12);
27
+ }
28
+
29
+ /** Earlier trusted NEEDS_HUMAN/PARKED comments carrying `sig=<hash>`. A PARKED summary counts as the failure it parked on. */
30
+ export function countIdentical(comments, sig, trusted = () => true) {
31
+ let n = 0;
32
+ for (const c of Array.isArray(comments) ? comments : []) {
33
+ const body = String(c?.body ?? "");
34
+ if (MARKER_RE.test(body) && SIG_RE.exec(body)?.[1] === sig && trusted(c)) n++;
35
+ }
36
+ return n;
37
+ }
38
+
39
+ /** True from the 2nd identical failure (`count` includes the one being handled). */
40
+ export const shouldPark = (count) => count >= 2;
41
+
42
+ /** The one consolidated comment: the attempts, the identical failure, and what would unblock it. */
43
+ export function summaryComment({ attempts, code, detail, unblock, sig = "" }) {
44
+ const n = Number.isInteger(attempts) ? attempts : 2;
45
+ return `## Parked: the same failure repeated\n**Attempts**: ${n} lane runs ended with the identical failure \`${code}\`; the engine stops relaunching it.\n**Failure**: ${String(detail ?? "").trim().slice(0, 1500)}\n**To unblock**: ${unblock || "a decision or input that changes what the lane can do (edit the issue or contract, supply the missing input), then remove the parked label to rerun."}${sig ? `\nsig=${sig}` : ""}`;
46
+ }
@@ -0,0 +1,45 @@
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 { repeatSignature, countIdentical, shouldPark, summaryComment } from "./failure-stop.mjs";
6
+ import { OUTCOME_CODES, RECOVERABLE_CODES, classifyNeedsHuman, parkedLabel } from "../engine/outcome-codes.mjs";
7
+
8
+ const D1 = "R3 unimplemented at 1e0c3e45 (cost $1.2345, 12 turns) 2026-11-25T10:00:00Z";
9
+ const D2 = "R3 unimplemented at 0703a2d8 (cost $9.99, 40 turns) 2026-11-26T11:11:11Z";
10
+ const nh = (sig) => ({ body: `<!-- FORGE:NEEDS_HUMAN -->\n## Needs human\nx\n\nsig=${sig}\n\n_cost $1_` });
11
+
12
+ describe("identical-failure stop (#5979)", () => {
13
+ it("the signature is stable across shas, costs and timestamps and differs across codes and details", () => {
14
+ assert.equal(repeatSignature("conformance.omission", D1), repeatSignature("conformance.omission", D2));
15
+ assert.notEqual(repeatSignature("conformance.omission", D1), repeatSignature("ci.red", D1));
16
+ assert.notEqual(repeatSignature("ci.red", "lint failed"), repeatSignature("ci.red", "tests failed"));
17
+ });
18
+ it("the 2nd identical failure parks, the 1st does not", () => {
19
+ const sig = repeatSignature("ci.red", "boom");
20
+ assert.equal(shouldPark(countIdentical([], sig) + 1), false);
21
+ assert.equal(shouldPark(countIdentical([nh(sig)], sig) + 1), true);
22
+ assert.equal(shouldPark(countIdentical([nh("ffffffffffff")], sig) + 1), false);
23
+ });
24
+ it("an untrusted comment or one without the marker does not count; a PARKED summary does", () => {
25
+ const sig = "abcabcabcabc";
26
+ assert.equal(countIdentical([nh(sig)], sig, () => false), 0);
27
+ assert.equal(countIdentical([{ body: `sig=${sig}` }], sig), 0);
28
+ assert.equal(countIdentical([{ body: `<!-- FORGE:PARKED -->\nsig=${sig}` }], sig), 1);
29
+ });
30
+ it("the summary names the attempts, the failure and what would unblock it", () => {
31
+ const s = summaryComment({ attempts: 2, code: "ci.red", detail: "boom", unblock: "decide X", sig: "abcabcabcabc" });
32
+ assert.match(s, /2 lane runs/);
33
+ assert.match(s, /`ci\.red`/);
34
+ assert.match(s, /boom/);
35
+ assert.match(s, /To unblock\*\*: decide X/);
36
+ assert.match(s, /sig=abcabcabcabc/);
37
+ });
38
+ it("failure.repeated is parked, never recoverable", () => {
39
+ assert.equal(RECOVERABLE_CODES.includes(OUTCOME_CODES.FAILURE_REPEATED), false);
40
+ const row = { outcome: "needs-human", code: OUTCOME_CODES.FAILURE_REPEATED };
41
+ assert.equal(classifyNeedsHuman(row), "terminal");
42
+ assert.equal(classifyNeedsHuman(row, { parked: true }), "parked");
43
+ assert.equal(parkedLabel(OUTCOME_CODES.FAILURE_REPEATED), "parked:failure.repeated");
44
+ });
45
+ });