forgedock 1.67.0 → 1.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/bin/config-schema.mjs +1 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +99 -12
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +17 -1
  6. package/bin/help-text.mjs +1 -0
  7. package/bin/lean/admission.mjs +21 -0
  8. package/bin/lean/admission.test.mjs +30 -0
  9. package/bin/lean/advisory.test.mjs +25 -10
  10. package/bin/lean/amendment-schema.mjs +3 -4
  11. package/bin/lean/attempts.mjs +34 -31
  12. package/bin/lean/attempts.test.mjs +33 -19
  13. package/bin/lean/basered.mjs +26 -0
  14. package/bin/lean/batch-health.mjs +17 -12
  15. package/bin/lean/batch-health.test.mjs +39 -11
  16. package/bin/lean/batch.test.mjs +51 -2
  17. package/bin/lean/ci-gate.mjs +2 -90
  18. package/bin/lean/ci-gate.test.mjs +1 -127
  19. package/bin/lean/ci-precheck.mjs +25 -8
  20. package/bin/lean/ci-precheck.test.mjs +24 -0
  21. package/bin/lean/clear-breaker.test.mjs +4 -3
  22. package/bin/lean/commentstate.mjs +10 -5
  23. package/bin/lean/commentstate.test.mjs +12 -1
  24. package/bin/lean/conformance.e2e.test.mjs +9 -6
  25. package/bin/lean/conformance.mjs +56 -196
  26. package/bin/lean/conformance.test.mjs +40 -376
  27. package/bin/lean/depcache.mjs +100 -10
  28. package/bin/lean/depcache.test.mjs +105 -0
  29. package/bin/lean/docsgate.mjs +0 -32
  30. package/bin/lean/docsgate.test.mjs +2 -23
  31. package/bin/lean/effects-cap.test.mjs +9 -1
  32. package/bin/lean/effects-killtree.test.mjs +35 -0
  33. package/bin/lean/effects.mjs +42 -24
  34. package/bin/lean/engine-readmit.test.mjs +35 -0
  35. package/bin/lean/envgap.mjs +93 -0
  36. package/bin/lean/envgap.test.mjs +53 -0
  37. package/bin/lean/execution.mjs +10 -4
  38. package/bin/lean/execution.test.mjs +12 -0
  39. package/bin/lean/failure-census.mjs +170 -0
  40. package/bin/lean/failure-census.test.mjs +59 -0
  41. package/bin/lean/guardgate.test.mjs +2 -3
  42. package/bin/lean/heavy.mjs +33 -4
  43. package/bin/lean/heavy.test.mjs +38 -6
  44. package/bin/lean/hotarea.mjs +0 -36
  45. package/bin/lean/hotarea.test.mjs +1 -22
  46. package/bin/lean/issuewatch-verify.mjs +19 -4
  47. package/bin/lean/issuewatch.mjs +21 -4
  48. package/bin/lean/issuewatch.test.mjs +48 -1
  49. package/bin/lean/lane-audit-gap.mjs +66 -0
  50. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  51. package/bin/lean/lane-audit-llm.mjs +5 -0
  52. package/bin/lean/lane-audit-query.mjs +47 -0
  53. package/bin/lean/lane-audit-query.test.mjs +44 -0
  54. package/bin/lean/lane-audit-signatures.mjs +33 -0
  55. package/bin/lean/lane-audit.mjs +110 -0
  56. package/bin/lean/lane-audit.test.mjs +97 -0
  57. package/bin/lean/lane-recovery.test.mjs +33 -0
  58. package/bin/lean/lanecheck.mjs +5 -3
  59. package/bin/lean/lanecheck.test.mjs +6 -0
  60. package/bin/lean/lean.mjs +206 -148
  61. package/bin/lean/lean.test.mjs +406 -190
  62. package/bin/lean/limits.mjs +17 -0
  63. package/bin/lean/limits.test.mjs +15 -1
  64. package/bin/lean/live-execution.mjs +21 -2
  65. package/bin/lean/live-execution.test.mjs +39 -0
  66. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  67. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  68. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  69. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  70. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  71. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  72. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  73. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  74. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  75. package/bin/lean/orchestrate.mjs +188 -33
  76. package/bin/lean/postdeploy-check.test.mjs +1 -3
  77. package/bin/lean/precheck.mjs +20 -0
  78. package/bin/lean/preflight.mjs +100 -11
  79. package/bin/lean/preflight.test.mjs +44 -4
  80. package/bin/lean/prompts.mjs +10 -21
  81. package/bin/lean/recurrence.mjs +6 -148
  82. package/bin/lean/recurrence.test.mjs +11 -147
  83. package/bin/lean/release-flakes.mjs +14 -2
  84. package/bin/lean/release-flakes.test.mjs +17 -1
  85. package/bin/lean/release-ledger.mjs +19 -1
  86. package/bin/lean/release-ledger.test.mjs +23 -0
  87. package/bin/lean/release-preflight.mjs +28 -0
  88. package/bin/lean/release-preflight.test.mjs +42 -1
  89. package/bin/lean/release-review.mjs +40 -5
  90. package/bin/lean/release-review.test.mjs +43 -2
  91. package/bin/lean/release.mjs +43 -14
  92. package/bin/lean/release.test.mjs +32 -0
  93. package/bin/lean/retry.mjs +1 -1
  94. package/bin/lean/retry.test.mjs +6 -1
  95. package/bin/lean/rotator.mjs +9 -0
  96. package/bin/lean/rotator.test.mjs +11 -1
  97. package/bin/lean/sandbox-remote.mjs +16 -9
  98. package/bin/lean/schedd.mjs +11 -6
  99. package/bin/lean/schedd.test.mjs +65 -5
  100. package/bin/lean/selfreview.mjs +1 -1
  101. package/bin/lean/statuscomment.mjs +4 -1
  102. package/bin/lean/validate-catalog.mjs +108 -0
  103. package/bin/lean/validate-catalog.test.mjs +46 -1
  104. package/bin/lean/verify.mjs +1 -1
  105. package/bin/pool/affinity.test.mjs +91 -0
  106. package/bin/pool/agent.mjs +143 -9
  107. package/bin/pool/cache-sweep.mjs +31 -10
  108. package/bin/pool/ci-autoscale.mjs +160 -0
  109. package/bin/pool/cli.mjs +37 -8
  110. package/bin/pool/docker.mjs +3 -0
  111. package/bin/pool/engine-placement.test.mjs +94 -0
  112. package/bin/pool/lane-target.mjs +41 -0
  113. package/bin/pool/lane-tools.mjs +7 -2
  114. package/bin/pool/lane-tools.test.mjs +9 -0
  115. package/bin/pool/mirror-seed.mjs +15 -11
  116. package/bin/pool/router.mjs +88 -32
  117. package/bin/pool/version.mjs +29 -2
  118. package/bin/review-staging.mjs +11 -3
  119. package/bin/runner.mjs +59 -11
  120. package/bin/stats/release.mjs +7 -0
  121. package/bin/stats/release.test.mjs +20 -0
  122. package/bin/stats/scorecard.mjs +187 -0
  123. package/bin/stats/scorecard.test.mjs +89 -0
  124. package/docs/CONFIG.md +41 -0
  125. package/docs/OUTCOME-CODES.md +1 -0
  126. package/docs/STATS.md +17 -0
  127. package/package.json +1 -1
  128. package/pool/image/Dockerfile +14 -2
  129. package/pool/image/manifest.json +25 -0
  130. package/pool/image/mirror.sh +11 -2
  131. package/pool/install/install-agent.ps1 +11 -4
  132. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  133. package/scripts/ci-local/cli.mjs +1 -1
  134. package/scripts/ci-local/plan.mjs +3 -2
  135. package/scripts/ci-local.test.sh +11 -0
  136. package/scripts/failure-census.mjs +67 -0
  137. package/scripts/review-finalize.sh +5 -5
  138. package/scripts/review-finalize.test.sh +8 -1
  139. package/scripts/verify-phase-trail.sh +11 -0
  140. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -0,0 +1,187 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `forgedock scorecard --repo R --release vX [--json]` (#6084): a per-release scorecard computed from the register
5
+ * (GitHub telemetry records, optional batch rows and LANE_AUDIT annotations), compared to the previous release. No LLM
6
+ * and no network beyond the injected `gh`. Each metric is null (n/a) when its source is absent or below min n; a verdict
7
+ * is null when either side is null. Verdict rule and tolerances match bin/stats/release.mjs (#4628).
8
+ */
9
+ import { DEFAULT_MIN_N, UNKNOWN, compareVersions, percentile } from "./aggregate.mjs";
10
+ import { existsSync, readFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { batchRoot, listBatches } from "../lean/batch.mjs";
13
+ import { defaultGh, fetchGithubRecords, isTrusted, isValidRepo, parsePages, toModel } from "./github-source.mjs";
14
+
15
+ export const SCORECARD_MARKER = "<!-- FORGE:SCORECARD v1 -->";
16
+ const isNum = (x) => typeof x === "number" && Number.isFinite(x);
17
+ // kind: rate (absolute tolerance) | rel (relative tolerance)
18
+ export const SCORECARD_METRICS = [
19
+ { key: "first_pass_rate", label: "first-pass merge rate", lowerBetter: false, flat: 0.02, kind: "rate" },
20
+ { key: "interventions_per_batch", label: "operator interventions/batch", lowerBetter: true, flat: 0.05, kind: "rel" },
21
+ { key: "needs_human_genuine", label: "needs-human (genuine)", lowerBetter: true, flat: 0.05, kind: "rel" },
22
+ { key: "needs_human_pipeline", label: "needs-human (pipeline)", lowerBetter: true, flat: 0.05, kind: "rel" },
23
+ { key: "queue_min", label: "queue min/lane", lowerBetter: true, flat: 0.05, kind: "rel" },
24
+ { key: "active_min", label: "active min/lane", lowerBetter: true, flat: 0.05, kind: "rel" },
25
+ { key: "wait_min", label: "wait min/lane", lowerBetter: true, flat: 0.05, kind: "rel" },
26
+ { key: "minutes_per_merge", label: "minutes/merge", lowerBetter: true, flat: 0.05, kind: "rel" },
27
+ { key: "usd_per_merge", label: "$/merge", lowerBetter: true, flat: 0.05, kind: "rel" },
28
+ { key: "revert_rate", label: "revert rate", lowerBetter: true, flat: 0.02, kind: "rate" },
29
+ { key: "rework_rate", label: "rework rate", lowerBetter: true, flat: 0.02, kind: "rate" },
30
+ { key: "tested_requirements_rate", label: "requirements covered by tests", lowerBetter: false, flat: 0.02, kind: "rate" },
31
+ { key: "stuck_issues", label: "stuck issues (>1 attempt)", lowerBetter: true, flat: 0.05, kind: "rel" },
32
+ ];
33
+
34
+ const ratio = (a, b, minN) => (b >= minN && b > 0 ? a / b : null);
35
+ const sum = (xs) => xs.reduce((a, b) => a + b, 0);
36
+ const median = (xs, minN) => (xs.length >= minN ? percentile(xs, 50) : null);
37
+ const phaseSum = (r, k) => { const v = Object.values(r.phases ?? {}).map((p) => p?.[k]).filter(isNum); return v.length ? sum(v) : null; };
38
+
39
+ /** The metric values of one release; every one null when its source is absent or its own sample is below minN. */
40
+ export function scorecardValues({ records = [], batchRows = [], laneAudits = [] } = {}, release, minN = DEFAULT_MIN_N) {
41
+ const runs = records.filter((r) => r?.version === release && r.finished);
42
+ const merged = runs.filter((r) => r.reason === "merged");
43
+ const rows = batchRows.filter((b) => b && (b.release == null || b.release === release) && isNum(b.interventions));
44
+ const audits = laneAudits.filter((a) => a && (a.release == null || a.release === release) && (a.class === "genuine" || a.class === "pipeline"));
45
+ const nh = (c) => (audits.length >= minN ? audits.filter((a) => a.class === c).length : null);
46
+ const wall = merged.map((r) => r.wallMs).filter(isNum);
47
+ const usd = merged.map((r) => phaseSum(r, "usd")).filter(isNum);
48
+ const field = (k) => median(merged.map((r) => r[k]).filter(isNum), minN);
49
+ const active = merged.map((r) => phaseSum(r, "ms")).filter(isNum);
50
+ const revFlagged = merged.filter((r) => typeof r.reverted === "boolean");
51
+ const verifiable = merged.filter((r) => r.verified != null);
52
+ const attempts = (r) => r.builderAttempts?.length ?? 0;
53
+ return {
54
+ n: runs.length,
55
+ first_pass_rate: ratio(merged.filter((r) => !r.remediated && attempts(r) <= 1).length, merged.length, minN),
56
+ interventions_per_batch: rows.length >= minN ? sum(rows.map((b) => b.interventions)) / rows.length : null,
57
+ needs_human_genuine: nh("genuine"),
58
+ needs_human_pipeline: nh("pipeline"),
59
+ queue_min: field("queueMin"),
60
+ active_min: active.length >= minN ? percentile(active, 50) / 60000 : null,
61
+ wait_min: field("waitMin"),
62
+ minutes_per_merge: wall.length >= minN ? percentile(wall, 50) / 60000 : null,
63
+ usd_per_merge: usd.length >= minN ? sum(usd) / usd.length : null,
64
+ revert_rate: ratio(revFlagged.filter((r) => r.reverted).length, revFlagged.length, minN),
65
+ rework_rate: ratio(merged.filter((r) => r.remediated).length, merged.length, minN),
66
+ tested_requirements_rate: ratio(verifiable.filter((r) => r.verified).length, verifiable.length, minN),
67
+ stuck_issues: runs.length >= minN ? runs.filter((r) => attempts(r) > 1).length : null,
68
+ };
69
+ }
70
+
71
+ function verdict(m, cur, prev) {
72
+ if (!isNum(cur) || !isNum(prev)) return null;
73
+ const d = m.kind === "rate" ? cur - prev : prev === 0 ? (cur === 0 ? 0 : Infinity) : (cur - prev) / prev;
74
+ if (Math.abs(d) <= m.flat) return "flat";
75
+ return (d < 0) === m.lowerBetter ? "improved" : "regressed";
76
+ }
77
+
78
+ /** Never throws: a malformed input yields an all-null scorecard. */
79
+ export function buildScorecard({ records = [], batchRows = [], laneAudits = [], release, prev = null, minN = DEFAULT_MIN_N } = {}) {
80
+ try {
81
+ const known = [...new Set((records ?? []).map((r) => r?.version).filter((v) => v && v !== UNKNOWN))].sort(compareVersions);
82
+ const prevVersion = prev ?? (known.includes(release) ? known[known.indexOf(release) - 1] ?? null : null);
83
+ const src = { records: records ?? [], batchRows: batchRows ?? [], laneAudits: laneAudits ?? [] };
84
+ const values = scorecardValues(src, release, minN);
85
+ const before = prevVersion ? scorecardValues(src, prevVersion, minN) : null;
86
+ const verdicts = Object.fromEntries(SCORECARD_METRICS.map((m) => [m.key, before ? verdict(m, values[m.key], before[m.key]) : null]));
87
+ const regressions = SCORECARD_METRICS.filter((m) => verdicts[m.key] === "regressed").map((m) => m.key);
88
+ return { release, against: prevVersion, minN, values, previous: before, verdicts, regressions };
89
+ } catch {
90
+ const values = Object.fromEntries(SCORECARD_METRICS.map((m) => [m.key, null]));
91
+ return { release, against: null, minN, values, previous: null, verdicts: Object.fromEntries(SCORECARD_METRICS.map((m) => [m.key, null])), regressions: [] };
92
+ }
93
+ }
94
+
95
+ const fmt = (m, v) => (v == null ? "n/a" : m.kind === "rate" ? `${(v * 100).toFixed(0)}%` : m.key === "usd_per_merge" ? `$${v.toFixed(2)}` : String(Math.round(v * 100) / 100));
96
+
97
+ export function renderScorecard(sc) {
98
+ const line = (r) => `| ${r.join(" | ")} |`;
99
+ const head = ["metric", sc.release, sc.against ?? "previous", "verdict"];
100
+ const rows = SCORECARD_METRICS.map((m) => [m.label, fmt(m, sc.values[m.key]), sc.previous ? fmt(m, sc.previous[m.key]) : "n/a", sc.verdicts[m.key] ?? "n/a"]);
101
+ const reg = sc.regressions.length ? `Regressions vs ${sc.against}: ${SCORECARD_METRICS.filter((m) => sc.regressions.includes(m.key)).map((m) => m.label).join(", ")}` : `Regressions: none${sc.against ? ` vs ${sc.against}` : ""}`;
102
+ return [`Release scorecard ${sc.release} (min n ${sc.minN}; n/a when the source is absent or below it)`, line(head), line(head.map(() => "---")), ...rows.map(line), "", reg].join("\n");
103
+ }
104
+
105
+ /** The FORGE:SCORECARD section: marker, table and snapshot as fenced JSON. */
106
+ export function scorecardComment(sc) {
107
+ return `${SCORECARD_MARKER}\n${renderScorecard(sc)}\n\n\`\`\`json\n${JSON.stringify(sc)}\n\`\`\`\n`;
108
+ }
109
+
110
+ export const SCORECARD_HELP = `forgedock scorecard --repo <owner/repo> --release <vX> [--json] [--min-n N]
111
+ Per-release scorecard from the GitHub register, compared to the previous release. No LLM calls.
112
+ `;
113
+
114
+ export function parseScorecardArgs(argv) {
115
+ const o = { repo: null, release: null, json: false, help: false, minN: DEFAULT_MIN_N, error: null };
116
+ for (let i = 0; i < argv.length; i++) {
117
+ const a = argv[i];
118
+ if (a === "--help" || a === "-h") o.help = true;
119
+ else if (a === "--json") o.json = true;
120
+ else if (a === "--repo" || a === "--release" || a === "--min-n") {
121
+ const v = argv[++i];
122
+ if (v == null || v.startsWith("--")) { o.error = `${a} needs a value`; break; }
123
+ if (a === "--min-n") { const n = Number(v); if (!Number.isInteger(n) || n < 1) { o.error = "--min-n must be a positive integer"; break; } o.minN = n; }
124
+ else o[a.slice(2)] = v;
125
+ } else { o.error = `unknown argument ${a}`; break; }
126
+ }
127
+ return o;
128
+ }
129
+
130
+ /** Batch logs of `repo` on disk: one row per batch, interventions = operator requeues applied (state.json `requeueApplied`). */
131
+ export function batchRowsFromDisk(repo, root = batchRoot()) {
132
+ const read = (f) => { try { return JSON.parse(readFileSync(f, "utf8")); } catch { return null; } };
133
+ return listBatches(root).flatMap((id) => {
134
+ const plan = read(join(root, id, "plan.json")), st = existsSync(join(root, id, "state.json")) ? read(join(root, id, "state.json")) : null;
135
+ if (!plan || plan.repo !== repo || !st) return [];
136
+ return [{ batch: id, interventions: Array.isArray(st.requeueApplied) ? st.requeueApplied.length : 0 }];
137
+ });
138
+ }
139
+
140
+ export const LANE_AUDIT_RE = /^<!-- FORGE:LANE_AUDIT v1 -->/;
141
+ export const FAILURE_CENSUS_RE = /^<!-- FORGE:FAILURE_CENSUS v1 -->/;
142
+
143
+ /**
144
+ * Trusted LANE_AUDIT and failure-census comments -> entries. Each comment starts with its marker and carries a fenced
145
+ * json block holding one object or an array: LANE_AUDIT `{issue, release?, class: "genuine"|"pipeline"}`, failure-census
146
+ * `{issue, release?, class?, reverted?}` (a census `class` counts as a needs-human audit when no LANE_AUDIT covers the issue).
147
+ */
148
+ export function parseRegisterComments(comments, env = process.env) {
149
+ const out = { laneAudits: [], census: [] };
150
+ for (const c of comments ?? []) {
151
+ const body = String(c?.body ?? "");
152
+ const kind = LANE_AUDIT_RE.test(body) ? "laneAudits" : FAILURE_CENSUS_RE.test(body) ? "census" : null;
153
+ if (!kind || !isTrusted(c, env)) continue;
154
+ const block = /```json\n([\s\S]*?)(?:\n```|$)/.exec(body);
155
+ if (!block) continue;
156
+ let v; try { v = JSON.parse(block[1]); } catch { continue; }
157
+ for (const e of Array.isArray(v) ? v : [v]) if (e && typeof e === "object") out[kind].push(e);
158
+ }
159
+ const audited = new Set(out.laneAudits.map((a) => a.issue));
160
+ out.laneAudits.push(...out.census.filter((e) => e.class && !audited.has(e.issue)).map((e) => ({ issue: e.issue, release: e.release, class: e.class })));
161
+ return out;
162
+ }
163
+
164
+ /** Fetch the register and build the scorecard. `deps.gh`/`deps.fetch` are injectable. */
165
+ export async function gatherScorecard({ repo, release, minN = DEFAULT_MIN_N }, deps = {}) {
166
+ const result = await (deps.fetch ?? fetchGithubRecords)({ repo, gh: deps.gh ?? defaultGh, useCache: deps.useCache ?? true });
167
+ const model = toModel(repo, result);
168
+ let reg = { laneAudits: [], census: [] };
169
+ try { reg = deps.register ?? parseRegisterComments(parsePages(await (deps.gh ?? defaultGh)(["api", "--paginate", `repos/${repo}/issues/comments`]))); } catch { /* no register comments: those metrics stay n/a */ }
170
+ const reverted = new Set(reg.census.filter((e) => e.reverted === true).map((e) => e.issue)), tracked = new Set(reg.census.filter((e) => typeof e.reverted === "boolean").map((e) => e.issue));
171
+ const runs = model.runs.map((r) => (tracked.has(r.issue) ? { ...r, reverted: reverted.has(r.issue) } : r));
172
+ return buildScorecard({ records: runs, laneAudits: [...(deps.laneAudits ?? []), ...reg.laneAudits], batchRows: deps.batchRows ?? (() => { try { return batchRowsFromDisk(repo); } catch { return []; } })(), release, minN });
173
+ }
174
+
175
+ export async function runScorecard(argv, deps = {}) {
176
+ const o = parseScorecardArgs(argv);
177
+ if (o.help) { process.stdout.write(SCORECARD_HELP); return 0; }
178
+ const fail = (msg) => { process.stderr.write(`forgedock scorecard: ${msg}\n`); return 2; };
179
+ if (o.error) return fail(o.error);
180
+ if (!o.release) return fail("--release is required");
181
+ if (!isValidRepo(o.repo)) return fail("--repo owner/repo is required");
182
+ try {
183
+ const sc = await gatherScorecard(o, deps);
184
+ process.stdout.write(`${o.json ? JSON.stringify(sc) : renderScorecard(sc)}\n`);
185
+ return 0;
186
+ } catch (err) { process.stderr.write(`forgedock scorecard: ${err.message}\n`); return 1; }
187
+ }
@@ -0,0 +1,89 @@
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 { mkdirSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "../tests/_tmp.mjs";
8
+ import { parseRegisterComments, batchRowsFromDisk, buildScorecard, renderScorecard, scorecardComment, parseScorecardArgs, runScorecard, gatherScorecard, SCORECARD_MARKER } from "./scorecard.mjs";
9
+
10
+ const run = (version, i, o = {}) => ({ version, issue: i, finished: true, reason: "merged", remediated: false, wallMs: 600000, verified: true,
11
+ phases: { implement: { usd: 2, ms: 300000 } }, builderAttempts: [{ attempt: 1 }], ...o });
12
+ const many = (v, n, f) => Array.from({ length: n }, (_, i) => run(v, i, f?.(i)));
13
+
14
+ describe("scorecard", () => {
15
+ it("computes metrics from fixtures; sources that are absent are null", () => {
16
+ const sc = buildScorecard({ records: many("1.0.0", 10), release: "1.0.0", minN: 5 });
17
+ assert.equal(sc.values.first_pass_rate, 1);
18
+ assert.equal(sc.values.minutes_per_merge, 10);
19
+ assert.equal(sc.values.usd_per_merge, 2);
20
+ assert.equal(sc.values.active_min, 5);
21
+ assert.equal(sc.values.stuck_issues, 0);
22
+ assert.equal(sc.values.interventions_per_batch, null);
23
+ assert.equal(sc.values.needs_human_genuine, null); // no LANE_AUDIT
24
+ assert.equal(sc.values.revert_rate, null);
25
+ });
26
+ it("splits needs-human by LANE_AUDIT class and averages interventions per batch", () => {
27
+ const laneAudits = [...Array(3).fill({ class: "genuine" }), ...Array(2).fill({ class: "pipeline" })];
28
+ const batchRows = [{ interventions: 2 }, { interventions: 4 }];
29
+ const sc = buildScorecard({ records: many("1.0.0", 5), laneAudits, batchRows, release: "1.0.0", minN: 2 });
30
+ assert.equal(sc.values.needs_human_genuine, 3);
31
+ assert.equal(sc.values.needs_human_pipeline, 2);
32
+ assert.equal(sc.values.interventions_per_batch, 3);
33
+ });
34
+ it("is null below min-n", () => {
35
+ assert.equal(buildScorecard({ records: many("1.0.0", 3), release: "1.0.0" }).values.first_pass_rate, null);
36
+ });
37
+ it("flags a regression against the previous release", () => {
38
+ const records = [...many("1.0.0", 10), ...many("1.1.0", 10, (i) => (i < 5 ? { remediated: true } : {}))];
39
+ const sc = buildScorecard({ records, release: "1.1.0" });
40
+ assert.equal(sc.against, "1.0.0");
41
+ assert.equal(sc.verdicts.first_pass_rate, "regressed");
42
+ assert.ok(sc.regressions.includes("rework_rate"));
43
+ assert.equal(sc.verdicts.minutes_per_merge, "flat");
44
+ });
45
+ it("never throws on bad input and renders with the marker", () => {
46
+ const sc = buildScorecard({ records: [null, 5], release: "x" });
47
+ assert.deepEqual(sc.regressions, []);
48
+ const recs = [...many("1.0.0", 10), ...many("1.1.0", 10, () => ({ remediated: true }))];
49
+ const out = scorecardComment(buildScorecard({ records: recs, release: "1.1.0" }));
50
+ assert.ok(out.startsWith(SCORECARD_MARKER));
51
+ assert.match(renderScorecard(buildScorecard({ records: recs, release: "1.1.0" })), /Regressions vs 1\.0\.0: .*first-pass merge rate/);
52
+ assert.match(renderScorecard(sc), /n\/a/);
53
+ });
54
+ it("parses CLI args; --release is required", async () => {
55
+ assert.deepEqual(parseScorecardArgs(["--repo", "o/r", "--release", "v1", "--json"]).release, "v1");
56
+ assert.match(parseScorecardArgs(["--bogus"]).error, /unknown/);
57
+ assert.match(parseScorecardArgs(["--release"]).error, /needs a value/);
58
+ assert.equal(await runScorecard(["--repo", "o/r"]), 2);
59
+ });
60
+ it("uses only the injected fetcher (no network)", async () => {
61
+ const fetch = async ({ repo }) => ({ records: [], items: [], repo });
62
+ const sc = await gatherScorecard({ repo: "o/r", release: "v1" }, { fetch, gh: async () => { throw new Error("no network"); } });
63
+ assert.equal(sc.values.n, 0);
64
+ });
65
+ it("reads batch logs from disk: interventions are applied requeues of that repo's batches", () => {
66
+ const root = tmpDir("sc-");
67
+ const mk = (id, repo, st) => { mkdirSync(join(root, id), { recursive: true }); writeFileSync(join(root, id, "plan.json"), JSON.stringify({ repo })); writeFileSync(join(root, id, "state.json"), JSON.stringify(st)); };
68
+ mk("b-1", "o/r", { requeueApplied: ["a", "b"] });
69
+ mk("b-2", "o/r", {});
70
+ mk("b-3", "x/y", { requeueApplied: ["a"] });
71
+ assert.deepEqual(batchRowsFromDisk("o/r", root), [{ batch: "b-1", interventions: 2 }, { batch: "b-2", interventions: 0 }]);
72
+ });
73
+ it("reads LANE_AUDIT and failure-census comments from the register; untrusted or malformed ones are ignored", async () => {
74
+ const c = (marker, v, assoc = "OWNER") => ({ author_association: assoc, user: { login: "u" }, body: `<!-- FORGE:${marker} v1 -->\n\`\`\`json\n${typeof v === "string" ? v : JSON.stringify(v)}\n\`\`\`` });
75
+ const reg = parseRegisterComments([
76
+ c("LANE_AUDIT", [{ issue: 1, class: "genuine" }, { issue: 2, class: "pipeline" }]),
77
+ c("FAILURE_CENSUS", { issue: 3, class: "pipeline", reverted: true }),
78
+ c("LANE_AUDIT", { issue: 9, class: "genuine" }, "NONE"),
79
+ c("LANE_AUDIT", "{not json"),
80
+ { body: "plain", author_association: "OWNER" },
81
+ ], {});
82
+ assert.deepEqual(reg.laneAudits.map((a) => `${a.issue}:${a.class}`), ["1:genuine", "2:pipeline", "3:pipeline"]);
83
+ assert.equal(reg.census.length, 1);
84
+ const fetch = async () => ({ records: [], items: [] });
85
+ const sc = await gatherScorecard({ repo: "o/r", release: "v1", minN: 1 }, { fetch, register: reg, batchRows: [] });
86
+ assert.equal(sc.values.needs_human_genuine, 1);
87
+ assert.equal(sc.values.needs_human_pipeline, 2);
88
+ });
89
+ });
package/docs/CONFIG.md CHANGED
@@ -488,6 +488,22 @@ orchestration:
488
488
 
489
489
  ---
490
490
 
491
+ ## `orchestrate.lane_audit` (OPTIONAL)
492
+
493
+ Engine-gap filing of the lane audit (#6078). When a lane ends needs-human or engine-error on an active pipeline/env/pool signature, the audit can file an issue in the engine repo.
494
+
495
+ ```yaml
496
+ orchestrate:
497
+ lane_audit:
498
+ file_gaps: false # default false; only the string true enables
499
+ repo: RapierCraftStudios/ForgeDock # optional: engine repo to file in
500
+ label: engine-gap # optional
501
+ ```
502
+
503
+ One issue per signature: it is found by the `<!-- forge-gap: SIGNATURE -->` marker among open issues with the label; a further lane with the same signature updates its occurrence count and affected-lane list (`#N`, a lane is counted once). Nothing is filed for `fixed_in_later` signatures or genuine/spec classes. Redaction: the body holds only the signature, class, owner, action, engine version, count and lane issue numbers; any text in it has the lane's repo name, `owner/name` patterns and absolute paths replaced by `<repo>`/`<path>`. Filing failures are ignored and never change how the lane ends.
504
+
505
+ ---
506
+
491
507
  ## `orchestrate.health` and `notify` (OPTIONAL)
492
508
 
493
509
  Early batch health (#5167). `forgedock orchestrate` checks each batch at T+15 and T+60 minutes after it was created (`plan.json` `created`), and once more when the batch ends. When the batch starts, it prints the schedule: `health checks: T+15 14:05Z, T+60 14:50Z, and at batch end; forgedock status --batch <id>`. The first unhealthy check raises one `BATCH UNHEALTHY <id>` alert, which lists the top causes and the exact recovery commands (`--requeue`, a relaunch, `--resume`, `--cancel`). `health.json` in the batch dir records the checkpoints already done and the alert, so a daemon restart arms only the remaining checks and a batch never alerts twice. Checks and alerts never fail, delay or change the batch.
@@ -851,6 +867,7 @@ The forge.yaml reader handles two levels, so the rehearsal block is written as t
851
867
  | `publish_workflow` | string | No | Workflow file post-merge looks for (and dispatches when no run appears) for the merge commit. Default: `publish.yml`. |
852
868
 
853
869
  | `preflight_command` | string | No | Shell command run on the host (not as Actions minutes) in the repo checkout on the staging head **before** the release PR is opened (#5277), again after each fix round, and once more on the final head before the PR is marked ready. Put the repo's own suites here, e.g. `preflight_command: npm test`. Setting it also opens the release PR as a **draft** and marks it ready only after review and a passing preflight, so Actions CI runs once on the final head. Unset: no preflight, the PR is opened ready as before. |
870
+ | `allow_red_staging` | bool | No | Staging-health gate (#6013): before a release is cut, every check-run of the staging head must be finished and green; otherwise the preflight step refuses and names **all** failed checks (classified regression or runner) and pending ones, so the fixes go out together and the next snapshot is cut once. `allow_red_staging: true` proceeds with a recorded warning. Default `false`. The ledger records each round (`rounds`: pr, head, outcome, cause, times) and `forgedock stats --release-ledger` trends snapshot rounds per release. |
854
871
  | `preflight_timeout` | integer | No | Seconds before the command is killed (counts as a failure). Default: `1200`. |
855
872
  | `preflight_blocking` | boolean | No | `true` (default): a failure files one `release-blocker` issue per head (a re-run comments on it) and stops the job before the PR is opened or marked ready; fix it and `--resume <id>`. `false`: the failure is recorded and the release goes on. |
856
873
  | `rehearsal_command` | string | No | Shell command run on the host (not as Actions minutes) in the repo checkout, on the release-PR head after review and before promotion (#5253). Wire the project's deploy dry-run here: bundle build, env load and the trusted-runtime closure check, e.g. `rehearsal_command: ./scripts/deploy-dry-run.sh` where the script builds the release bundle, loads the production env file in check mode and verifies the trusted-runtime closure, exiting non-zero on the first failure. Unset: no rehearsal, release behavior is unchanged. |
@@ -1753,6 +1770,7 @@ execution:
1753
1770
  | `warm_sandboxes` | integer | No | Warm sandboxes per repo the pool agent keeps ready (checkout at the base ref, dependency cache primed). When `N > 0` the launch spec carries `warm: N` and the lane first calls `POST {endpoint}/sandboxes/claim`; a ready warm sandbox takes the lane (refreshed to the lane's base ref with an incremental fetch before work starts), and when none is ready, the claim fails or the endpoint lacks the route the lane starts cold. Default `0` (off): no claim call and the launch spec is unchanged (forge#4912). |
1754
1771
  | `unreachable_window_min` | number | No | Remote providers: how long a lane keeps polling (with backoff, up to 30s) after the provider's transport fails (connection refused/reset, `fetch failed`, timeout, 502/503/504) before it ends `deferred` with `sandbox.unreachable` (forge#4672). Inside the window the lane never ends and the sandbox is never torn down; after it the sandbox is kept and adopted on the next attempt or `--resume`; the engine-error breaker does not count it. `adopt` applies the same window. Default: 5 |
1755
1772
  | `on_budget` | string | No | `stop` (default): running lanes finish and the rest end `held` (`execution budget: ...`) for a later `--resume`. `local`: the rest run as detached host lanes. |
1773
+ | `min_lane_engine` | string | No | Lowest lane-engine version (e.g. `1.67`) a pool agent may run this batch's lanes on (forge#6091). Placement always prefers agents on the orchestrator's engine version; unset (default), a lower-version agent is still used as a fallback when it is the only one free. Set, agents below it are skipped and, when none qualifies, the launch is deferred (`pool.engine_old`) until an agent upgrades. |
1756
1774
  | `host_capabilities` | list | No | Host-only capabilities the dispatching host has and a sandbox does not relay (forge#4542): names such as `sops`, `prod_monitor`, `ops_credentials`. A lane whose issue text names one (built-in signals: `.secrets/*.enc.yaml`, `sops`, `ssh *-monitor`, `obs-psql`, `credentials.yaml`; a declared name written out; `host_capability_patterns`) is placed `local` in `remote` and `hybrid` mode with the reason `host capability: <name>`, unless the provider relays it (`relay_commands`, forge#4778; otherwise remote providers relay none). A remote lane that still blocks as `credentials` naming only a declared capability ends `env.capability_remote` (recoverable) and is rerun locally once. |
1757
1775
  | `host_capability_patterns` | list | No | `name:regex` entries (case-insensitive) that also mean the lane needs capability `name`, e.g. `vault:vault\s+kv`. An invalid entry is ignored. |
1758
1776
  | `relay_commands` | list | No | Read-only capability relay (forge#4778): `capability:command` entries, e.g. `prod_monitor:obs-psql` or `prod_monitor:obs-*` (exact name, or a prefix glob with one trailing `*`; no `/`, whitespace or other glob characters). A `remote`/`pool` lane needing a listed capability is placed remote: the sandbox runs the command unchanged (a `cs-relay` shim), the request goes sandbox -> pool agent -> router queue, and the dispatching host picks it up on its status poll, gates it against this list and runs it with no shell, a 120 s timeout and a 1 MB output cap, redacting known secrets; a refused command gets rc 126 and the key never leaves the host. List only read-only wrappers, never `sops` or `ops_credentials`. The frozen contract's simple validate / repro_test commands that pass the gate are pre-fetched at dispatch and shipped with the lane (96 KB cap). An older router or agent without the relay makes `cs-relay` exit 125, the lane blocks as `credentials` and is recovered locally once, as before. |
@@ -2035,6 +2053,7 @@ review:
2035
2053
  auth: "JWT + refresh token rotation; sessions stored in Redis"
2036
2054
  database: "Always use docker exec <container> for psql/migrations"
2037
2055
 
2056
+ # max_parallel: 2 # release review: reviewers running at once (default max(2, cores/2)); the rest queue. Reviewers run at nice 19 / ionice idle (#6098)
2038
2057
  # max_filed_findings: 2 # per-review cap on filed findings (default 2; 1 on review-finding lineage)
2039
2058
 
2040
2059
  # key_paths:
@@ -2964,3 +2983,25 @@ A failed or timed-out sweep (10 min limit) shows as `cache_sweep_error` in the a
2964
2983
  ## Complete Example
2965
2984
 
2966
2985
  See [`forge.yaml.example`](../forge.yaml.example) at the repository root for a fully annotated example covering all sections.
2986
+
2987
+ ---
2988
+
2989
+ ## Router config: `ci_autoscale` (#5695)
2990
+
2991
+ Keys of the pool router's own config file (not `forge.yaml`). The CI runner autoscaler is off by default.
2992
+
2993
+ | Key | Default | Meaning |
2994
+ |---|---|---|
2995
+ | `ci_autoscale.enabled` | `false` | Turns on `POST /ci/workflow-job` tracking and the reconcile at the end of each router tick. |
2996
+ | `ci_autoscale.dry_run` | `false` | Log every scale decision with its inputs but start or stop nothing. |
2997
+ | `ci_autoscale.repo` | unset | `owner/name` for `generate-jitconfig` and the jobs-API poll fallback. Uses the router host's `gh auth token`. |
2998
+ | `ci_autoscale.poll_s` | `300` | Seconds between jobs-API polls. |
2999
+ | `ci_autoscale.runner_group_id` | `1` | Runner group for JIT runners. |
3000
+ | `ci_autoscale.labels.<label>` | none | One entry per runner label: `min` (warm runners), `max` (hard cap), `size` `{cpus, mem_gb}` (default 1 / 2). Only jobs carrying a configured label are counted. |
3001
+ | `ci_autoscale.floors.mem_available_gb` | `3` | MemAvailable that must remain after the reservation. |
3002
+ | `ci_autoscale.floors.load_per_cpu` | `0.8` | Load per vCPU allowed after the reservation. |
3003
+ | `ci_autoscale.floors.net_rx_mbps_max` | unset | Refuse starts above this host RX rate (deploy exempt). |
3004
+ | `ci_autoscale.lane_floor` | `{cpus: 2, mem_gb: 3}` | Pool `cpus_free`/`mem_free_gb` left for lanes. CI never takes it. |
3005
+ | `ci_autoscale.windows` | `[]` | `[{from, to, why}]` ISO times: no starts or stops inside a window. |
3006
+
3007
+ Priority is deploy label > release branch (`release/*`, `hotfix/*`) > lanes > ordinary PR CI. Agent config `runner_image` (default `ghcr.io/actions/actions-runner:latest`) is the runner container image.
@@ -60,6 +60,7 @@ An absent or unknown code is recorded as `unclassified`, with the raw reason kep
60
60
  | `env.tool_missing` | Core work-on (forge#4323): a validate command the builder recorded as failed was rerun by the engine and could not run because the host lacks a tool or module (`command not found` / exit 127, Python `No module named x`, Node `Cannot find module|package 'x'` for a bare name the repo does not track). An environment error, not a conformance failure: no builder resume, no reviewer. Also ends this way when a remote-sandbox builder reports a missing tool as a `credentials` block (forge#4685, `missingToolBlock`). Ends `needs-human` naming the tool; recoverable by `forgedock orchestrate` (the recovery lane runs the check through the repo's own toolchain). Skipped on a CI-verified head | lean | `gate()` rerun via `io.runCommand`, `{rc, output}` classified by `conformance.mjs` `missingTool` |
61
61
  | `env.repro_unrunnable` | Core work-on (forge#4334): on a bug lane the frozen `repro_test` could not be run on head by `scripts/acceptance-red-green.sh` (`HEAD=UNRUNNABLE`: timeout, exit 126/127, unclassifiable output) or the harness returned no result. An environment error, not a conformance failure: no builder resume, no reviewer. Ends `needs-human`; recoverable by `forgedock orchestrate` (the recovery lane reruns the repro command through the repo's own toolchain and installed dependencies). Other non-proofs (passes on base, fails on head, base unrunnable) stay `conformance.unimplemented` | lean | `gate()` `io.redGreen` words, classified by `conformance.mjs` `reproFailures` |
62
62
  | `env.capability_remote` | Core work-on (forge#4542): a lane placed in a remote sandbox ended `builder.blocked (credentials)` and its summary names only host capabilities declared in `execution.host_capabilities` (SOPS/age key, ops credentials, prod monitor SSH), which the sandbox does not relay but the dispatching host has. Recoverable by `forgedock orchestrate`: the recovery lane is placed local, once, under the same lease. A credential need the host lacks too stays `builder.blocked` | lean | `endBlocked` via `execution.mjs` `hostCapabilityBlock` |
63
+ | `env.engine_skew` | Core work-on (forge#5931): a remote sandbox lane ran an engine version (major.minor) other than the dispatching host's, so gates fixed in the host version still fire. Held as an environment outcome (re-admitted on an engine upgrade or --set-env), never reported as conformance. |
63
64
  | `sandbox.start_failed` | A `forgedock orchestrate` lane sandbox (forge.yaml `execution`, provider `container` or `remote`) could not start: bad image, missing endpoint, a refused launch (HTTP 4xx other than 401/403/429) or a non-HTTP start failure. The lane never ran. Final `needs-human` row: not relaunched and not counted by the engine-error circuit breaker | orchestrate | `bin/lean/execution.mjs` `providerLanes`: `provider.start` threw without `retryable`, `transient` or a 5xx/401/403 `status` |
64
65
  | `base.red` | Core work-on: a `verify.invariants` guard command fails on the base too (forge#5239). `deferred` (retry 900 s), never needs-human; the introducing issue gets a `FORGE:BASE_RED` comment (reopened if closed) | lean | `bin/lean/basered.mjs` guard run on the base |
65
66
  | `sandbox.capacity` | The sandbox provider had no capacity for the lane (HTTP 429/503 from the remote transport). `deferred`, requeued after `Retry-After` when sent, else 60s; not counted toward `orchestration.max_deferrals`, like `host.busy` (forge#4528) | orchestrate | `provider.start` threw with `err.retryable: true` |
package/docs/STATS.md CHANGED
@@ -333,3 +333,20 @@ The lean lane assigns each issue an arm (sha1 of id and issue number over the ra
333
333
  runs per arm with the metrics of `--by version`; a metric under min n is null and so is any target that needs it, never a
334
334
  pass. `targets_met` is true only when every target is met. `--require-met` (with `--experiment`) prints the same report but exits 1 unless `targets_met` is true (0 otherwise; 2 without `--experiment`), so a post-deploy check can gate on it (#4634). The report, `scripts/bench-lightlane.mjs aggregate` and
335
335
  `scripts/eval-gate-scorecard.mjs` share one record: `{schema: "forge.bench.v1", source, arms, targets}`.
336
+
337
+ ## Per-release scorecard (`forgedock scorecard`, forge#6084)
338
+
339
+ `forgedock scorecard --repo owner/repo --release vX [--json] [--min-n N]` prints a per-release table computed from the
340
+ GitHub register (telemetry records; no LLM, no network beyond `gh`), compared with the previous known release. The
341
+ release flow appends the same table, with a `Regressions vs <prev>: ...` line, to the release PR body; if the scorecard
342
+ cannot be computed the section is left out and the PR is still created.
343
+
344
+ Metrics (each `n/a` when its source is absent or its sample is below min n, default 10; verdicts reuse the `--by version`
345
+ rule and tolerances): first-pass merge rate (merged runs with no remediation and at most one builder attempt),
346
+ operator interventions per batch (batch rows), needs-human by LANE_AUDIT class (genuine vs pipeline), queue, active and
347
+ wait minutes per merged lane, minutes (wall p50) and $ per merge, revert rate, rework rate (merged runs that needed
348
+ remediation), share of requirements covered by tests (merged runs whose requirements were all verified) and stuck issues
349
+ (runs with more than one builder attempt).
350
+
351
+ Batch rows are read from the local batch logs (`~/.forge/batches/*/state.json`, interventions = applied requeues of the repo's batches). The scorecard is published in the release PR body (the release notes). LANE_AUDIT and failure-census are read from trusted issue comments that start with `<!-- FORGE:LANE_AUDIT v1 -->` or `<!-- FORGE:FAILURE_CENSUS v1 -->` and carry a fenced `json` block (one object or an array): LANE_AUDIT `{issue, release?, class: genuine|pipeline}`, failure-census `{issue, release?, class?, reverted?}` (`reverted` feeds the revert rate; a census `class` counts as an audit when no LANE_AUDIT covers the issue). They are optional inputs: they are not on every base, so without them
352
+ the dependent metrics report `n/a` rather than a guess.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "forgedock",
3
- "version": "1.67.0",
3
+ "version": "1.68.0",
4
4
  "description": "An AI engineering team that ships to production",
5
5
  "bin": {
6
6
  "forgedock": "bin/forgedock.mjs"
@@ -13,14 +13,17 @@ ARG FORGEDOCK_VERSION
13
13
  ARG CLAUDE_CODE_VERSION=2.1.309
14
14
  ARG UV_VERSION=0.12.5
15
15
  ARG POETRY_VERSION=2.4.3
16
+ ARG YQ_VERSION=4.44.3
17
+ ARG PLAYWRIGHT_VERSION=1.49.1
16
18
 
17
19
  LABEL org.opencontainers.image.version=$FORGEDOCK_VERSION
18
20
  RUN test -n "$FORGEDOCK_VERSION" || { echo "FORGEDOCK_VERSION build arg is required" >&2; exit 1; }
19
21
 
20
- ENV IS_SANDBOX=1 DEBIAN_FRONTEND=noninteractive LANG=C.UTF-8 PATH=/opt/cs/bin:/opt/node/bin:/root/.local/bin:$PATH
22
+ ENV IS_SANDBOX=1 DEBIAN_FRONTEND=noninteractive LANG=C.UTF-8 PLAYWRIGHT_BROWSERS_PATH=/opt/playwright UV_PYTHON_INSTALL_DIR=/opt/uv-python PATH=/opt/cs/bin:/opt/node/bin:/root/.local/bin:$PATH
21
23
 
22
24
  RUN apt-get update && apt-get install -y --no-install-recommends \
23
25
  ca-certificates curl git jq xz-utils build-essential python3 python3-venv python3-dev pkg-config libpq-dev \
26
+ shellcheck xvfb xauth postgresql-client redis-tools \
24
27
  && install -d -m 0755 /etc/apt/keyrings \
25
28
  && curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o /etc/apt/keyrings/githubcli.gpg \
26
29
  && echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/githubcli.gpg] https://cli.github.com/packages stable main" > /etc/apt/sources.list.d/github-cli.list \
@@ -35,7 +38,16 @@ RUN curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-l
35
38
  && npm cache clean --force
36
39
 
37
40
  RUN curl -LsSf "https://astral.sh/uv/${UV_VERSION}/install.sh" | env UV_INSTALL_DIR=/usr/local/bin sh \
38
- && uv tool install "poetry==${POETRY_VERSION}"
41
+ && uv tool install "poetry==${POETRY_VERSION}" \
42
+ && uv python install 3.11 3.13 \
43
+ && ln -s "$(uv python find 3.11)" /usr/local/bin/python3.11 \
44
+ && ln -s "$(uv python find 3.13)" /usr/local/bin/python3.13
45
+
46
+ # yq (mikefarah): pinned release binary. Playwright chromium lives at PLAYWRIGHT_BROWSERS_PATH, shared by every lane user.
47
+ RUN curl -fsSL "https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/yq_linux_amd64" -o /usr/local/bin/yq \
48
+ && chmod 0755 /usr/local/bin/yq \
49
+ && npx --yes "playwright@${PLAYWRIGHT_VERSION}" install --with-deps chromium \
50
+ && rm -rf /var/lib/apt/lists/* /root/.npm
39
51
 
40
52
  COPY entrypoint.sh /usr/local/bin/cs-entrypoint
41
53
  COPY warm-refresh.sh /usr/local/bin/cs-warm-refresh
@@ -0,0 +1,25 @@
1
+ {
2
+ "tools": [
3
+ { "name": "git", "binary": "git", "kind": "apt", "package": "git" },
4
+ { "name": "curl", "binary": "curl", "kind": "apt", "package": "curl" },
5
+ { "name": "jq", "binary": "jq", "kind": "apt", "package": "jq" },
6
+ { "name": "shellcheck", "binary": "shellcheck", "kind": "apt", "package": "shellcheck" },
7
+ { "name": "xvfb", "binary": "xvfb-run", "kind": "apt", "package": "xvfb" },
8
+ { "name": "postgresql-client", "binary": "psql", "kind": "apt", "package": "postgresql-client" },
9
+ { "name": "redis-tools", "binary": "redis-cli", "kind": "apt", "package": "redis-tools" },
10
+ { "name": "gh", "binary": "gh", "kind": "apt", "package": "gh" },
11
+ { "name": "docker", "binary": "docker", "kind": "apt", "package": "docker-ce-cli" },
12
+ { "name": "python3", "binary": "python3", "kind": "apt", "package": "python3" },
13
+ { "name": "python3.12", "binary": "python3.12", "kind": "apt", "package": "python3" },
14
+ { "name": "yq", "binary": "yq", "kind": "download", "marker": "/usr/local/bin/yq" },
15
+ { "name": "node", "binary": "node", "kind": "download", "marker": "nodejs.org/dist" },
16
+ { "name": "corepack", "binary": "corepack", "kind": "npm", "package": "corepack" },
17
+ { "name": "forgedock", "binary": "forgedock", "kind": "npm", "package": "forgedock" },
18
+ { "name": "claude", "binary": "claude", "kind": "npm", "package": "@anthropic-ai/claude-code" },
19
+ { "name": "uv", "binary": "uv", "kind": "download", "marker": "astral.sh/uv" },
20
+ { "name": "poetry", "binary": "poetry", "kind": "uv-tool", "package": "poetry" },
21
+ { "name": "python3.11", "binary": "python3.11", "kind": "uv-python", "package": "3.11" },
22
+ { "name": "python3.13", "binary": "python3.13", "kind": "uv-python", "package": "3.13" },
23
+ { "name": "playwright-chromium", "binary": "chromium", "kind": "playwright", "package": "chromium" }
24
+ ]
25
+ }
@@ -13,7 +13,7 @@ mirror_valid() {
13
13
  local m="$1"
14
14
  [ -d "$m/objects" ] || return 1
15
15
  [ -n "$(git -C "$m" for-each-ref --count=1 2>/dev/null)" ] || return 1
16
- [ -z "$(find "$m/objects" -type f -size 0 -print -quit 2>/dev/null)" ] || return 1
16
+ [ -z "$(find "$m/objects" -type f -size 0 ! -name 'tmp_*' ! -name '*.lock' -print -quit 2>/dev/null)" ] || return 1 # git's own in-flight temp/lock files are empty by design (#6094)
17
17
  if [ "${MIRROR_FSCK:-}" = "1" ]; then git -C "$m" fsck --connectivity-only --no-dangling >/dev/null 2>&1 || return 1; fi
18
18
  return 0
19
19
  }
@@ -40,11 +40,20 @@ mirror_build() {
40
40
  return 1
41
41
  }
42
42
 
43
+ # #6094: a mirror is judged corrupt only by someone who holds the per-repo lock. A lock held elsewhere means a build or fetch is
44
+ # writing into it (transiently "invalid"), so the caller queues behind it instead of quarantining a healthy mirror.
45
+ mirror_corrupt() {
46
+ local m="$1" lock="$1.lock"
47
+ [ -d "$m" ] || return 1
48
+ mirror_valid "$m" && return 1
49
+ ( flock -n 9 || exit 1; ! mirror_valid "$m" ) 9>"$lock"
50
+ }
51
+
43
52
  mirror_prepare() {
44
53
  local url="$1" m="$2" lock
45
54
  mkdir -p "$(dirname "$m")" 2>/dev/null
46
55
  lock="$m.lock"
47
- if [ -d "$m" ] && ! mirror_valid "$m"; then
56
+ if mirror_corrupt "$m"; then
48
57
  # Bad mirror: set it aside for everyone, rebuild once in the background, this lane clones directly.
49
58
  ( flock -w "${MIRROR_LOCK_WAIT:-900}" 9 || exit 0
50
59
  if [ -d "$m" ] && ! mirror_valid "$m"; then mirror_quarantine "$m"; fi
@@ -18,6 +18,7 @@ param(
18
18
  [int] $AllowMemGb = 0, # 0 = half of physical RAM (min 4)
19
19
  [string] $Distro = 'computeshare',
20
20
  [ValidateSet('auto', 'mirrored', 'nat')] [string] $Networking = 'auto', # nat: for PCs where mirrored mode fails (e.g. WSL error 0x8007054f)
21
+ [switch] $KeepaliveAtStartup, # run the keep-alive at boot (S4U) for accounts that never log on interactively
21
22
  [switch] $Force # kept for compatibility; the install never prompts
22
23
  )
23
24
  $ErrorActionPreference = 'Stop'
@@ -35,8 +36,13 @@ New-Item -ItemType Directory -Force -Path $installDir | Out-Null
35
36
  $ts = (Get-Command tailscale.exe -ErrorAction SilentlyContinue).Source
36
37
  if (-not $ts) { $ts = Join-Path $env:ProgramFiles 'Tailscale\tailscale.exe' }
37
38
  if (-not (Test-Path $ts)) { Fail 'Tailscale is not installed.' }
38
- $tsIp = (& $ts ip -4 | Select-Object -First 1).Trim()
39
- if ($tsIp -notmatch '^100\.') { Fail "Could not read this machine's Tailscale IPv4 (got '$tsIp')." }
39
+ # The CLI refuses (401) when Tailscale belongs to another Windows user and prints nothing; fall back to the adapter.
40
+ $tsIp = ''
41
+ try { $tsIp = ("$(& $ts ip -4 2>$null | Select-Object -First 1)").Trim() } catch { $tsIp = '' }
42
+ if ($tsIp -notmatch '^100\.') {
43
+ $tsIp = ("$(Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.InterfaceAlias -like 'Tailscale*' -and $_.IPAddress -like '100.*' } | Select-Object -First 1 -ExpandProperty IPAddress)").Trim()
44
+ }
45
+ if ($tsIp -notmatch '^100\.') { Fail 'Found no Tailscale IPv4 address (the tailscale CLI was denied or empty and no Tailscale adapter has a 100.x address).' }
40
46
  Say "Tailscale IP $tsIp"
41
47
 
42
48
  # --- Resource ceiling --------------------------------------------------------------------------------------------
@@ -222,10 +228,11 @@ $keep = Join-Path $installDir 'keepalive.ps1'
222
228
  Copy-Item (Join-Path $PSScriptRoot 'keepalive.ps1') $keep -Force
223
229
  $taskArgs = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$keep`" -Distro $Distro -Port $Port -TailscaleIp $tsIp" + $(if ($mirrored) { ' -Mirrored' } else { '' })
224
230
  $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $taskArgs
225
- $trigger = New-ScheduledTaskTrigger -AtLogOn -User "$env:USERDOMAIN\$env:USERNAME"
231
+ $trigger = if ($KeepaliveAtStartup) { New-ScheduledTaskTrigger -AtStartup } else { New-ScheduledTaskTrigger -AtLogOn -User "$env:USERDOMAIN\$env:USERNAME" }
232
+ $logonType = if ($KeepaliveAtStartup) { 'S4U' } else { 'Interactive' }
226
233
  $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1)
227
234
  # Highest: on NAT networking the task maintains a netsh portproxy, which needs an elevated token.
228
- $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel Highest
235
+ $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType $logonType -RunLevel Highest
229
236
  Register-ScheduledTask -TaskName 'computeshare-keepalive' -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Description 'computeshare agent keep-alive' -Force | Out-Null
230
237
  Start-ScheduledTask -TaskName 'computeshare-keepalive'
231
238
 
@@ -53,7 +53,15 @@ function branchOk(cfg, branch) {
53
53
  }
54
54
 
55
55
  // Does this workflow gate a pull request into the base branch? Returns '' when yes, else the reason it does not.
56
+ // With a release branch (a.releaseBranch, #6049) a workflow that gates a pull request into it, or runs on a push to it, also counts.
56
57
  function gateReason(ev, a) {
58
+ const why = gateReasonLane(ev, a);
59
+ if (!why || !a.releaseBranch || a.releaseBranch === a.baseBranch) return why;
60
+ if (ev.pull_request && branchOk(ev.pull_request, a.releaseBranch) && pathsOk(ev.pull_request, a.changed)) return '';
61
+ if (ev.push && !(Array.isArray(ev.push.tags) && !Array.isArray(ev.push.branches) && !Array.isArray(ev.push['branches-ignore'])) && branchOk(ev.push, a.releaseBranch) && pathsOk(ev.push, a.changed)) return '';
62
+ return why;
63
+ }
64
+ function gateReasonLane(ev, a) {
57
65
  const names = Object.keys(ev);
58
66
  if (ev.pull_request) {
59
67
  const c = ev.pull_request;
@@ -14,7 +14,7 @@ function parseArgs(argv) {
14
14
  const t = argv[i];
15
15
  const take = () => { if (i + 1 >= argv.length) throw new Error(`${t} needs a value`); return argv[++i]; };
16
16
  if (t === '--repo') o.repo = take(); else if (t === '--base') o.base = take(); else if (t === '--base-branch') o.baseBranch = take();
17
- else if (t === '--head-branch') o.headBranch = take(); else if (t === '--files') o.files = take().split(/[\n ]+/).filter(Boolean);
17
+ else if (t === '--head-branch') o.headBranch = take(); else if (t === '--release-branch') o.releaseBranch = take(); else if (t === '--files') o.files = take().split(/[\n ]+/).filter(Boolean);
18
18
  else if (t === '--files-from') o.files = fs.readFileSync(take(), 'utf8').split('\n').filter(Boolean);
19
19
  else if (t === '--out') o.out = take(); else if (t === '--plan') o.planFile = take(); else if (t === '--no-cache') o.noCache = true;
20
20
  else if (t === '--budget-minutes') o.budgetMinutes = Number(take()); else if (t === '--max-parallel') o.maxParallel = Number(take());
@@ -62,8 +62,9 @@ export function buildPlan(opts) {
62
62
  const tracked = git(repo, ['ls-files', '-z', '--cached', '--others', '--exclude-standard']).out.split('\0').filter(Boolean);
63
63
  const baseFiles = baseSha ? listAtRef(repo, baseRef) : [];
64
64
 
65
+ const releaseBranch = opts.releaseBranch && opts.releaseBranch !== baseBranch ? String(opts.releaseBranch) : '';
65
66
  const a = {
66
- repo, baseRef, baseSha, baseBranch, headBranch, headSha: head, changed, from, tracked, config, repository: repoSlug(repo),
67
+ repo, releaseBranch, baseRef, baseSha, baseBranch, headBranch, headSha: head, changed, from, tracked, config, repository: repoSlug(repo),
67
68
  defFiles(re) { return [...new Set([...baseFiles, ...tracked].filter((f) => re.test(f)))].sort(); },
68
69
  readDefs(f) {
69
70
  const baseText = baseSha ? readAtRef(repo, baseRef, f) : null;
@@ -76,7 +77,7 @@ export function buildPlan(opts) {
76
77
  const defRe = new RegExp([gha, gitlab, circle, azure, bitbucket, buildkite].map((m) => m.DEF_RE.source).join('|'));
77
78
  const defContents = a.defFiles(defRe).map((f) => { const d = a.readDefs(f); return `${f}\n${d.base}\n${d.head}`; }).join('\n--\n');
78
79
  const changeContents = changed.map((f) => `${f}:${fileHash(repo, f)}`);
79
- const key = sha256(JSON.stringify([PLAN_VERSION, repo, defContents, changeContents, baseSha, baseBranch, headBranch, hostClass(), config, process.version, process.env.FORGE_CI_LOCAL_SERVICES || '', fs.existsSync(path.join(repo, 'package.json')) ? sha256(fs.readFileSync(path.join(repo, 'package.json'))) : '']));
80
+ const key = sha256(JSON.stringify([PLAN_VERSION, repo, defContents, changeContents, baseSha, baseBranch, headBranch, hostClass(), config, releaseBranch, process.version, process.env.FORGE_CI_LOCAL_SERVICES || '', fs.existsSync(path.join(repo, 'package.json')) ? sha256(fs.readFileSync(path.join(repo, 'package.json'))) : '']));
80
81
  const cacheDir = path.join(opts.cacheDir || path.join(homeForgeDir(), 'ci-local', 'plans'));
81
82
  const cacheFile = path.join(cacheDir, key + '.json');
82
83
  if (!opts.noCache && fs.existsSync(cacheFile)) {
@@ -1134,5 +1134,16 @@ FIRST=$(printf '%s\n' "$OUT" | grep '^CI_LOCAL_JOB: pass' | head -n 1)
1134
1134
  has "4057: the cheapest known job runs first (small before big)" "$FIRST" "gha:ci:small"
1135
1135
  FORGE_TELEMETRY=off bash -c 'grep -q "wait_ms" "$0"' "$S" && ok || bad "4057: ci-local.sh forwards wait_ms to telemetry"
1136
1136
 
1137
+ # 6049: a workflow that only runs on a push to the release branch is a gate with --release-branch, not without it
1138
+ r=$(blank rel); mkdir -p "$r/.github/workflows"
1139
+ printf 'name: Release\non:\n push:\n branches: [main]\njobs:\n fmt:\n runs-on: ubuntu-latest\n steps:\n - run: echo fmt-check\n' > "$r/.github/workflows/release.yml"
1140
+ commit_base "$r"; echo x > "$r/a.txt"
1141
+ P=$(plan "$r" --base-branch dev --files "a.txt" | jq -c .)
1142
+ eq "release-only push workflow is not a lane gate without --release-branch" not-applicable "$(state "$P" gha:release)"
1143
+ P=$(plan "$r" --base-branch dev --files "a.txt" --release-branch main | jq -c .)
1144
+ eq "release-only push workflow is a gate with --release-branch" runnable "$(state "$P" gha:release:fmt)"
1145
+ P=$(plan "$r" --base-branch dev --files "a.txt" --release-branch other | jq -c .)
1146
+ eq "a different release branch does not select it" not-applicable "$(state "$P" gha:release)"
1147
+
1137
1148
  echo "ci-local.test.sh: $pass passed, $fail failed"
1138
1149
  [ "$fail" -eq 0 ]