forgedock 1.52.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 (93) 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 +53 -16
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +15 -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 +195 -22
  21. package/bin/lean/conformance.test.mjs +152 -5
  22. package/bin/lean/effects.mjs +8 -4
  23. package/bin/lean/execution.mjs +19 -3
  24. package/bin/lean/execution.test.mjs +39 -0
  25. package/bin/lean/findinglabel.mjs +16 -0
  26. package/bin/lean/findinglabel.test.mjs +39 -0
  27. package/bin/lean/issuewatch-release.mjs +6 -2
  28. package/bin/lean/issuewatch-release.test.mjs +16 -0
  29. package/bin/lean/issuewatch.mjs +11 -1
  30. package/bin/lean/lanelock.mjs +14 -0
  31. package/bin/lean/lean.mjs +165 -34
  32. package/bin/lean/lean.test.mjs +289 -9
  33. package/bin/lean/light.mjs +48 -7
  34. package/bin/lean/light.test.mjs +37 -3
  35. package/bin/lean/limits.test.mjs +142 -9
  36. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  37. package/bin/lean/orchestrate.mjs +96 -26
  38. package/bin/lean/postdeploy-check.test.mjs +39 -0
  39. package/bin/lean/prompts.mjs +8 -7
  40. package/bin/lean/quota.mjs +39 -0
  41. package/bin/lean/recovery.test.mjs +10 -0
  42. package/bin/lean/relaxation.mjs +73 -0
  43. package/bin/lean/relaxation.test.mjs +54 -0
  44. package/bin/lean/release-postmerge.mjs +119 -0
  45. package/bin/lean/release-rehearsal.mjs +63 -0
  46. package/bin/lean/release-rehearsal.test.mjs +93 -0
  47. package/bin/lean/release-review.e2e.test.mjs +77 -0
  48. package/bin/lean/release-review.mjs +198 -0
  49. package/bin/lean/release-review.test.mjs +180 -0
  50. package/bin/lean/release.mjs +228 -0
  51. package/bin/lean/release.test.mjs +292 -0
  52. package/bin/lean/rotator.mjs +150 -31
  53. package/bin/lean/rotator.test.mjs +105 -2
  54. package/bin/lean/sandbox-remote.mjs +9 -2
  55. package/bin/lean/schedd.mjs +49 -4
  56. package/bin/lean/schedd.test.mjs +87 -6
  57. package/bin/lean/verifier.mjs +3 -2
  58. package/bin/lean/verify.mjs +2 -1
  59. package/bin/lean/verify.test.mjs +6 -0
  60. package/bin/pool/agent.mjs +18 -4
  61. package/bin/pool/router.mjs +66 -24
  62. package/bin/review-staging.mjs +23 -0
  63. package/bin/stats/conformance-outcomes.mjs +208 -0
  64. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  65. package/bin/stats/depth.mjs +218 -0
  66. package/bin/stats/depth.test.mjs +133 -0
  67. package/bin/stats/experiment.mjs +7 -5
  68. package/bin/stats/github-source.mjs +2 -2
  69. package/bin/stats/index.mjs +64 -2
  70. package/bin/stats/local-source.mjs +11 -0
  71. package/bin/stats/query.mjs +69 -0
  72. package/bin/stats/selffiled.mjs +52 -0
  73. package/bin/stats/selffiled.test.mjs +71 -0
  74. package/commands/orchestrate.md +1 -1
  75. package/commands/review-pr-agents/security.md +4 -0
  76. package/commands/review-pr-staging.md +2 -0
  77. package/commands/work-on/build.md +4 -6
  78. package/docs/CONFIG.md +65 -8
  79. package/docs/ISSUE-WATCH.md +2 -0
  80. package/docs/OUTCOME-CODES.md +3 -0
  81. package/docs/STATS.md +44 -0
  82. package/docs/TELEMETRY.md +1 -1
  83. package/package.json +1 -1
  84. package/pool/README.md +1 -1
  85. package/pool/image/cs-cred +14 -1
  86. package/scripts/backfill-finding-labels.mjs +50 -0
  87. package/scripts/backfill-finding-labels.test.mjs +36 -0
  88. package/scripts/doctor-pipeline-state.sh +21 -6
  89. package/scripts/file-deferred-followups.sh +59 -251
  90. package/scripts/file-deferred-followups.test.sh +85 -206
  91. package/scripts/followup-route.mjs +12 -0
  92. package/scripts/owner-route-parity.test.sh +17 -1
  93. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -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
+ }
@@ -0,0 +1,54 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { analyzeRelaxations, relaxationFailures, relaxationBlock, isRelaxationTestPath } from "./relaxation.mjs";
6
+ import { reviewerPrompt } from "./prompts.mjs";
7
+ import { verifierPrompt } from "./verifier.mjs";
8
+
9
+ const hunk = (file, lines, start = 10) => `diff --git a/${file} b/${file}\n@@ -1,0 +${start},${lines.length} @@\n${lines.map((l) => `+${l}`).join("\n")}\n`;
10
+ const removal = (file, lines) => `diff --git a/${file} b/${file}\n@@ -3,${lines.length} +3,0 @@\n${lines.map((l) => `-${l}`).join("\n")}\n`;
11
+ // modelled on AlterLab #39954: a "thin stub" rescue whose script_redirect class accepts JS cookie challenges
12
+ const RESCUE = hunk("shared/detection/antibot.py", ["def thin_stub_rescue(html):", " if SCRIPT_REDIRECT.search(html): # document.cookie=...; location.href=...", " return True"]);
13
+ const NEG = hunk("tests/test_antibot.py", ["def test_cookie_challenge_not_benign():", " assert not thin_stub_rescue(COOKIE_CHALLENGE)"]);
14
+ const GLOBS = ["shared/detection/**"];
15
+
16
+ describe("#5237 relaxation detector", () => {
17
+ it("replay of #39954: the cookie-challenge acceptance is flagged and blocks without a negative test", () => {
18
+ const a = analyzeRelaxations({ diff: RESCUE, riskPaths: GLOBS });
19
+ assert.ok(a.relaxations.length >= 1);
20
+ assert.equal(a.relaxations[0].file, "shared/detection/antibot.py");
21
+ assert.ok(a.relaxations.some((r) => /return True/.test(r.excerpt)));
22
+ const f = relaxationFailures(a);
23
+ assert.equal(f.length, 1); assert.equal(f[0].code, "conformance.unimplemented"); assert.equal(f[0].kind, "relaxation_untested");
24
+ });
25
+ it("a positive-only test does not satisfy the requirement; a negative test does", () => {
26
+ const pos = hunk("tests/test_antibot.py", ["def test_thin_page_ok():", " assert thin_stub_rescue(THIN_PAGE) is True"]);
27
+ assert.equal(relaxationFailures(analyzeRelaxations({ diff: RESCUE + pos, riskPaths: GLOBS })).length, 1);
28
+ const a = analyzeRelaxations({ diff: RESCUE + NEG, riskPaths: GLOBS });
29
+ assert.ok(a.negatives >= 1); assert.deepEqual(relaxationFailures(a), []);
30
+ });
31
+ it("a removed deny is a relaxation", () => {
32
+ const a = analyzeRelaxations({ diff: removal("shared/detection/rules.py", [" if challenge(html):", " raise Blocked()"]), riskPaths: GLOBS });
33
+ assert.deepEqual(a.relaxations.map((r) => r.class), ["deny_removed"]);
34
+ });
35
+ it("ignores files outside the declared globs, test files, comments, and an empty glob list", () => {
36
+ assert.deepEqual(analyzeRelaxations({ diff: RESCUE, riskPaths: ["billing/**"] }).relaxations, []);
37
+ assert.deepEqual(analyzeRelaxations({ diff: RESCUE, riskPaths: [] }).relaxations, []);
38
+ assert.deepEqual(analyzeRelaxations({ diff: hunk("shared/detection/x.py", ["# return True when benign"]), riskPaths: GLOBS }).relaxations, []);
39
+ assert.deepEqual(analyzeRelaxations({ diff: hunk("shared/detection/test_x.py", [" return True"]), riskPaths: GLOBS }).relaxations, []);
40
+ assert.ok(isRelaxationTestPath("tests/a.py") && isRelaxationTestPath("src/a.test.ts") && !isRelaxationTestPath("src/a.ts"));
41
+ assert.deepEqual(analyzeRelaxations({ diff: "", riskPaths: GLOBS }), { relaxations: [], negatives: 0 });
42
+ });
43
+ it("prompts carry the relaxed hunks; unchanged without relaxations", () => {
44
+ const { relaxations } = analyzeRelaxations({ diff: RESCUE, riskPaths: GLOBS });
45
+ const blk = relaxationBlock(relaxations);
46
+ assert.match(blk, /<relaxation_checks>[\s\S]*antibot\.py:\d+[\s\S]*negative-corpus/);
47
+ const base = { issue: { number: 1, title: "t", body: "b" }, contract: {}, diff: "d", files: ["a"] };
48
+ assert.doesNotMatch(verifierPrompt(base), /relaxation_checks/);
49
+ assert.match(verifierPrompt({ ...base, relaxations }), /<relaxation_checks>/);
50
+ assert.doesNotMatch(reviewerPrompt({ ...base, result: {} }), /relaxation_checks/);
51
+ assert.match(reviewerPrompt({ ...base, result: {}, relaxations }), /<relaxation_checks>/);
52
+ assert.equal(relaxationBlock([]), "");
53
+ });
54
+ });
@@ -0,0 +1,119 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Post-merge step of `forgedock release` (#5213, part 3 of #5208): confirm or dispatch the publish run for the merge commit,
5
+ * wait for the published artifact (`release.artifact_check`), then open and merge the version-sync PR (`release.version_sync`).
6
+ * Every wait is bounded (`ctx.config.postMerge` overrides the bounds) and ends in `{blocked}`, never a throw, so a resume
7
+ * retries the step; each sub-step is idempotent (an existing run, PR or merged PR is reused). Rationale:
8
+ * devdocs/decisions/5208-release-postmerge.md.
9
+ */
10
+
11
+ const BOUNDS = {
12
+ publishPolls: 6, publishPollMs: 10_000, // wait for a run to appear (bot merges never trigger one)
13
+ runPolls: 90, runPollMs: 20_000, // wait for the run to finish
14
+ artifactTries: 8, artifactBaseMs: 5_000, artifactMaxMs: 120_000, // npm propagation: exponential backoff
15
+ branchPolls: 6, branchPollMs: 10_000, // wait for the sync branch to be pushed
16
+ checkPolls: 30, checkPollMs: 20_000, // wait for the sync PR's checks
17
+ };
18
+ const json = (s) => JSON.parse(String(s || "null"));
19
+ const blocked = (reason) => ({ blocked: true, reason });
20
+ const GREEN = new Set(["SUCCESS", "NEUTRAL", "SKIPPED"]);
21
+
22
+ async function findRun({ io, repo, workflow, sha }) {
23
+ const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--commit", sha, "--json", "databaseId,status,conclusion", "--limit", "5"])) ?? [];
24
+ return runs[0] ?? null;
25
+ }
26
+
27
+ /** Poll `fn` until it returns a truthy value, at most `polls` times, sleeping `ms` between tries. */
28
+ async function poll(io, polls, ms, fn) {
29
+ for (let i = 0; i < polls; i++) {
30
+ const v = await fn();
31
+ if (v) return v;
32
+ if (i < polls - 1) await io.sleep(ms);
33
+ }
34
+ return null;
35
+ }
36
+
37
+ async function publishRun(ctx, sha, b) {
38
+ const { io, repo, config } = ctx;
39
+ const workflow = config.publishWorkflow || "publish.yml";
40
+ const look = () => findRun({ io, repo, workflow, sha });
41
+ let run = await poll(io, b.publishPolls, b.publishPollMs, look);
42
+ let dispatched = false;
43
+ if (!run) {
44
+ await io.gh(["workflow", "run", workflow, "--repo", repo, "--ref", ctx.def]);
45
+ dispatched = true;
46
+ run = await poll(io, b.publishPolls, b.publishPollMs, look);
47
+ if (!run) return { err: `no ${workflow} run for ${sha.slice(0, 8)} after a dispatch on ${ctx.def}; check the Actions tab, then resume` };
48
+ }
49
+ const done = await poll(io, b.runPolls, b.runPollMs, async () => { const r = await look(); return r?.status === "completed" ? r : null; });
50
+ if (!done) return { err: `${workflow} run ${run.databaseId} did not finish in time; resume to keep waiting` };
51
+ if (done.conclusion !== "success") return { err: `${workflow} run ${done.databaseId} concluded ${done.conclusion}` };
52
+ return { run: done.databaseId, dispatched };
53
+ }
54
+
55
+ async function artifact(ctx, b) {
56
+ const { io, config } = ctx;
57
+ let wait = b.artifactBaseMs;
58
+ for (let i = 0; i < b.artifactTries; i++) {
59
+ if ((await io.run(config.artifactCheck)).ok) return { ok: true, tries: i + 1 };
60
+ if (i < b.artifactTries - 1) { await io.sleep(wait); wait = Math.min(wait * 2, b.artifactMaxMs); }
61
+ }
62
+ return { err: `release.artifact_check still failing after ${b.artifactTries} tries: ${config.artifactCheck}` };
63
+ }
64
+
65
+ async function versionSync(ctx, sha, b) {
66
+ const { io, repo, staging } = ctx;
67
+ const pkg = JSON.parse(Buffer.from(String(await io.gh(["api", `repos/${repo}/contents/package.json?ref=${sha}`, "--jq", ".content"])).replace(/\s/g, ""), "base64").toString("utf8"));
68
+ const branch = `chore/sync-version-${pkg.version}`;
69
+ const find = async () => json(await io.gh(["pr", "list", "--repo", repo, "--base", staging, "--head", branch, "--state", "all", "--json", "number,state", "--limit", "1"]))?.[0] ?? null;
70
+ let pr = await find();
71
+ if (pr?.state === "MERGED") return { pr: pr.number, merged: true, reused: true };
72
+ if (!pr) {
73
+ const has = await poll(io, b.branchPolls, b.branchPollMs, async () => { try { await io.gh(["api", `repos/${repo}/branches/${branch}`, "--jq", ".name"]); return true; } catch { return false; } });
74
+ if (!has) return { err: `version-sync branch ${branch} did not appear; publish.yml may have skipped the sync, open it by hand` };
75
+ const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", staging, "--head", branch, "--title", `chore: sync version ${pkg.version} to ${staging}`, "--body", `Version-only sync of the ${pkg.version} release back to ${staging} (forgedock release).`])).trim();
76
+ const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
77
+ if (!Number.isSafeInteger(n)) return { err: `gh pr create returned no PR url: ${url}` };
78
+ pr = { number: n };
79
+ }
80
+ let red = null;
81
+ const green = await poll(io, b.checkPolls, b.checkPollMs, async () => {
82
+ const v = json(await io.gh(["pr", "view", String(pr.number), "--repo", repo, "--json", "state,headRefOid,statusCheckRollup"]));
83
+ if (v?.state === "MERGED") return { head: null, already: true };
84
+ const res = (v?.statusCheckRollup ?? []).map((c) => String(c.conclusion || c.state || "").toUpperCase());
85
+ if (res.some((r) => r && !GREEN.has(r) && !["PENDING", "IN_PROGRESS", "QUEUED", "EXPECTED"].includes(r))) { red = res.find((r) => r && !GREEN.has(r) && !["PENDING", "IN_PROGRESS", "QUEUED", "EXPECTED"].includes(r)); return { red: true }; }
86
+ return res.length && res.every((r) => GREEN.has(r)) ? { head: v.headRefOid } : null;
87
+ });
88
+ if (green?.already) return { pr: pr.number, merged: true };
89
+ if (green?.red) return { err: `version-sync PR #${pr.number} has a failing check (${red}); fix and merge it by hand` };
90
+ // GITHUB_TOKEN PRs get no CI, so "no checks" is a stop, not a green light.
91
+ if (!green) return { err: `version-sync PR #${pr.number} has no passing checks yet (a PR opened by GITHUB_TOKEN gets no CI: close and reopen it); resume once green` };
92
+ await io.gh(["pr", "merge", String(pr.number), "--repo", repo, "--merge", "--match-head-commit", green.head]);
93
+ return { pr: pr.number, merged: true };
94
+ }
95
+
96
+ /** @returns {Promise<{published, run, artifact, sync}|{blocked: true, reason: string}|{stopped: true, why: string}>} */
97
+ export async function postMergeStep(ctx) {
98
+ const { io, repo, state, config = {} } = ctx;
99
+ const b = { ...BOUNDS, ...(config.postMerge ?? {}) };
100
+ const pr = state.steps["release-pr"].result.pr;
101
+ const view = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "state,mergeCommit"]));
102
+ const sha = view?.mergeCommit?.oid;
103
+ if (view?.state !== "MERGED" || !sha) return { stopped: true, why: `release PR #${pr} is not merged (${view?.state ?? "unknown"}); nothing to publish yet` };
104
+
105
+ const pub = await publishRun(ctx, sha, b);
106
+ if (pub.err) return blocked(pub.err);
107
+ let art = null;
108
+ if (config.artifactCheck) {
109
+ art = await artifact(ctx, b);
110
+ if (art.err) return blocked(art.err);
111
+ }
112
+ let sync = null;
113
+ if (config.versionSync) {
114
+ sync = await versionSync(ctx, sha, b);
115
+ if (sync.err) return blocked(sync.err);
116
+ }
117
+ io.print(`release: published (run ${pub.run}${pub.dispatched ? ", dispatched" : ""})${art ? ", artifact confirmed" : ""}${sync ? `, version-sync PR #${sync.pr} merged` : ""}`);
118
+ return { published: true, merge: sha, run: pub.run, dispatched: pub.dispatched, artifact: art?.ok ?? null, sync };
119
+ }
@@ -0,0 +1,63 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Rehearsal step of `forgedock release` (#5253): runs the project's own deploy dry-run (forge.yaml `release.rehearsal`) on the
5
+ * host against the release-PR head, after review and before promotion. A failing blocking rehearsal files (or updates) one
6
+ * `release-blocker` issue per head and stops the job like a GATE_FAILURE; `--resume` re-runs it. The result is recorded in the
7
+ * release state and in a FORGE:REHEARSAL section of the release PR body. No model call. Effects go through `ctx.io`.
8
+ */
9
+ export const REHEARSAL_TIMEOUT_MS = 20 * 60_000;
10
+ export const OUTPUT_TAIL_CHARS = 6000;
11
+ export const BLOCKER_LABEL = "release-blocker";
12
+ const PR_START = "<!-- FORGE:REHEARSAL -->", PR_END = "<!-- /FORGE:REHEARSAL -->";
13
+ const json = (s) => JSON.parse(String(s || "null"));
14
+ const off = (v) => ["false", "off", "no", "0"].includes(String(v ?? "").trim().toLowerCase());
15
+
16
+ /**
17
+ * The rehearsal keys of forge.yaml's `release` map -> `{command, timeoutMs, blocking}`, or null when no command is set. The
18
+ * forge.yaml parser reads two levels, so the block is the flat keys `rehearsal_command`, `rehearsal_timeout` (seconds) and
19
+ * `rehearsal_blocking`.
20
+ */
21
+ export function parseRehearsalConfig(r) {
22
+ const command = typeof r?.rehearsal_command === "string" ? r.rehearsal_command.trim() : "";
23
+ if (!command) return null;
24
+ const secs = Number(r.rehearsal_timeout);
25
+ return { command, timeoutMs: Number.isFinite(secs) && secs > 0 ? secs * 1000 : REHEARSAL_TIMEOUT_MS, blocking: !off(r.rehearsal_blocking) };
26
+ }
27
+
28
+ const tail = (s) => { const t = String(s ?? ""); return t.length > OUTPUT_TAIL_CHARS ? `…${t.slice(-OUTPUT_TAIL_CHARS)}` : t; };
29
+ const marker = (head) => `<!-- FORGE:RELEASE_BLOCKER head=${head} -->`;
30
+
31
+ const prSection = (res) => `${PR_START}\n**Rehearsal**: ${res.ok ? "PASS" : res.blocking ? "FAIL (promotion held)" : "FAIL (non-blocking)"} at \`${res.head}\` — \`${res.command}\`${res.issue ? ` (#${res.issue})` : ""}\n${PR_END}`;
32
+
33
+ async function recordInPr({ io, repo, pr }, res) {
34
+ const body = String(json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "body"]))?.body ?? "");
35
+ const a = body.indexOf(PR_START), b = body.indexOf(PR_END);
36
+ const base = a >= 0 && b > a ? (body.slice(0, a) + body.slice(b + PR_END.length)).trimEnd() : body.trimEnd();
37
+ await io.gh(["pr", "edit", String(pr), "--repo", repo, "--body", `${base}\n\n${prSection(res)}\n`]);
38
+ }
39
+
40
+ /** One open release-blocker issue per head: comment on it when it exists, else create it. @returns the issue number. */
41
+ async function fileBlocker({ io, repo, pr }, res) {
42
+ const text = `Release rehearsal failed on PR #${pr} at head \`${res.head}\`.\n\nCommand: \`${res.command}\` (exit ${res.code ?? "?"}${res.timedOut ? ", timed out" : ""})\n\n\`\`\`\n${tail(res.output)}\n\`\`\`\n`;
43
+ const open = json(await io.gh(["issue", "list", "--repo", repo, "--label", BLOCKER_LABEL, "--state", "open", "--limit", "100", "--json", "number,body"])) ?? [];
44
+ const found = open.find((i) => String(i.body ?? "").includes(marker(res.head)));
45
+ if (found) { await io.gh(["issue", "comment", String(found.number), "--repo", repo, "--body", text]); return found.number; }
46
+ const url = String(await io.gh(["issue", "create", "--repo", repo, "--label", BLOCKER_LABEL, "--title", `release-blocker: rehearsal failed at ${res.head.slice(0, 12)}`, "--body", `${marker(res.head)}\n${text}`])).trim();
47
+ return Number(/\/issues\/(\d+)/.exec(url)?.[1]) || null;
48
+ }
49
+
50
+ export async function rehearsalStep(ctx) {
51
+ const { io, repo, config } = ctx;
52
+ const cfg = config.rehearsal;
53
+ if (!cfg) return { skipped: true };
54
+ const { pr } = ctx.state.steps["release-pr"].result;
55
+ const head = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "headRefOid"]))?.headRefOid;
56
+ const run = await io.rehearse(cfg.command, { timeout: cfg.timeoutMs });
57
+ const res = { ok: !!run.ok, head, command: cfg.command, blocking: cfg.blocking, code: run.code ?? null, timedOut: !!run.timedOut, output: run.ok ? "" : tail(run.output), at: new Date(io.now()).toISOString() };
58
+ if (!res.ok) res.issue = await fileBlocker({ io, repo, pr }, res);
59
+ await recordInPr({ io, repo, pr }, res);
60
+ const { output, ...kept } = res;
61
+ if (!res.ok && res.blocking) return { stopped: true, why: `release rehearsal failed at ${head} (release-blocker #${res.issue}); fix it, then resume`, ...kept };
62
+ return kept;
63
+ }
@@ -0,0 +1,93 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { tmpDir } from "../tests/_tmp.mjs";
6
+ import { runRelease, withStubs, newReleaseId, readReleaseConfig, openRelease } from "./release.mjs";
7
+ import { parseRehearsalConfig } from "./release-rehearsal.mjs";
8
+
9
+ const DISK = [{ mount: "/", type: "ext4" }];
10
+ const REPO = "o/r", HEAD = "b".repeat(40);
11
+ const ok = async () => ({ ok: true });
12
+
13
+ function fakeIo({ run = { ok: true }, issues = [], body = "Bundle" } = {}) {
14
+ const calls = [], rehearsed = [];
15
+ const st = { issues: [...issues], body };
16
+ const io = {
17
+ calls, rehearsed, st, now: () => 1_700_000_000_000, print: () => {},
18
+ runningLanes: async () => [], batches: async () => [], setParallel: async () => {},
19
+ rehearse: async (cmd, o) => { rehearsed.push([cmd, o]); return run; },
20
+ gh: async (a) => {
21
+ calls.push(a); const j = a.join(" ");
22
+ if (a[0] === "pr" && a[1] === "list" && a.includes("open")) return JSON.stringify(a.includes("--head") ? [{ number: 7, headRefOid: HEAD, url: "u" }] : []);
23
+ if (j.includes("headRefOid")) return JSON.stringify({ headRefOid: HEAD });
24
+ if (j.includes("--json comments")) return JSON.stringify({ comments: [{ body: "FORGE:GATE_PASS" }] });
25
+ if (a[0] === "api") return JSON.stringify([{ name: "forge/deploy-gate", conclusion: "success" }]);
26
+ if (j.includes("--json body")) return JSON.stringify({ body: st.body });
27
+ if (a[0] === "pr" && a[1] === "edit") { st.body = a[a.indexOf("--body") + 1]; return ""; }
28
+ if (a[0] === "pr" && a[1] === "merge") return "";
29
+ if (a[0] === "issue" && a[1] === "list") return JSON.stringify(st.issues);
30
+ if (a[0] === "issue" && a[1] === "create") { st.issues.push({ number: 42, body: a[a.indexOf("--body") + 1] }); return "https://github.com/o/r/issues/42"; }
31
+ if (a[0] === "issue" && a[1] === "comment") return "";
32
+ throw new Error(`unexpected gh ${j}`);
33
+ },
34
+ };
35
+ return io;
36
+ }
37
+ const go = async (io, config, root = tmpDir("rehearsal-"), id = newReleaseId()) => ({
38
+ out: await runRelease({ io, repo: REPO, root, mounts: DISK, id, opts: { merge: true }, config, branches: { staging: "staging", default: "main" }, steps: withStubs({ review: ok, fixes: ok, "post-merge": ok }) }),
39
+ root, id,
40
+ });
41
+ const cfg = (o = {}) => ({ rehearsal: parseRehearsalConfig({ rehearsal_command: "./dry-run.sh", ...o }) });
42
+
43
+ describe("release rehearsal (#5253)", () => {
44
+ it("unconfigured: no rehearse, no issue/PR-body calls, promotion merges", async () => {
45
+ const io = fakeIo();
46
+ const { out } = await go(io, {});
47
+ assert.equal(out.status, "done");
48
+ assert.equal(io.rehearsed.length, 0);
49
+ assert.ok(!io.calls.some((a) => a[0] === "issue" || (a[0] === "pr" && a[1] === "edit")));
50
+ assert.ok(io.calls.some((a) => a[0] === "pr" && a[1] === "merge"));
51
+ });
52
+
53
+ it("failing rehearsal holds promotion and files one blocker with output and head; a rerun comments", async () => {
54
+ const io = fakeIo({ run: { ok: false, code: 2, output: "bundle missing incident files" } });
55
+ const { out, root, id } = await go(io, cfg());
56
+ assert.equal(out.status, "stopped"); assert.equal(out.step, "rehearsal");
57
+ assert.ok(!io.calls.some((a) => a[0] === "pr" && a[1] === "merge"));
58
+ const creates = io.calls.filter((a) => a[0] === "issue" && a[1] === "create");
59
+ assert.equal(creates.length, 1);
60
+ const body = creates[0][creates[0].indexOf("--body") + 1];
61
+ assert.ok(body.includes("bundle missing incident files") && body.includes(HEAD));
62
+ assert.ok(creates[0].includes("release-blocker"));
63
+ assert.match(io.st.body, /Rehearsal\*\*: FAIL/);
64
+ assert.equal(openRelease(root, id).load().steps.rehearsal.result.head, HEAD);
65
+ await go(io, cfg(), root, id);
66
+ assert.equal(io.calls.filter((a) => a[0] === "issue" && a[1] === "create").length, 1);
67
+ assert.equal(io.calls.filter((a) => a[0] === "issue" && a[1] === "comment").length, 1);
68
+ assert.equal((io.st.body.match(/<!-- FORGE:REHEARSAL -->/g) ?? []).length, 1);
69
+ });
70
+
71
+ it("blocking:false records the failure and still promotes", async () => {
72
+ const io = fakeIo({ run: { ok: false, code: 1, output: "x" } });
73
+ const { out } = await go(io, cfg({ rehearsal_blocking: "false" }));
74
+ assert.equal(out.status, "done");
75
+ assert.match(io.st.body, /non-blocking/);
76
+ });
77
+
78
+ it("passing rehearsal is recorded in state and PR body, then promotes; timeout is passed in ms", async () => {
79
+ const io = fakeIo();
80
+ const { out, root, id } = await go(io, cfg({ rehearsal_timeout: "30" }));
81
+ assert.equal(out.status, "done");
82
+ assert.equal(io.rehearsed[0][1].timeout, 30_000);
83
+ const r = openRelease(root, id).load().steps.rehearsal;
84
+ assert.ok(r.done && r.result.ok && r.result.head === HEAD);
85
+ assert.match(io.st.body, /Rehearsal\*\*: PASS/);
86
+ });
87
+
88
+ it("config parsing", () => {
89
+ assert.ok(!("rehearsal" in readReleaseConfig("")));
90
+ assert.equal(parseRehearsalConfig({ rehearsal_command: " " }), null);
91
+ assert.deepEqual(readReleaseConfig("release:\n rehearsal_command: ./d.sh\n rehearsal_timeout: 60\n rehearsal_blocking: false\n").rehearsal, { command: "./d.sh", timeoutMs: 60000, blocking: false });
92
+ });
93
+ });