forgedock 1.59.2 → 1.60.1

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 (97) 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 +19 -6
  7. package/bin/lean/conformance.test.mjs +37 -3
  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 +144 -21
  22. package/bin/lean/lean.test.mjs +180 -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 +67 -3
  32. package/bin/lean/preflight.test.mjs +37 -1
  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 +110 -0
  80. package/bin/lean/validate-catalog.test.mjs +55 -0
  81. package/bin/pool/agent.mjs +12 -1
  82. package/bin/pool/lane-tools.mjs +146 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/router.mjs +3 -1
  85. package/bin/pool/warm.mjs +14 -3
  86. package/docs/CONFIG.md +225 -1
  87. package/docs/ISSUE-WATCH.md +1 -0
  88. package/docs/design/visual-gate.md +10 -0
  89. package/docs/eval/adversarial-bench.md +1 -0
  90. package/package.json +1 -1
  91. package/pool/README.md +2 -0
  92. package/scripts/acceptance-red-green.sh +5 -2
  93. package/scripts/acceptance-red-green.test.sh +11 -0
  94. package/scripts/bench-adversarial.mjs +4 -0
  95. package/scripts/bench-lightlane.mjs +2 -1
  96. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  97. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -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
+ }
@@ -0,0 +1,194 @@
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 { readFileSync, existsSync } from "node:fs";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { join } from "node:path";
8
+ import { CAPABILITIES, REFUSED, capability, conductorConfig, conductorGuard, renderConductor, installConductor, recover, recoverFromCli, CONDUCTOR_WORKFLOW_PATH } from "./release-conductor.mjs";
9
+ import { fenced } from "./release-fence.mjs";
10
+ import { renderReleaseStatus } from "./release-status.mjs";
11
+ import { initFromCli } from "./release-config.mjs";
12
+
13
+ const ID = "r20260101-000000-1", NOW = 1_700_000_000_000;
14
+ const b64 = (o) => ({ content: Buffer.from(typeof o === "string" ? o : JSON.stringify(o)).toString("base64") });
15
+ const POLICY = { trust: { actors: ["github-actions[bot]"] }, deploy: { pipelines: { full: { workflow: "deploy.yml" } } }, rollback: { full_workflow: "rb.yml" } };
16
+
17
+ /** Fake GitHub: `_active`, the lease heartbeat comment and the release ledger; `commits` records every ledger write. */
18
+ function world({ active = {}, state, heartbeatAgeS = 3600, policy = POLICY } = {}) {
19
+ const w = { active: { epoch: 4, lease: { holder: "host-1", release: ID, epoch: 4, commentId: 9 }, ...active }, commits: [], gh: [], holds: [] };
20
+ w.state = state ?? { id: ID, repo: "o/r", lane: "release", steps: { "post-merge": { result: { merge: "bbbb2222" } } }, deploy: { phase: "DEPLOYING", merge: "bbbb2222", target: { sha: "aaaa1111" } } };
21
+ const io = {
22
+ now: () => NOW, print: () => {},
23
+ api: async (m, path, body) => {
24
+ if (/contents\/active\.json\?ref=_active$/.test(path)) return b64(w.active);
25
+ if (/controls\.jsonl/.test(path)) return b64("");
26
+ if (/issues\/comments\/9$/.test(path)) return { updated_at: new Date(NOW - heartbeatAgeS * 1000).toISOString() };
27
+ if (/git\/ref\/heads\//.test(path)) return { object: { sha: "h0" } };
28
+ if (/contents\/state\.json/.test(path)) return b64(w.state);
29
+ if (m === "POST" && /git\/trees$/.test(path)) { w.commits.push(JSON.parse(body.tree[0].content)); return { sha: "t1" }; }
30
+ if (/git\/commits\/h/.test(path)) return { tree: { sha: "t0" } };
31
+ if (m === "POST" && /git\/commits$/.test(path)) return { sha: "c1" };
32
+ if (m === "PATCH" && /git\/refs/.test(path)) return {};
33
+ if (m === "POST" && /issues\/\d+\/comments$/.test(path)) return { id: 1 };
34
+ throw new Error(`unrouted ${m} ${path}`);
35
+ },
36
+ gh: async (a) => { w.gh.push(a); if (a[0] === "issue" && a[1] === "list") return "[]"; if (a[0] === "issue" && a[1] === "create") return "https://github.com/o/r/issues/42"; return ""; },
37
+ };
38
+ const fence = { lctx: { io, repo: "o/r", credential: "driver" }, lease: { holder: "conductor-gh", release: ID, epoch: 5 }, record: async () => {}, now: () => "t" };
39
+ const takeFence = async () => ({ fence });
40
+ return { w, io, policy, takeFence, ctx: { io, repo: "o/r", id: ID, policy, def: "main", actor: "github-actions[bot]", host: "gh" } };
41
+ }
42
+
43
+ describe("capability matrix (#5564)", () => {
44
+ it("github-only actions run, host-only actions wait, plan/build/review/merge/patch are refused", () => {
45
+ for (const [a, c] of Object.entries(CAPABILITIES)) {
46
+ const r = capability(a, POLICY);
47
+ assert.ok(c.where === "host" ? r.host : r.run, a);
48
+ }
49
+ for (const a of REFUSED) assert.ok(capability(a, POLICY).refused, a);
50
+ assert.ok(capability("nonsense", POLICY).refused);
51
+ });
52
+ it("full rollback runs only when the rollback workflow is configured", () => {
53
+ assert.ok(capability("rollback_full", POLICY).run);
54
+ assert.match(capability("rollback_full", {}).why, /rollback\.full_workflow/);
55
+ });
56
+ });
57
+
58
+ describe("recover (#5564)", () => {
59
+ it("fresh lease: does nothing", async () => {
60
+ const { ctx, takeFence } = world({ heartbeatAgeS: 10 });
61
+ let took = 0;
62
+ const r = await recover(ctx, { takeFence: async (...a) => { took++; return takeFence(...a); } });
63
+ assert.match(r.noop, /fresh/);
64
+ assert.equal(took, 0);
65
+ });
66
+
67
+ it("I17: stale lease at DEPLOYING: takes epoch + 1, replays the deploy and finishes", async () => {
68
+ const { ctx, w, takeFence } = world();
69
+ const seen = [];
70
+ const r = await recover(ctx, { takeFence, deploy: async (c) => { seen.push(c.fence.lease.epoch); c.state.deploy.phase = "LIVE"; return { live: true }; } });
71
+ assert.equal(r.live, true);
72
+ assert.equal(r.epoch, 5);
73
+ assert.deepEqual(seen, [5]);
74
+ assert.equal(w.commits.at(-1).deploy.phase, "LIVE");
75
+ });
76
+
77
+ it("deploy blocked, rollback workflow configured: rolls back to the recorded target", async () => {
78
+ const { ctx, takeFence } = world();
79
+ let to = null;
80
+ const r = await recover(ctx, { takeFence, deploy: async () => ({ blocked: true, reason: "LIVE_CHECK failed" }), rollback: async (_c, a) => { to = a.to; return { ok: true, rung: "full" }; } });
81
+ assert.equal(r.ended, "rolled-back");
82
+ assert.equal(to, "full");
83
+ });
84
+
85
+ it("rollback workflow unconfigured: holds at last healthy and files needs-agent", async () => {
86
+ const { ctx, w, takeFence } = world({ policy: { ...POLICY, rollback: undefined } });
87
+ const r = await recover(ctx, { takeFence, deploy: async () => ({ blocked: true, reason: "LIVE_CHECK failed" }), rollback: async () => { throw new Error("must not roll back"); } });
88
+ assert.equal(r.ended, "held");
89
+ assert.ok(w.gh.some((a) => a[0] === "issue" && a[1] === "create" && a.includes("needs-agent")));
90
+ });
91
+
92
+ it("a hold from the deploy (freeze, deterministic failure) never rolls back blindly", async () => {
93
+ const { ctx, takeFence } = world();
94
+ const r = await recover(ctx, { takeFence, deploy: async () => ({ blocked: true, reason: "freeze set", hold: "x" }), rollback: async () => { throw new Error("must not roll back"); } });
95
+ assert.equal(r.ended, "held");
96
+ });
97
+
98
+ it("HELD: with a hold set the conductor performs no action", async () => {
99
+ const { ctx, w } = world({ active: { holds: { [ID]: { reason: "owner" } } } });
100
+ const r = await recover(ctx, { takeFence: async () => { throw new Error("must not take the lease"); }, deploy: async () => { throw new Error("must not act"); } });
101
+ assert.match(r.refused, /held/);
102
+ assert.equal(w.commits.length, 0);
103
+ });
104
+
105
+ it("refuses a non-allowlisted actor and an unmerged ledger", async () => {
106
+ const a = world();
107
+ assert.match((await recover({ ...a.ctx, actor: "mallory" }, { takeFence: a.takeFence })).refused, /trust\.actors/);
108
+ const b = world({ state: { id: ID, steps: {} } });
109
+ assert.match((await recover(b.ctx, { takeFence: b.takeFence })).refused, /merged/);
110
+ });
111
+
112
+ it("zombie: the old driver's epoch is refused after the takeover", async () => {
113
+ const { w, io } = world();
114
+ w.active = { epoch: 5, lease: { holder: "conductor-gh", epoch: 5 } };
115
+ let ran = 0;
116
+ const r = await fenced({ lctx: { io, repo: "o/r" }, lease: { holder: "host-1", epoch: 4 }, record: async () => {}, now: () => "t" }, { action: "dispatch", key: "k" }, async () => { ran++; });
117
+ assert.match(r.refused, /fenced/);
118
+ assert.equal(ran, 0);
119
+ });
120
+
121
+ it("host-only SLI soak is listed as waiting and shown by release status", async () => {
122
+ const { ctx, takeFence } = world({ policy: { ...POLICY, verify: { workflow: "v.yml", slis: [{ name: "p99" }] } } });
123
+ const seen = {};
124
+ const r = await recover(ctx, { takeFence, deploy: async (c) => { seen.slis = c.config.verify.slis; c.state.deploy.phase = "LIVE"; return { live: true }; } });
125
+ assert.deepEqual(r.waiting, ["sli_soak (host-only)"]);
126
+ assert.deepEqual(seen.slis, []);
127
+ const s = { id: ID, repo: "o/r", status: "running", source: "ledger", steps: [], waiting_host: r.waiting, next_actions: [] };
128
+ assert.match(renderReleaseStatus(s), /waiting on a host: sli_soak/);
129
+ });
130
+
131
+ it("recoverFromCli maps outcomes to exit codes", async () => {
132
+ const { w, io, policy } = world({ heartbeatAgeS: 5 });
133
+ const out = []; io.print = (l) => out.push(l);
134
+ assert.equal(await recoverFromCli([ID, "--repo", "o/r"], { io, policy, def: "main", actor: "github-actions[bot]" }), 0);
135
+ assert.match(out[0], /nothing to do/);
136
+ w.active.holds = { [ID]: {} };
137
+ w.active.lease.commentId = undefined; w.active.lease.expires = 0;
138
+ assert.equal(await recoverFromCli([ID, "--repo", "o/r"], { io, policy, def: "main", actor: "github-actions[bot]" }), 1);
139
+ });
140
+ });
141
+
142
+ describe("conductor template (#5564)", () => {
143
+ const tpl = readFileSync(new URL("../../templates/github-actions/forge-conductor.yml", import.meta.url), "utf8");
144
+ const scopes = JSON.parse(readFileSync(new URL("../../templates/github-actions/forge-conductor.scopes.json", import.meta.url), "utf8"));
145
+ const rendered = renderConductor({ version: "1.59.1", cron: "0 */6 * * *", workflows: ["Deploy"] });
146
+
147
+ it("pins an exact forgedock version", () => {
148
+ assert.match(tpl, /forgedock@__FORGEDOCK_VERSION__/);
149
+ assert.match(rendered, /forgedock@1\.59\.1 release recover/);
150
+ assert.doesNotMatch(rendered, /__[A-Z_]+__|@latest/);
151
+ });
152
+ it("has the four triggers and the configured watchdog cron", () => {
153
+ for (const t of ["workflow_run:", "deployment_status:", "workflow_dispatch:", "schedule:"]) assert.ok(rendered.includes(t), t);
154
+ assert.match(rendered, /types: \[completed\]/);
155
+ assert.match(rendered, /cron: '0 \*\/6 \* \* \*'/);
156
+ assert.match(renderConductor({ version: "1.0.0", cron: "0 3 * * *", workflows: ["A", "B"] }), /workflows: \["A","B"\]/);
157
+ });
158
+ it("the no-op path runs before any checkout step", () => {
159
+ const find = tpl.indexOf("_active"), checkout = tpl.indexOf("actions/checkout");
160
+ assert.ok(find > 0 && checkout > find);
161
+ assert.ok(tpl.indexOf("if: steps.active.outputs.release != ''") < checkout);
162
+ });
163
+ it("token scopes: the workflow permissions equal the scope file; no secrets, no merge, no PR write", () => {
164
+ const block = /permissions:\n((?: \w[\w-]*: \w+\n)+)/.exec(tpl)[1];
165
+ const perms = Object.fromEntries(block.trim().split("\n").map((l) => l.trim().split(": ")));
166
+ assert.deepEqual(perms, scopes.permissions);
167
+ assert.ok(!("pull-requests" in perms) && !("id-token" in perms));
168
+ assert.doesNotMatch(tpl, /secrets\.(?!GITHUB_TOKEN)|pr merge|gh api[^\n]*merge/);
169
+ });
170
+ });
171
+
172
+ describe("bootstrap guard and init --conductor (#5564)", () => {
173
+ const on = { controls: { conductor: { enabled: true } } };
174
+ it("refuses while the workflow is absent from the default branch", () => {
175
+ const gitHas = (has) => ({ git: (a) => { if (!has) throw new Error("not found"); assert.equal(a[1], `origin/main:${CONDUCTOR_WORKFLOW_PATH}`); return "x"; } });
176
+ assert.match(conductorGuard({ io: gitHas(false), policy: on, def: "main" }), /absent from origin\/main/);
177
+ assert.equal(conductorGuard({ io: gitHas(true), policy: on, def: "main" }), null);
178
+ assert.equal(conductorGuard({ io: gitHas(false), policy: {}, def: "main" }), null);
179
+ });
180
+ it("conductorConfig defaults the watchdog to every 6 h", () => {
181
+ assert.equal(conductorConfig({}).watchdogCron, "0 */6 * * *");
182
+ assert.equal(conductorConfig({ controls: { conductor: { watchdog_cron: "0 1 * * *" } } }).watchdogCron, "0 1 * * *");
183
+ });
184
+ it("init --conductor writes the pinned workflow, never overwrites, and plain init is unchanged", async () => {
185
+ const cwd = tmpDir("conductor-");
186
+ const out = [], io = { print: (l) => out.push(l) };
187
+ assert.equal(await initFromCli(["--conductor"], { io, cwd }), 0);
188
+ const { version } = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
189
+ assert.ok(readFileSync(join(cwd, CONDUCTOR_WORKFLOW_PATH), "utf8").includes(`forgedock@${version} release recover`));
190
+ assert.equal(installConductor({ io, cwd, policy: null }), 1);
191
+ assert.equal(initFromCli([], { io, cwd }), 1); // policy file now exists
192
+ assert.ok(existsSync(join(cwd, ".forge/release.yaml")));
193
+ });
194
+ });