forgedock 1.59.2 → 1.60.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 (94) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -3
  2. package/bin/engine-cli.mjs +50 -10
  3. package/bin/labels.json +5 -0
  4. package/bin/lean/batch.mjs +21 -2
  5. package/bin/lean/batch.test.mjs +116 -1
  6. package/bin/lean/conformance.mjs +12 -5
  7. package/bin/lean/conformance.test.mjs +30 -2
  8. package/bin/lean/depcache.mjs +34 -15
  9. package/bin/lean/depcache.test.mjs +100 -1
  10. package/bin/lean/design-gate.mjs +15 -10
  11. package/bin/lean/design-gate.test.mjs +21 -0
  12. package/bin/lean/effects.mjs +18 -2
  13. package/bin/lean/execution.mjs +23 -5
  14. package/bin/lean/execution.test.mjs +81 -1
  15. package/bin/lean/gatewatch.test.mjs +5 -5
  16. package/bin/lean/issuewatch-triage.mjs +68 -0
  17. package/bin/lean/issuewatch-triage.test.mjs +98 -0
  18. package/bin/lean/issuewatch.mjs +34 -6
  19. package/bin/lean/issuewatch.test.mjs +11 -0
  20. package/bin/lean/lanelock.mjs +5 -4
  21. package/bin/lean/lean.mjs +123 -17
  22. package/bin/lean/lean.test.mjs +154 -6
  23. package/bin/lean/orchestrate-cancel.test.mjs +33 -0
  24. package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
  25. package/bin/lean/orchestrate-recovering.test.mjs +42 -0
  26. package/bin/lean/orchestrate.mjs +23 -10
  27. package/bin/lean/pagegate.mjs +50 -12
  28. package/bin/lean/pagegate.test.mjs +38 -1
  29. package/bin/lean/phaseledger.mjs +65 -2
  30. package/bin/lean/phaseledger.test.mjs +70 -2
  31. package/bin/lean/preflight.mjs +5 -2
  32. package/bin/lean/preflight.test.mjs +7 -0
  33. package/bin/lean/prompts.mjs +2 -1
  34. package/bin/lean/recovery.test.mjs +11 -6
  35. package/bin/lean/release-classify.mjs +143 -0
  36. package/bin/lean/release-classify.test.mjs +130 -0
  37. package/bin/lean/release-conductor.mjs +163 -0
  38. package/bin/lean/release-conductor.test.mjs +194 -0
  39. package/bin/lean/release-config.mjs +60 -8
  40. package/bin/lean/release-config.test.mjs +43 -1
  41. package/bin/lean/release-control.mjs +22 -5
  42. package/bin/lean/release-control.test.mjs +22 -0
  43. package/bin/lean/release-credentials.mjs +40 -0
  44. package/bin/lean/release-credentials.test.mjs +42 -0
  45. package/bin/lean/release-deploy.mjs +3 -3
  46. package/bin/lean/release-deploy.test.mjs +8 -0
  47. package/bin/lean/release-docs.test.mjs +93 -0
  48. package/bin/lean/release-fence.mjs +2 -0
  49. package/bin/lean/release-gate.mjs +88 -0
  50. package/bin/lean/release-gate.test.mjs +116 -0
  51. package/bin/lean/release-gates.mjs +5 -1
  52. package/bin/lean/release-ledger.mjs +47 -1
  53. package/bin/lean/release-ledger.test.mjs +33 -1
  54. package/bin/lean/release-mergeback.mjs +148 -0
  55. package/bin/lean/release-mergeback.test.mjs +129 -0
  56. package/bin/lean/release-p0.mjs +193 -0
  57. package/bin/lean/release-p0.test.mjs +127 -0
  58. package/bin/lean/release-plan.mjs +267 -0
  59. package/bin/lean/release-plan.test.mjs +202 -0
  60. package/bin/lean/release-preflight.mjs +16 -0
  61. package/bin/lean/release-regate.mjs +141 -0
  62. package/bin/lean/release-regate.test.mjs +149 -0
  63. package/bin/lean/release-review.mjs +5 -3
  64. package/bin/lean/release-rollback.mjs +277 -0
  65. package/bin/lean/release-rollback.test.mjs +245 -0
  66. package/bin/lean/release-snapshot.mjs +48 -9
  67. package/bin/lean/release-snapshot.test.mjs +43 -1
  68. package/bin/lean/release-start.mjs +164 -0
  69. package/bin/lean/release-start.test.mjs +171 -0
  70. package/bin/lean/release-status.mjs +6 -2
  71. package/bin/lean/release-train.mjs +159 -0
  72. package/bin/lean/release-train.test.mjs +139 -0
  73. package/bin/lean/release.mjs +127 -5
  74. package/bin/lean/release.test.mjs +80 -0
  75. package/bin/lean/sandbox-remote.mjs +2 -0
  76. package/bin/lean/schedd-load.test.mjs +82 -0
  77. package/bin/lean/schedd.mjs +67 -31
  78. package/bin/lean/schedd.test.mjs +80 -1
  79. package/bin/lean/validate-catalog.mjs +94 -0
  80. package/bin/lean/validate-catalog.test.mjs +42 -0
  81. package/bin/pool/agent.mjs +4 -1
  82. package/bin/pool/lane-tools.mjs +115 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/warm.mjs +1 -1
  85. package/docs/CONFIG.md +225 -1
  86. package/docs/ISSUE-WATCH.md +1 -0
  87. package/docs/design/visual-gate.md +10 -0
  88. package/docs/eval/adversarial-bench.md +1 -0
  89. package/package.json +1 -1
  90. package/pool/README.md +2 -0
  91. package/scripts/bench-adversarial.mjs +4 -0
  92. package/scripts/bench-lightlane.mjs +2 -1
  93. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  94. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -176,6 +176,7 @@ ${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}
176
176
  ### Recommendation
177
177
  ### Related Issues
178
178
  ### Test plan (bug issues: per deliver requirement, see the contract test_plan)
179
+ ${LEAN_DIR}/classification.json{type,severity,exists_in,flag,exists_in_evidence:{cite,repro:{command,red_on_live,green_after}}}
179
180
 
180
181
  If the issue is already fixed or invalid, write ${RESULT_FILE} {"status":"already-fixed|invalid","summary":"one line","evidence":["file:line ..."]} and stop. A feature already reachable (another name, or a stdlib or wrapped dependency function) is a duplicate: INVALID, naming the equivalent and its path; its deprecation counts against an alias. If it is blocked, write {"status":"blocked","summary":"",...} with a typed "block" (rules below) and stop.
181
182
 
@@ -288,7 +289,7 @@ export function buildOpeningNote({ paths = [], tests = [], packFiles = [] } = {}
288
289
  /** #4857: validate-command rules for the plan prompt (the implement session resumes it), kept out of the shared templates (their token caps are guarded). */
289
290
  export function unrunnableValidateNote(testRunners = null) {
290
291
  const map = testRunners && typeof testRunners === "object" ? Object.entries(testRunners).map(([k, v]) => `${k}/ -> ${v}`).join("; ") : "";
291
- 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.`;
292
+ 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, and the engine rewrites an unrunnable command from the repo's CI-derived command catalogue: prefer the repo's own CI test commands over free-form paths. A substitute that runs the same test ids with the same result is recorded, not failed. A criterion only time or production can show (a 14-day metric, a corpus re-run, a published scorecard) is post-deploy or defer with a bucket: never narrow it into something the lane can observe.`;
292
293
  }
293
294
 
294
295
  /** #5419: the R-docs rule for the planner; "" when forge.yaml docs.required_for is unset. */
@@ -106,16 +106,16 @@ describe("in-batch recovery of mechanical needs-human (#4267)", () => {
106
106
  assert.ok(formatOutcomeLists(rows).some((l) => /^unrecovered: #1 \(budget\.exceeded: Implement turn budget spent/.test(l)));
107
107
  });
108
108
 
109
- it("conformance gaps are recoverable: one recovery lane each, regression/guard_broken/scope_creep/e2e_unverified stay terminal, notes name the defer route", async () => {
110
- const codes = ["conformance.unimplemented", "conformance.omission", "conformance.unjustified_deferral"];
109
+ it("conformance gaps are recoverable: one recovery lane each, guard_broken/e2e_unverified stay terminal, notes name the defer route", async () => {
110
+ const codes = ["conformance.unimplemented", "conformance.omission", "conformance.unjustified_deferral", "conformance.regression", "conformance.scope_creep"];
111
111
  for (const c of codes) {
112
112
  assert.equal(classifyNeedsHuman({ outcome: "needs-human", code: c }), "recoverable", c);
113
113
  assert.ok(RECOVERABLE_CODES.includes(c) && RECOVER_HOW[c], c);
114
114
  }
115
- for (const c of ["conformance.regression", "conformance.guard_broken", "conformance.scope_creep", "conformance.e2e_unverified"]) {
115
+ for (const c of ["conformance.guard_broken", "conformance.e2e_unverified"]) {
116
116
  assert.equal(classifyNeedsHuman({ outcome: "needs-human", code: c }), "terminal", c);
117
117
  }
118
- for (const c of codes.slice(1)) assert.match(RECOVER_HOW[c], /`defer`[\s\S]*why|why[\s\S]*follow-up/i);
118
+ for (const c of codes.slice(1, 3)) assert.match(RECOVER_HOW[c], /`defer`[\s\S]*why|why[\s\S]*follow-up/i);
119
119
  assert.match(RECOVER_HOW["conformance.omission"], /add-requirement/);
120
120
  const { rows, calls } = await batch({ 1: [NH("conformance.omission", "R2 not covered", { branch: "feat/issue-1-lean" }), NH("conformance.omission", "again")] });
121
121
  assert.deepEqual(calls.filter((c) => c.n === 1).map((c) => c.recover?.code ?? null), [null, "conformance.omission"]);
@@ -128,7 +128,7 @@ describe("in-batch recovery of mechanical needs-human (#4267)", () => {
128
128
  1: [NH("builder.blocked", "Builder is blocked (product-decision): pick a pricing model")],
129
129
  2: [],
130
130
  3: [NH("builder.blocked", "Builder is blocked (spend): needs a paid plan")],
131
- 4: [NH("conformance.regression", "R2 broke")],
131
+ 4: [NH("conformance.guard_broken", "R2 broke")],
132
132
  5: [{ terminalReason: "merged" }] }, { 2: "**Depends on**: #1" });
133
133
  const r = byIssue(rows);
134
134
  assert.equal(calls.filter((c) => c.n === 1).length, 1); assert.equal(calls.filter((c) => c.n === 3).length, 1);
@@ -141,7 +141,7 @@ describe("in-batch recovery of mechanical needs-human (#4267)", () => {
141
141
  assert.match(esc, /#1 \(builder\.blocked\): Builder is blocked \(product-decision\)/);
142
142
  assert.match(esc, /#3 \(builder\.blocked\): Builder is blocked \(spend\)/);
143
143
  assert.doesNotMatch(esc, /#4/, "the needs-human list holds only human codes");
144
- assert.ok(lines.some((l) => /^unrecovered: #4 \(conformance\.regression: R2 broke\)$/.test(l)));
144
+ assert.ok(lines.some((l) => /^unrecovered: #4 \(conformance\.guard_broken: R2 broke\)$/.test(l)));
145
145
  });
146
146
 
147
147
  it("base.conflict: a recovery base-sync with a clean result re-queues the issue; the report lists recovered issues separately", async () => {
@@ -167,6 +167,11 @@ describe("in-batch recovery of mechanical needs-human (#4267)", () => {
167
167
  assert.equal(byIssue(rows)[2].recovered, "contract.invalid"); assert.equal(byIssue(rows)[2].outcome, "merged"); assert.equal(calls.filter((c) => c.n === 2).length, 2);
168
168
  });
169
169
 
170
+ it("#5644: conformance.regression gets one recovery lane", async () => {
171
+ const { rows, calls } = await batch({ 1: [NH("conformance.regression"), { terminalReason: "merged" }] });
172
+ assert.equal(byIssue(rows)[1].recovered, "conformance.regression"); assert.equal(byIssue(rows)[1].outcome, "merged"); assert.equal(calls.filter((c) => c.n === 1).length, 2);
173
+ });
174
+
170
175
  it("relabelNeedsHuman (SPEC-7/8): only a recovery that ends final engine-error/deferred relabels; invalid/merged never; a requeued deferred waits", async () => {
171
176
  const relabels = [];
172
177
  const rl = { relabelNeedsHuman: async (x) => { relabels.push(x); }, pollMs: 5 };
@@ -0,0 +1,143 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /** Classification record (#5557): path facts and risk are derived by code from the unit map; the LLM sets only type, severity, exists_in, flag, narrative. */
4
+ import { resolvePath, matchesAny } from "./release-unitmap.mjs";
5
+
6
+ export const CLASSIFICATION_FILE = ".forge-lean/classification.json";
7
+ export const ReleaseClassifyTYPES = ["bug", "feature", "chore", "docs", "infra", "incident"];
8
+ export const SEVERITIES = ["P0", "P1", "P2", "P3"];
9
+ export const EXISTS_IN = ["live", "staging-only", "unknown"];
10
+ export const FLAGS = ["present", "required", "exempt", "none"];
11
+ export const SOURCES = ["path-derived", "text-only", "human"];
12
+ const MIGRATION_RE = /(^|\/)infra\/migrations\//;
13
+ const SAFE_MARKER = /--\s*HOTFIX-SAFE/, UNSAFE_MARKER = /HOTFIX-UNSAFE/;
14
+
15
+ /** Design 4.3 defaults (epic #5549), used when the policy has no `risk.rules`; the implicit last rule is `{risk: low}`. */
16
+ export const DEFAULT_RISK_RULES = [
17
+ { when: { migration: true }, risk: "high", forces: "release" },
18
+ { when: { paths: ["shared/billing*", "services/api/app/**/auth*", "services/api/app/**/billing*", "services/worker/**/queue*", "services/worker/**/dispatch*"] }, risk: "high" },
19
+ { when: { paths: ["shared/penetrator/**", "shared/detection/**", "services/worker/worker/anti_detection/**", "**/tier_policy.py", "shared/rollout*.py"] }, risk: "high", requires: "rollout-declaration" },
20
+ { when: { contract: true }, risk: "medium", forces: "atomic-wave" },
21
+ { when: { rolled_units_gt: 1 }, risk: "medium" },
22
+ { when: { diff_lines_gt: 400 }, risk: "medium" },
23
+ ];
24
+
25
+ /**
26
+ * @param {{diffLines?: number, hotfixMarkers?: {unsafe?: boolean, safe?: string[]}, texts?: Record<string,string>}} extra
27
+ * hotfixMarkers: `unsafe` when any file carries HOTFIX-UNSAFE, `safe` the migration paths carrying `-- HOTFIX-SAFE`; `texts` (file contents by path) is scanned for the same markers.
28
+ */
29
+ export function deriveFacts(policy, files, { diffLines = 0, hotfixMarkers = {}, texts = {} } = {}) {
30
+ const res = (files ?? []).map((f) => resolvePath(policy, f));
31
+ const units = [...new Set(res.flatMap((r) => (r.units.length ? r.units : [])).concat(res.flatMap((r) => r.affects)))];
32
+ const shared = [...new Set(res.filter((r) => r.unit === "none" && r.affects.length).map((r) => r.path.split("/").slice(0, 2).join("/")))];
33
+ const migFiles = res.filter((r) => MIGRATION_RE.test(r.path) || r.forces.some((f) => f.reason === "migrations")).map((r) => r.path);
34
+ const unsafe = hotfixMarkers.unsafe === true || Object.values(texts).some((t) => UNSAFE_MARKER.test(t));
35
+ const safePaths = new Set([...(hotfixMarkers.safe ?? []), ...Object.keys(texts).filter((k) => SAFE_MARKER.test(texts[k]))]);
36
+ const safe = migFiles.length > 0 && migFiles.every((p) => safePaths.has(p));
37
+ const migrations = unsafe || (migFiles.length && !safe) ? "breaking" : migFiles.length ? "additive" : "none";
38
+ return { units, shared_modules: shared, migrations, contract: res.some((r) => r.contracts.length > 0), paths: res.map((r) => r.path), diff_lines: diffLines };
39
+ }
40
+
41
+ /** First matching rule wins: {risk, rule: <index|"default">, forces?}. */
42
+ export function riskOf(policy, facts) {
43
+ const rules = policy?.risk?.rules?.length ? policy.risk.rules : DEFAULT_RISK_RULES;
44
+ for (let i = 0; i < rules.length; i++) {
45
+ const w = rules[i].when ?? {};
46
+ const hit = (w.migration === undefined || (w.migration === (facts.migrations !== "none")))
47
+ && (w.paths === undefined || facts.paths.some((p) => matchesAny(w.paths, p)))
48
+ && (w.contract === undefined || w.contract === facts.contract)
49
+ && (w.rolled_units_gt === undefined || facts.units.length > w.rolled_units_gt)
50
+ && (w.diff_lines_gt === undefined || facts.diff_lines > w.diff_lines_gt);
51
+ if (hit) return { risk: rules[i].risk, rule: i + 1, ...(rules[i].forces ? { forces: rules[i].forces } : {}), ...(rules[i].requires ? { requires: rules[i].requires } : {}) };
52
+ }
53
+ return { risk: "low", rule: "default" };
54
+ }
55
+
56
+ /**
57
+ * `live` needs (a) a cited file:line that exists on the live sha (git cat-file + the line) and (b) a repro `{command, red_on_live, green_after}`
58
+ * whose command, run on a detached checkout of the live sha via `run(command, liveSha)` (exit code or `{exit}`), fails. `green_after` may be null until the fix lands.
59
+ * `staging-only` and `unknown` need no live evidence.
60
+ * @param {{git: (args: string[]) => Promise<string>|string, liveSha?: string|null, run?: (command: string, sha: string) => Promise<number|{exit:number}>|number|{exit:number}}} io
61
+ */
62
+ export async function verifyExistsIn(rec, { git, liveSha, run }) {
63
+ if (rec.exists_in !== "live") return { ...rec };
64
+ const ev = rec.exists_in_evidence ?? {};
65
+ const repro = ev.repro ?? {};
66
+ const m = /^([^\s:]+):(\d+)$/.exec(String(ev.cite ?? "").trim());
67
+ let ok = false;
68
+ if (m && liveSha && typeof repro.command === "string" && repro.command.trim() && typeof run === "function") {
69
+ try {
70
+ await git(["cat-file", "-e", `${liveSha}:${m[1]}`]);
71
+ const lines = String(await git(["show", `${liveSha}:${m[1]}`])).split("\n").length;
72
+ if (Number(m[2]) >= 1 && Number(m[2]) <= lines) {
73
+ const res = await run(repro.command, liveSha);
74
+ const exit = typeof res === "number" ? res : res?.exit;
75
+ ok = typeof exit === "number" && exit !== 0; // red: the repro fails on the live sha
76
+ }
77
+ } catch { ok = false; }
78
+ }
79
+ return ok ? { ...rec, exists_in_evidence: { ...ev, repro: { ...repro, red_on_live: true, green_after: repro.green_after ?? null } } }
80
+ : { ...rec, exists_in: "unknown", lane_hint: "release", downgraded: "exists_in live lacked a verifiable file:line on the live sha and a repro that fails (red) there" };
81
+ }
82
+
83
+ /** Text-only records are capped at `classify.text_only_cap` (default 0.5) and never claim `migrations: none`. */
84
+ export function applySourceRules(rec, policy) {
85
+ const cap = policy?.classify?.text_only_cap ?? 0.5;
86
+ const out = { ...rec };
87
+ if (out.source === "text-only") {
88
+ out.confidence = Math.min(Number(out.confidence ?? cap), cap);
89
+ if (out.migrations === "none") out.migrations = "unknown";
90
+ }
91
+ return out;
92
+ }
93
+
94
+ export function validateClassification(rec) {
95
+ const p = [];
96
+ if (!rec || typeof rec !== "object" || Array.isArray(rec)) return ["classification must be an object"];
97
+ const en = (k, vals, opt) => { if (rec[k] === undefined && opt) return; if (!vals.includes(rec[k])) p.push(`${k}: must be one of ${vals.join("|")}`); };
98
+ const strs = (k) => { if (rec[k] !== undefined && !(Array.isArray(rec[k]) && rec[k].every((x) => typeof x === "string"))) p.push(`${k}: must be an array of strings`); };
99
+ en("type", ReleaseClassifyTYPES); en("severity", SEVERITIES); en("exists_in", EXISTS_IN);
100
+ en("flag", FLAGS, true); en("source", SOURCES, true); en("risk", ["low", "medium", "high"], true);
101
+ en("migrations", ["none", "additive", "breaking", "unknown"], true); en("lane_hint", ["none", "release", "hotfix", "train", "integration"], true);
102
+ strs("units"); strs("shared_modules"); strs("deps");
103
+ if (rec.ready !== undefined && typeof rec.ready !== "boolean") p.push("ready: must be a boolean");
104
+ if (rec.epic !== undefined && rec.epic !== null && typeof rec.epic !== "string" && !Number.isInteger(rec.epic)) p.push("epic: must be a string, integer or null");
105
+ if (rec.confidence !== undefined && !(typeof rec.confidence === "number" && rec.confidence >= 0 && rec.confidence <= 1)) p.push("confidence: must be a number in 0..1");
106
+ const ev = rec.exists_in_evidence;
107
+ if (ev !== undefined) {
108
+ if (!ev || typeof ev !== "object") p.push("exists_in_evidence: must be an object");
109
+ else {
110
+ if (ev.cite !== undefined && typeof ev.cite !== "string") p.push("exists_in_evidence.cite: must be a string file:line");
111
+ const r = ev.repro;
112
+ if (r !== undefined && r !== null) {
113
+ if (typeof r !== "object" || typeof r.command !== "string") p.push("exists_in_evidence.repro.command: must be a string");
114
+ else {
115
+ if (typeof r.red_on_live !== "boolean") p.push("exists_in_evidence.repro.red_on_live: must be a boolean");
116
+ if (r.green_after !== null && r.green_after !== undefined && typeof r.green_after !== "boolean") p.push("exists_in_evidence.repro.green_after: must be a boolean or null");
117
+ }
118
+ }
119
+ }
120
+ }
121
+ if (rec.severity === "P0" && !(rec.severity_evidence ?? rec.production_evidence)) p.push("severity: P0 needs production-impacting evidence cited");
122
+ return p;
123
+ }
124
+
125
+ /** Overwrites every derived field; the LLM's units, migrations and risk are never kept. */
126
+ export function buildClassifyRecord(llm, policy, facts, { text = false } = {}) {
127
+ const r = riskOf(policy, facts);
128
+ const { units: _u, shared_modules: _s, migrations: _m, risk: _r, ...kept } = llm ?? {};
129
+ const rec = { ...kept, units: facts.units, shared_modules: facts.shared_modules, migrations: facts.migrations, contract_changed: facts.contract, risk: r.risk, risk_rule: r.rule,
130
+ source: text ? "text-only" : (llm?.source === "human" ? "human" : "path-derived") };
131
+ if (rec.migrations !== "none" || r.forces === "release") rec.lane_hint = "release";
132
+ else rec.lane_hint ??= "none";
133
+ return applySourceRules(rec, policy);
134
+ }
135
+
136
+ const lab = (ns, v) => `${ns}:${v}`;
137
+ export function labelsOf(rec) {
138
+ const risk = { low: "low", medium: "med", high: "high" }[rec.risk];
139
+ return [lab("type", rec.type), lab("priority", rec.severity), lab("where", rec.exists_in), ...(rec.units ?? []).map((u) => lab("unit", u)), lab("mig", rec.migrations), risk && lab("risk", risk),
140
+ rec.lane_hint && rec.lane_hint !== "none" ? lab("lane", rec.lane_hint) : null].filter((l) => l && !l.endsWith(":undefined"));
141
+ }
142
+
143
+ export const renderClassify = (rec) => `**Classification** (engine-derived paths and risk)\n\n\`\`\`json\n${JSON.stringify(rec, null, 1)}\n\`\`\``;
@@ -0,0 +1,130 @@
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 { execFileSync } from "node:child_process";
5
+ import { writeFileSync, rmSync } from "node:fs";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { join } from "node:path";
8
+ import assert from "node:assert/strict";
9
+ import { DEFAULT_RISK_RULES, deriveFacts, riskOf, verifyExistsIn, buildClassifyRecord, applySourceRules, validateClassification, labelsOf, renderClassify } from "./release-classify.mjs";
10
+
11
+ const policy = {
12
+ units: { api: { paths: ["services/api/**"] }, web: { paths: ["web/**"] } },
13
+ couplings: [{ paths: ["shared/**"], affects: ["api", "web"] }],
14
+ contracts: [{ producer: "api", consumers: ["web"], paths: ["services/api/routers/**"] }],
15
+ };
16
+
17
+ describe("deriveFacts", () => {
18
+ it("units come from the map, shared modules and contract from paths", () => {
19
+ const f = deriveFacts(policy, ["services/api/a.py", "shared/detection/x.py", "services/api/routers/r.py"]);
20
+ assert.deepEqual(f.units.sort(), ["api", "web"]);
21
+ assert.deepEqual(f.shared_modules, ["shared/detection"]);
22
+ assert.equal(f.contract, true);
23
+ assert.equal(f.migrations, "none");
24
+ });
25
+ it("a migration path is breaking unless marked HOTFIX-SAFE; HOTFIX-UNSAFE always breaks", () => {
26
+ const p = "infra/migrations/001.sql";
27
+ assert.equal(deriveFacts(policy, [p]).migrations, "breaking");
28
+ assert.equal(deriveFacts(policy, [p], { texts: { [p]: "-- HOTFIX-SAFE\nalter" } }).migrations, "additive");
29
+ assert.equal(deriveFacts(policy, [p, "a.py"], { texts: { [p]: "-- HOTFIX-SAFE", "a.py": "# HOTFIX-UNSAFE" } }).migrations, "breaking");
30
+ });
31
+ });
32
+
33
+ describe("riskOf", () => {
34
+ it("first matching rule wins (migration high before contract medium)", () => {
35
+ const f = deriveFacts(policy, ["infra/migrations/1.sql", "services/api/routers/r.py"]);
36
+ assert.deepEqual(riskOf(policy, f), { risk: "high", rule: 1, forces: "release" });
37
+ });
38
+ it("contract is medium, a plain one-unit diff is low, a large diff is medium", () => {
39
+ assert.equal(riskOf(policy, deriveFacts(policy, ["services/api/routers/r.py"])).risk, "medium");
40
+ assert.equal(riskOf(policy, deriveFacts(policy, ["web/a.js"])).risk, "low");
41
+ assert.equal(riskOf(policy, deriveFacts(policy, ["web/a.js"], { diffLines: 401 })).risk, "medium");
42
+ });
43
+ it("policy risk.rules replace the defaults and high_paths globs match", () => {
44
+ const p = { ...policy, risk: { rules: [{ when: { paths: ["web/billing/**"] }, risk: "high" }] } };
45
+ assert.equal(riskOf(p, deriveFacts(p, ["web/billing/x.js"])).risk, "high");
46
+ assert.equal(riskOf(p, deriveFacts(p, ["web/other.js"])).risk, "low");
47
+ });
48
+ });
49
+
50
+ describe("verifyExistsIn", () => {
51
+ const rec = { exists_in: "live", exists_in_evidence: { cite: "a.py:2", repro: { command: "pytest x", red_on_live: true, green_after: true } } };
52
+ const red = () => 1;
53
+ const git = async (a) => { if (a[0] === "cat-file") { if (a[2].endsWith("missing.py")) throw new Error("nope"); return ""; } return "l1\nl2\nl3"; };
54
+ it("keeps live when the line exists on the live sha and the repro is red then green", async () => {
55
+ assert.equal((await verifyExistsIn(rec, { git, liveSha: "abc", run: red })).exists_in, "live");
56
+ });
57
+ it("downgrades to unknown and release otherwise", async () => {
58
+ for (const r of [{ ...rec, exists_in_evidence: { cite: "missing.py:2", repro: rec.exists_in_evidence.repro } }, { ...rec, exists_in_evidence: { cite: "a.py:9", repro: rec.exists_in_evidence.repro } }, { ...rec, exists_in_evidence: { cite: "a.py:2" } }]) {
59
+ const o = await verifyExistsIn(r, { git, liveSha: "abc", run: red });
60
+ assert.equal(o.exists_in, "unknown"); assert.equal(o.lane_hint, "release");
61
+ }
62
+ assert.equal((await verifyExistsIn(rec, { git, liveSha: null, run: red })).exists_in, "unknown");
63
+ });
64
+ });
65
+
66
+ describe("verifyExistsIn repro and defaults (#5557)", () => {
67
+ const git = async (a) => (a[0] === "cat-file" ? "" : "l1\nl2\nl3");
68
+ const mk = (green) => ({ exists_in: "live", exists_in_evidence: { cite: "a.py:2", repro: { command: "false", red_on_live: true, green_after: green } } });
69
+ it("a repro that passes (not red) on the live sha downgrades to unknown + release", async () => {
70
+ const o = await verifyExistsIn(mk(null), { git, liveSha: "abc", run: async () => ({ exit: 0 }) });
71
+ assert.equal(o.exists_in, "unknown"); assert.equal(o.lane_hint, "release");
72
+ });
73
+ it("green_after null is accepted while the repro is red", async () => {
74
+ const o = await verifyExistsIn(mk(null), { git, liveSha: "abc", run: async () => ({ exit: 2 }) });
75
+ assert.equal(o.exists_in, "live"); assert.equal(o.exists_in_evidence.repro.green_after, null);
76
+ });
77
+ it("without a run callback live cannot be verified; staging-only needs no evidence", async () => {
78
+ assert.equal((await verifyExistsIn(mk(null), { git, liveSha: "abc" })).exists_in, "unknown");
79
+ assert.equal((await verifyExistsIn({ exists_in: "staging-only" }, { git })).exists_in, "staging-only");
80
+ });
81
+ it("round trip: a record in the prompt shape survives as live in a fixture git repo", async () => {
82
+ const d = tmpDir("classify-rt-");
83
+ try {
84
+ const g = (...a) => execFileSync("git", ["-C", d, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" });
85
+ g("init", "-q"); writeFileSync(join(d, "a.py"), "x = 1\ny = 2\n"); g("add", "."); g("commit", "-qm", "c");
86
+ const sha = g("rev-parse", "HEAD").trim();
87
+ const rec = JSON.parse(JSON.stringify({ type: "bug", severity: "P2", exists_in: "live", flag: "none", exists_in_evidence: { cite: "a.py:2", repro: { command: "exit 1", red_on_live: true, green_after: null } } }));
88
+ const o = await verifyExistsIn(rec, { git: async (a) => g(...a), liveSha: sha, run: async (cmd) => { try { execFileSync("sh", ["-c", cmd], { cwd: d }); return 0; } catch (e) { return e.status ?? 1; } } });
89
+ assert.equal(o.exists_in, "live");
90
+ } finally { rmSync(d, { recursive: true, force: true }); }
91
+ });
92
+ it("six built-in defaults apply in order when the policy has no rules", () => {
93
+ assert.equal(DEFAULT_RISK_RULES.length, 6);
94
+ const r = (files, o) => riskOf({}, deriveFacts(policy, files, o));
95
+ assert.deepEqual(r(["infra/migrations/1.sql"]), { risk: "high", rule: 1, forces: "release" });
96
+ assert.equal(r(["shared/billing_x.py"]).rule, 2);
97
+ assert.equal(r(["shared/detection/x.py"]).rule, 3);
98
+ assert.equal(r(["services/api/routers/r.py"]).rule, 4);
99
+ assert.equal(r(["services/api/a.py", "web/a.js"]).rule, 5);
100
+ assert.equal(r(["web/a.js"], { diffLines: 500 }).rule, 6);
101
+ assert.deepEqual(r(["web/a.js"]), { risk: "low", rule: "default" });
102
+ });
103
+ it("validateClassification checks field types and hotfixMarkers drive migrations", () => {
104
+ assert.ok(validateClassification({ type: "bug", severity: "P2", exists_in: "unknown", units: "api", ready: "yes", confidence: 2, deps: [1], source: "x", exists_in_evidence: { repro: { command: "c", red_on_live: "y" } } }).length >= 6);
105
+ assert.deepEqual(validateClassification({ type: "bug", severity: "P2", exists_in: "live", exists_in_evidence: { cite: "a:1", repro: { command: "c", red_on_live: true, green_after: null } }, epic: null }), []);
106
+ assert.equal(deriveFacts(policy, ["a.py"], { hotfixMarkers: { unsafe: true } }).migrations, "breaking");
107
+ assert.equal(deriveFacts(policy, ["infra/migrations/1.sql"], { hotfixMarkers: { safe: ["infra/migrations/1.sql"] } }).migrations, "additive");
108
+ });
109
+ });
110
+
111
+ describe("text-only and record building", () => {
112
+ it("text-only caps confidence at 0.5 and never trusts migrations none", () => {
113
+ const o = applySourceRules({ source: "text-only", confidence: 0.9, migrations: "none" }, policy);
114
+ assert.equal(o.confidence, 0.5); assert.notEqual(o.migrations, "none");
115
+ });
116
+ it("buildClassifyRecord ignores LLM-typed units and migrations and forces release on a migration", () => {
117
+ const f = deriveFacts(policy, ["infra/migrations/1.sql"]);
118
+ const r = buildClassifyRecord({ type: "bug", severity: "P2", exists_in: "unknown", units: ["web"], migrations: "none", risk: "low" }, policy, f);
119
+ assert.deepEqual(r.units, []); assert.equal(r.migrations, "breaking"); assert.equal(r.risk, "high"); assert.equal(r.lane_hint, "release");
120
+ });
121
+ it("validates enums, builds namespaced labels and a comment body", () => {
122
+ assert.ok(validateClassification({ type: "x", severity: "P9", exists_in: "live" }).length >= 2);
123
+ assert.deepEqual(validateClassification({ type: "bug", severity: "P2", exists_in: "unknown" }), []);
124
+ const r = buildClassifyRecord({ type: "bug", severity: "P2", exists_in: "unknown" }, policy, deriveFacts(policy, ["web/a.js"]));
125
+ assert.deepEqual(labelsOf(r), ["type:bug", "priority:P2", "where:unknown", "unit:web", "mig:none", "risk:low"]);
126
+ assert.match(renderClassify(r), /"units"/);
127
+ assert.ok(labelsOf({ ...r, lane_hint: "release" }).includes("lane:release"), "lane_hint adds a lane:* label");
128
+ assert.ok(!labelsOf({ ...r, lane_hint: "none" }).some((l) => l.startsWith("lane:")));
129
+ });
130
+ });
@@ -0,0 +1,163 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Release conductor (#5564, epic #5549 Phase 3, I17/I22/I24, R6): `forgedock release recover <id>`, the host-less recovery path run by
5
+ * the version-pinned `forge-conductor.yml` workflow. With a stale lease (`CONDUCTOR_TTL_S`) it takes the lease (epoch + 1) and
6
+ * continues the deploy from the last `done` (deployStep reconciles every unfinished intent); with a fresh lease it does nothing.
7
+ * It acts only when the ledger says merged, for allowlisted actors (`trust.actors`), fenced by epoch, and never while HELD.
8
+ * `CAPABILITIES` is the matrix of design 2.6: GitHub-only actions run, host-only ones wait (listed by `release status`), and
9
+ * plan/build/review/merge/patch are refused. Safe end state: roll back to the recorded target, else hold and file `needs-agent`.
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { dirname, join } from "node:path";
13
+ import { readActive, readLedger, writeRelease } from "./release-ledger.mjs";
14
+ import { holdCheck, runControl } from "./release-control.mjs";
15
+ import { deployStep } from "./release-deploy.mjs";
16
+ import { runRollback, takeFence } from "./release-rollback.mjs";
17
+ import { riskClass } from "./release-verify.mjs";
18
+
19
+ export const CONDUCTOR_TTL_S = 900;
20
+ export const CONDUCTOR_WORKFLOW_PATH = ".github/workflows/forge-conductor.yml";
21
+ export const CONDUCTOR_MARKER = "FORGE:CONDUCTOR";
22
+ const TEMPLATE = new URL("../../templates/github-actions/forge-conductor.yml", import.meta.url);
23
+
24
+ /** Design 2.6: where each action class may run. `needs` is a policy key the action requires. */
25
+ export const CAPABILITIES = {
26
+ rerun: { where: "github" },
27
+ redispatch: { where: "github" },
28
+ observe: { where: "github" },
29
+ livecheck: { where: "github" },
30
+ smoke: { where: "github" },
31
+ rollback_full: { where: "github", needs: "rollback.full_workflow" },
32
+ sli_soak: { where: "host" },
33
+ purge: { where: "host" },
34
+ };
35
+ /** Never run by the conductor, whatever the matrix says (patching is host-only work). */
36
+ export const REFUSED = ["plan", "build", "review", "merge", "patch"];
37
+
38
+ /** @returns {{run: true} | {host: true, why} | {refused: true, why}} */
39
+ export function capability(action, policy = {}) {
40
+ if (REFUSED.includes(action)) return { refused: true, why: `the conductor never does ${action}` };
41
+ const c = CAPABILITIES[action];
42
+ if (!c) return { refused: true, why: `unknown action ${action}` };
43
+ if (c.where === "host") return { host: true, why: `${action} is host-only; waits for a host driver` };
44
+ if (c.needs && !c.needs.split(".").reduce((o, k) => o?.[k], policy)) return { host: true, why: `${action} needs ${c.needs}, which is not configured` };
45
+ return { run: true };
46
+ }
47
+
48
+ /** `controls.conductor` of the policy: {enabled, watchdogCron, workflows}. */
49
+ export function conductorConfig(policy) {
50
+ const c = policy?.controls?.conductor ?? {};
51
+ return { enabled: c.enabled === true, watchdogCron: typeof c.watchdog_cron === "string" ? c.watchdog_cron : "0 */6 * * *", workflows: Array.isArray(c.workflows) && c.workflows.length ? c.workflows : ["Deploy"] };
52
+ }
53
+
54
+ /** Bootstrap guard (R10): a reason to refuse starting a managed release, or null. */
55
+ export function conductorGuard({ io, policy, def }) {
56
+ if (!conductorConfig(policy).enabled) return null;
57
+ try { io.git(["show", `origin/${def}:${CONDUCTOR_WORKFLOW_PATH}`]); return null; } catch { return `controls.conductor is enabled but ${CONDUCTOR_WORKFLOW_PATH} is absent from origin/${def}; run \`forgedock release init --conductor\` and merge it first`; }
58
+ }
59
+
60
+ /** The template with the exact forgedock version, the watchdog cron and the deploy workflow names filled in. */
61
+ export function renderConductor({ version, cron = "0 */6 * * *", workflows = ["Deploy"], template = readFileSync(TEMPLATE, "utf8") }) {
62
+ return template.replaceAll("__FORGEDOCK_VERSION__", version).replaceAll("__WATCHDOG_CRON__", cron).replaceAll("__DEPLOY_WORKFLOWS__", JSON.stringify(workflows));
63
+ }
64
+
65
+ /** `release init --conductor`: write the pinned workflow into the repo (never overwrites). @returns exit code */
66
+ export function installConductor({ io, cwd, policy }) {
67
+ const file = join(cwd, CONDUCTOR_WORKFLOW_PATH);
68
+ if (existsSync(file)) { io.print(`release init: ${CONDUCTOR_WORKFLOW_PATH} exists; not overwriting`); return 1; }
69
+ const { version } = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
70
+ const c = conductorConfig(policy);
71
+ mkdirSync(dirname(file), { recursive: true });
72
+ writeFileSync(file, renderConductor({ version, cron: c.watchdogCron, workflows: c.workflows }));
73
+ io.print(`release init: wrote ${CONDUCTOR_WORKFLOW_PATH} (forgedock@${version}); merge it to the default branch, then set controls.conductor.enabled`);
74
+ return 0;
75
+ }
76
+
77
+ /** Stale = the lease heartbeat comment (else `expires`) is older than `ttlS`. */
78
+ async function leaseStale(lctx, lease, ttlS, now) {
79
+ if (lease.commentId) {
80
+ try { const c = await lctx.io.api("GET", `repos/${lctx.repo}/issues/comments/${lease.commentId}`); return now - Date.parse(c.updated_at) >= ttlS * 1000; } catch (e) { if (!/404|not found/i.test(String(e?.message ?? e))) throw e; }
81
+ }
82
+ return typeof lease.expires === "number" ? now >= lease.expires : true;
83
+ }
84
+
85
+ const mergedSha = (s) => s?.deploy?.merge ?? s?.steps?.["post-merge"]?.result?.merge ?? null;
86
+
87
+ /** One needs-agent issue per release (idempotent by marker). */
88
+ async function fileNeedsAgent(ctx, why) {
89
+ const { io, repo, state } = ctx, marker = `${CONDUCTOR_MARKER} ${state.id}`;
90
+ const found = JSON.parse(String(await io.gh(["issue", "list", "--repo", repo, "--state", "open", "--search", `"${marker}" in:body`, "--json", "number,body", "--limit", "20"])) || "[]");
91
+ const hit = found.find((i) => String(i.body ?? "").includes(marker));
92
+ if (hit) return hit.number;
93
+ const url = String(await io.gh(["issue", "create", "--repo", repo, "--label", "needs-agent", "--title", `release ${state.id}: conductor stopped at last healthy state`, "--body", `${why}\n\nA host driver must finish this release (\`forgedock release --resume ${state.id}\`).\n\n<!-- ${marker} -->`])).trim();
94
+ return Number(/\/issues\/(\d+)/.exec(url)?.[1]) || url;
95
+ }
96
+
97
+ /** Safe end state: roll back to the recorded target when the rollback workflow is configured (unless the live record never moved), else hold and file needs-agent. */
98
+ async function safeEnd(ctx, why, deps, { rollback = true } = {}) {
99
+ const rb = capability("rollback_full", ctx.policy);
100
+ if (rollback && rb.run) {
101
+ const r = await deps.rollback(ctx, { reason: why, to: "full" });
102
+ return { ended: r.ok ? "rolled-back" : "rollback-stopped", why, rollback: r };
103
+ }
104
+ const h = await runControl("hold", [ctx.state.id, "--reason", `conductor: ${why}`], { io: ctx.io, repo: ctx.repo, policy: ctx.policy, actor: ctx.actor, host: ctx.host, now: ctx.io.now?.() });
105
+ const issue = await fileNeedsAgent(ctx, why);
106
+ return { ended: "held", why, hold: h.ok, issue, ...(rb.run ? {} : { note: rb.why }) };
107
+ }
108
+
109
+ /**
110
+ * Take over a stale lease for release `id` and continue it with GitHub-only actions.
111
+ * `ctx`: {io, repo, id, policy, def, actor, host}. `deps` (tests): {deploy, rollback, takeFence}.
112
+ * @returns {Promise<{noop: string} | {refused: string} | {live: true} | {ended: string, why: string}>}
113
+ */
114
+ export async function recover(ctx, deps = {}) {
115
+ const { io, repo, id, policy = {} } = ctx;
116
+ const d = { deploy: deployStep, rollback: runRollback, takeFence, ...deps };
117
+ const lctx = { io, repo, credential: "driver" };
118
+ let active;
119
+ try { active = await readActive(lctx); } catch (e) { return { refused: `cannot read _active (${String(e?.message ?? e)}); acting on nothing (I5)` }; }
120
+ const lease = active.lease;
121
+ if (!lease || lease.release !== id) return { noop: `no active lease for ${id}` };
122
+ if (!(await leaseStale(lctx, lease, CONDUCTOR_TTL_S, io.now()))) return { noop: `lease of ${lease.holder} (epoch ${lease.epoch}) is fresh` };
123
+ if (!ctx.actor || !(policy.trust?.actors ?? []).includes(ctx.actor)) return { refused: `actor ${ctx.actor ?? "unknown"} is not in trust.actors` };
124
+ let why = null;
125
+ try { why = await holdCheck(lctx, id); } catch (e) { why = `cannot read _active (${String(e?.message ?? e)})`; }
126
+ if (why) return { refused: why };
127
+ const led = await readLedger(lctx, id);
128
+ if (!led || led.rejected) return { refused: led ? `ledger rejected: ${led.rejected}` : `no ledger for ${id}` };
129
+ const state = led.state;
130
+ if (!mergedSha(state)) return { refused: "the ledger does not say the release is merged; the conductor only recovers deploys" };
131
+ if (state.deploy?.phase === "LIVE") return { noop: "release is already LIVE" };
132
+
133
+ let head = led.head, chain = Promise.resolve();
134
+ const write = async () => { const r = await writeRelease(lctx, id, state, head); if (!r.ok) throw new Error(`ledger write lost the race for ${id}`); head = r.sha; };
135
+ const lane = policy.lanes?.[state.lane], pipeline = lane?.pipeline ?? "full";
136
+ const verify = policy.verify ? { ...policy.verify, slis: [] } : undefined; // SLI soak is host-only (2.6): the other layers still run
137
+ const c = { io, repo, def: ctx.def, state, policy, actor: ctx.actor, host: ctx.host, save: () => { chain = chain.then(write); }, config: { deploy: policy.deploy, deployPipeline: pipeline, policy, verify, verifyRisk: riskClass(state.lane, pipeline), verifySoak: lane?.soak_min } };
138
+ const f = await d.takeFence(c, `conductor-${ctx.host ?? "gh"}`, CONDUCTOR_TTL_S);
139
+ if (f.refused) return { refused: f.refused };
140
+ c.fence = f.fence;
141
+ const epoch = f.fence?.lease?.epoch, pending = (state.intents ?? []).filter((i) => !i.done).length;
142
+ state.conductorWaiting = (policy.verify?.slis ?? []).length ? ["sli_soak (host-only)"] : [];
143
+ let r;
144
+ try { r = await d.deploy(c); } catch (e) { r = { blocked: true, reason: `conductor step failed: ${String(e?.message ?? e).split("\n")[0]}` }; }
145
+ c.save(); await chain;
146
+ if (r.live || r.skipped) { io.print?.(`release ${id}: conductor finished the deploy (epoch ${epoch}, ${pending} unfinished intent(s) replayed)`); return { live: true, epoch, waiting: state.conductorWaiting }; }
147
+ const e = await safeEnd(c, r.reason ?? r.why ?? "deploy did not complete", d, { rollback: !r.hold });
148
+ return { ...e, epoch };
149
+ }
150
+
151
+ /** `forgedock release recover <id> [--repo R]`; @returns 0 done, nothing to do or rolled back, 1 refused, 3 ended in hold or a stopped rollback. */
152
+ export async function recoverFromCli(argv, { io, policy, def, actor, host }) {
153
+ const flagOf = (f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
154
+ const id = argv.find((a, i) => !a.startsWith("--") && argv[i - 1] !== "--repo");
155
+ if (!id) { io.print("release recover: release id required"); return 1; }
156
+ const repo = flagOf("--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
157
+ const r = await recover({ io, repo, id, policy, def, actor, host });
158
+ if (r.noop) { io.print(`release recover ${id}: nothing to do (${r.noop})`); return 0; }
159
+ if (r.refused) { io.print(`release recover ${id}: refused: ${r.refused}`); return 1; }
160
+ if (r.live) { io.print(`release recover ${id}: live`); return 0; }
161
+ io.print(`release recover ${id}: ${r.ended} (${r.why})`);
162
+ return r.ended === "rolled-back" ? 0 : 3;
163
+ }