forgedock 1.60.1 → 1.61.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 (70) hide show
  1. package/bin/config-schema.mjs +44 -1
  2. package/bin/engine/runlog.mjs +52 -0
  3. package/bin/engine-cli.mjs +9 -4
  4. package/bin/env/bench.mjs +38 -0
  5. package/bin/env/cli.mjs +134 -0
  6. package/bin/env/env.mjs +339 -0
  7. package/bin/forgedock.mjs +32 -3
  8. package/bin/help-text.mjs +2 -0
  9. package/bin/lean/ci-budget.mjs +3 -1
  10. package/bin/lean/ci-classify.mjs +74 -0
  11. package/bin/lean/ci-classify.test.mjs +147 -0
  12. package/bin/lean/ci-emit.mjs +175 -0
  13. package/bin/lean/ci-emit.test.mjs +177 -0
  14. package/bin/lean/ci-preflight.mjs +183 -0
  15. package/bin/lean/ci-preflight.test.mjs +122 -0
  16. package/bin/lean/ci-runner-health.mjs +213 -0
  17. package/bin/lean/ci-runner-health.test.mjs +113 -0
  18. package/bin/lean/ci-watch.mjs +79 -0
  19. package/bin/lean/ci-watch.test.mjs +80 -0
  20. package/bin/lean/depcache.mjs +38 -8
  21. package/bin/lean/deploy-stages.mjs +514 -0
  22. package/bin/lean/deploy-stages.test.mjs +580 -0
  23. package/bin/lean/effects.mjs +50 -0
  24. package/bin/lean/execution.mjs +8 -1
  25. package/bin/lean/lean.mjs +38 -6
  26. package/bin/lean/lean.test.mjs +61 -0
  27. package/bin/lean/release-deploy.mjs +12 -6
  28. package/bin/lean/release-flakes.mjs +16 -0
  29. package/bin/lean/release-flakes.test.mjs +15 -0
  30. package/bin/lean/release-gates.mjs +24 -1
  31. package/bin/lean/release-ledger.mjs +21 -0
  32. package/bin/lean/release-minutes-timing.test.mjs +57 -0
  33. package/bin/lean/release-minutes.mjs +98 -0
  34. package/bin/lean/release-promote.mjs +444 -0
  35. package/bin/lean/release-promote.test.mjs +470 -0
  36. package/bin/lean/release-rollback.mjs +14 -6
  37. package/bin/lean/release.mjs +31 -2
  38. package/bin/lean/sandbox-remote.mjs +11 -3
  39. package/bin/lean/testengine-recall.mjs +82 -0
  40. package/bin/lean/testengine-recall.test.mjs +103 -0
  41. package/bin/lean/testengine-shard.mjs +150 -0
  42. package/bin/lean/testengine-shard.test.mjs +111 -0
  43. package/bin/lean/testengine.mjs +486 -0
  44. package/bin/lean/testengine.test.mjs +303 -0
  45. package/bin/lean/verify-settle.test.mjs +156 -0
  46. package/bin/lean/verify.mjs +98 -3
  47. package/bin/pool/agent.mjs +57 -6
  48. package/bin/pool/ci-events.mjs +189 -0
  49. package/bin/pool/ci-events.test.mjs +143 -0
  50. package/bin/pool/docker.mjs +7 -0
  51. package/bin/pool/lane-tools.mjs +1 -0
  52. package/bin/pool/router.mjs +25 -1
  53. package/bin/pool/warm.mjs +1 -1
  54. package/bin/stats/ci-awareness.mjs +66 -0
  55. package/bin/stats/index.mjs +44 -3
  56. package/bin/stats/release-ledger.test.mjs +226 -0
  57. package/bin/stats/release.mjs +365 -1
  58. package/bin/stats/stats.test.mjs +36 -0
  59. package/docs/CI.md +31 -0
  60. package/docs/CONFIG.md +235 -2
  61. package/docs/ENV-LIBRARY.md +172 -0
  62. package/docs/STATS.md +43 -0
  63. package/docs/ci-events.md +88 -0
  64. package/docs/test-engine.md +98 -0
  65. package/package.json +1 -1
  66. package/pool/README.md +1 -0
  67. package/pool/image/entrypoint.sh +15 -3
  68. package/pool/services/docker-compose.yml +53 -0
  69. package/pool/services/git-mirror.sh +22 -0
  70. package/templates/github-actions/forge-env/action.yml +65 -0
@@ -287,6 +287,31 @@ export function makeHostProbe() {
287
287
  };
288
288
  }
289
289
 
290
+ /**
291
+ * #5718: the read and cancel seams of CI runs, on any `gh(args)` runner (the lane io and `forgedock ci cancel-superseded` share them).
292
+ * `checkSuites(sha)`: [{id, status, conclusion, app}] (status queued | in_progress | completed), for verify.settle.
293
+ * `branchRuns(branch)`: the queued and running runs, [{id, headSha, status, event, actor, createdAt}], for verify.cancel_superseded.
294
+ * `viewerLogin()`: the login this process acts as; an installation token has no user, so a bot sets FORGE_BOT_LOGIN.
295
+ */
296
+ export function ciRunSeams({ gh, repo }) {
297
+ const rows = (out) => String(out ?? "").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
298
+ return {
299
+ async checkSuites(sha) { return rows(await gh(["api", "--paginate", `repos/${repo}/commits/${sha}/check-suites`, "--jq", ".check_suites[] | {id, status, conclusion, app: .app.slug} | @json"])); },
300
+ async branchRuns(branch) {
301
+ const jq = ".workflow_runs[] | {id, headSha: .head_sha, status, event, actor: (.triggering_actor.login // .actor.login // null), createdAt: .created_at} | @json";
302
+ const out = [];
303
+ for (const status of ["queued", "in_progress"]) out.push(...rows(await gh(["api", "--paginate", `repos/${repo}/actions/runs?branch=${encodeURIComponent(branch)}&status=${status}&per_page=100`, "--jq", jq])));
304
+ return out;
305
+ },
306
+ async cancelRun(id) { await gh(["api", "-X", "POST", `repos/${repo}/actions/runs/${id}/cancel`]); },
307
+ async viewerLogin() {
308
+ const env = String(process.env.FORGE_BOT_LOGIN ?? "").trim();
309
+ if (env) return env;
310
+ try { return String(await gh(["api", "user", "--jq", ".login"])).trim() || null; } catch { return null; }
311
+ },
312
+ };
313
+ }
314
+
290
315
  /**
291
316
  * Required status checks for `lane` (#4158): the union of classic branch protection (contexts + checks) and the
292
317
  * repository rulesets that apply to the branch (`rules/branches/{lane}`, type required_status_checks). Each source
@@ -449,6 +474,30 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
449
474
  async rerunFailedJobs(runId) {
450
475
  await run("gh")(["run", "rerun", String(runId), "--failed", "-R", repo]);
451
476
  },
477
+ /** #5692: Actions runs of a head sha, newest first: [{id, status, conclusion}]. */
478
+ async runsForSha(sha) {
479
+ const j = JSON.parse(await run("gh")(["api", `repos/${repo}/actions/runs?head_sha=${encodeURIComponent(sha)}`]) || "{}");
480
+ return (j.workflow_runs ?? []).map((r) => ({ id: r.id, status: r.status, conclusion: r.conclusion ?? null }));
481
+ },
482
+ /** #5692: jobs of one run with their steps: [{id, name, status, conclusion, steps:[{name, status, conclusion, completed_at}]}]. */
483
+ async jobsOf(runId) {
484
+ const j = JSON.parse(await run("gh")(["api", `repos/${repo}/actions/runs/${encodeURIComponent(String(runId))}/jobs?per_page=100`]) || "{}");
485
+ return (j.jobs ?? []).map((x) => ({ id: x.id, name: x.name, status: x.status, conclusion: x.conclusion ?? null,
486
+ steps: (x.steps ?? []).map((s) => ({ name: s.name, status: s.status, conclusion: s.conclusion ?? null, completed_at: s.completed_at ?? null })) }));
487
+ },
488
+ /** #5692: `gh run cancel <id>`; throws when it cannot. */
489
+ async cancelRun(runId) { await run("gh")(["run", "cancel", String(runId), "-R", repo]); },
490
+ /** #5692: router long-poll GET /ci/events (FORGEDOCK_CI_EVENTS_URL + FORGEDOCK_CI_TOKEN); null when unconfigured or unreachable. */
491
+ async ciEventsWait({ repo: r = repo, sha, pr, since = 0, waitS = 0 }) {
492
+ const base = process.env.FORGEDOCK_CI_EVENTS_URL || process.env.FORGE_CI_EVENTS_URL;
493
+ if (!base) return null;
494
+ try {
495
+ const u = new URL(base);
496
+ u.search = new URLSearchParams({ repo: r, ...(sha ? { sha } : { pr: String(pr) }), since: String(since), wait: String(waitS) }).toString();
497
+ const res = await fetch(u, { headers: process.env.FORGEDOCK_CI_TOKEN ? { authorization: `Bearer ${process.env.FORGEDOCK_CI_TOKEN}` } : {}, signal: AbortSignal.timeout((waitS + 10) * 1000) });
498
+ return res.ok ? await res.json() : null;
499
+ } catch { return null; }
500
+ },
452
501
  /** Check runs on a commit (push-triggered CI): [{name, state: success|failure|pending, url, id, conclusion}], same mapping as checkStates; `id` orders attempts (#4387). */
453
502
  async commitChecks(sha) {
454
503
  const out = String(await run("gh")(["api", "--paginate", `repos/${repo}/commits/${sha}/check-runs`, "--jq", ".check_runs[] | {id, name, status, conclusion, url: .html_url} | @json"]));
@@ -458,6 +507,7 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
458
507
  return { name: c.name, state, url: c.url ?? null, id: c.id ?? null, conclusion: c.status === "completed" ? String(c.conclusion ?? "").toLowerCase() || null : null }; // #4387 id orders attempts; #4403 raw conclusion (skipped = not run)
459
508
  });
460
509
  },
510
+ ...ciRunSeams({ gh: run("gh"), repo }), // #5718: checkSuites, branchRuns, cancelRun, viewerLogin
461
511
  /**
462
512
  * #4270 verify.check_run: one completed check run on `sha` (`gh api -X POST repos/<repo>/check-runs`, JSON on stdin).
463
513
  * Needs a token allowed to create check runs (GitHub App, checks:write). Resolves {id, html_url}; throws on failure.
@@ -53,6 +53,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
53
53
  import { readFile, readdir } from "node:fs/promises";
54
54
  import { cpus, homedir, loadavg } from "node:os";
55
55
  import { dirname, join } from "node:path";
56
+ import { mergeRemoteLog } from "../engine/runlog.mjs";
56
57
  import { promisify } from "node:util";
57
58
  import { isLaneAlive, launchLane, writeAtomic } from "./batch.mjs";
58
59
  import { schedDir } from "./sched.mjs";
@@ -486,7 +487,13 @@ export function containerProvider({ batch, repo, image, gitDir, cacheDir = `${ho
486
487
  try { s = String(await docker(["inspect", "-f", "{{.State.Status}}", h.id])).trim(); } catch { return "gone"; }
487
488
  return ["running", "created", "restarting"].includes(s) ? "running" : "exited";
488
489
  },
489
- async fetchResult(h) { return readJson(batch.resultFile(h?.issue)); },
490
+ async fetchResult(h) {
491
+ const r = readJson(batch.resultFile(h?.issue));
492
+ if (!r || typeof r !== "object" || !r.runLog) return r;
493
+ const { runLog, ...rest } = r; // #5697: merge the lane's exported run log into the host run log
494
+ mergeRemoteLog(process.env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
495
+ return rest;
496
+ },
490
497
  async teardown(h) {
491
498
  try { await docker(["rm", "-f", h.id]); return true; } catch (e) {
492
499
  if (/no such container/i.test(errText(e))) return true;
package/bin/lean/lean.mjs CHANGED
@@ -81,7 +81,9 @@ import { unjustified } from "./enumerating.mjs";
81
81
  import { applyEnumerating, renameDuplicates, verifyApplied } from "./mechfix.mjs"; // #5348
82
82
  import { addLaneWorktree, DEFAULT_SPARSE_MAX_KB } from "./worktree.mjs";
83
83
  import { claimWarm, refillWarm, warmTreeCount, NO_HOOKS } from "./warmtree.mjs";
84
- import { parseVerify, runCiVerify, collectFailedLogs, capLogs, VERIFY_MODES, VERIFY_CHECK_NAME, verifyReport, ciGate, rerunFailedOnce, rerunTarget, splitFlaky } from "./verify.mjs";
84
+ import { ciSignal, cancelDecision, eventLog } from "./ci-watch.mjs";
85
+ import { classifyCiFailure } from "./ci-classify.mjs";
86
+ import { parseVerify, runCiVerify, collectFailedLogs, capLogs, VERIFY_MODES, VERIFY_CHECK_NAME, verifyReport, ciGate, rerunFailedOnce, rerunTarget, splitFlaky, cancelSuperseded } from "./verify.mjs";
85
87
  import { e2eSpecs, e2eWanted, uiInteractiveChanged, ownFailures, runE2eGate, fakedPaths, NO_TRIGGER } from "./e2e.mjs";
86
88
  import { transferToEpic } from "./acceptance.mjs";
87
89
  import { laneBackendId } from "./limits.mjs";
@@ -260,6 +262,7 @@ const defaultCredExec = (args) => {
260
262
  * @param {string} [o.reviewerModel] default claude-sonnet-5-5
261
263
  * @param {string} [o.fixModel] model of fresh fix-round sessions (#4363, forge.yaml lean.fix_model); default the reviewer model
262
264
  * @param {object} [o.builderRouting] forge.yaml lean.builder_routing/builder_mid_model (#4394): {mode: on (default)|off, midModel}
265
+ * @param {object|string} [o.ci] forge.yaml ci block or bare `fail_fast` policy (#5692): `deterministic` cancels the run on a downstream-class CI event; default off
263
266
  * @param {string} [o.followupsDefaultMilestone] forge.yaml followups.default_milestone (#4664): milestone of deferred follow-ups whose parent's milestone has shipped and has no next one
264
267
  * @param {string} [o.followupsRollupLabel] forge.yaml followups.rollup_issue_label (#5078): a repo's own open issue with this label is the post-deploy rollup when no marked one is open
265
268
  * @param {string} [o.sequenceRegenerate] forge.yaml lean.sequence.regenerate (#4386): snapshot generator for a schema-changing renumbered migration
@@ -2825,7 +2828,12 @@ export async function runCore(o) {
2825
2828
  files = await changedFiles();
2826
2829
  if (ciGateNames === undefined) ciGateNames = vcfg.workflow ? null : await ciGate({ io, lane, mergeWait, verify: vcfg });
2827
2830
  const verifyArgs = { io, branch, head, changedFiles: files, verify: vcfg, ciMaxMinutes, now, sleep, random, exclude: ciSeenRuns, gate: ciGateNames,
2828
- push: () => gitPush(["push", "-u", "origin", branch]),
2831
+ push: !vcfg.cancelSuperseded || vcfg.cancelSuperseded === "off" ? () => gitPush(["push", "-u", "origin", branch]) : async () => { // #5718: runs of the head this push replaces are cancelled
2832
+ const pushedAt = now(); await gitPush(["push", "-u", "origin", branch]);
2833
+ const c = await cancelSuperseded({ io, branch, head, mode: vcfg.cancelSuperseded, pushedAt });
2834
+ if (c.cancelled.length || c.failed.length) ev({ event: "CI_SUPERSEDED_CANCEL", head, cancelled: c.cancelled, failed: c.failed });
2835
+ },
2836
+ onSettle: (rec) => ev({ event: "CI_SETTLE", head, ...rec }), // #5718: verify.settle shadow/condition record
2829
2837
  onPoll: async () => { await renew(); onProgress({ event: "phase_paused", phase: "verify", detail: `CI verification pending on ${branch}` }); } };
2830
2838
  let v = await runCiVerify(verifyArgs);
2831
2839
  if (v.runId != null) ciSeenRuns.push(v.runId);
@@ -3679,15 +3687,15 @@ export async function runCore(o) {
3679
3687
  * logs, shared with ciVerify's verify.max_rounds budget; the fixed head is re-reviewed and pushed, then the wait restarts.
3680
3688
  * Returns null to wait again, or a terminal result (rounds exhausted, no session, no new commit, review failure).
3681
3689
  */
3682
- async function mergeFixRound(checks) {
3690
+ async function mergeFixRound(checks, ctx = null) { // ctx: a CI event (#5692) that started the round before its check completed
3683
3691
  // #4586: the failed runs are rerun once per head before a round is counted; the red check is waited out until the rerun reports (bounded).
3684
3692
  const rkey = `merge:${localHead}`, rerun = ciReruns.get(rkey);
3685
- if (!rerun && !isSplit) {
3693
+ if (!rerun && !isSplit && !ctx) { // a still-running run cannot be rerun (#5692)
3686
3694
  const rr = await rerunFailedOnce({ io, v: { failedChecks: checks, failures: checks.map((c) => ({ job: c.name })) } });
3687
3695
  ciReruns.set(rkey, { rr, urls: new Map(checks.map((c) => [c.name, c.url ?? null])), waits: 0 });
3688
3696
  ev({ event: "CI_FLAKE_RERUN", trigger: "merge", head: localHead, runs: rr.runs, jobs: rr.jobs, result: rr.ok ? "rerun-started" : "rerun-failed", detail: rr.detail });
3689
3697
  if (rr.ok) { await sleep(20000); return null; }
3690
- } else if (rerun?.rr.ok && rerun.waits < 20 && checks.every((c) => (c.url ?? null) === rerun.urls.get(c.name))) {
3698
+ } else if (!ctx && rerun?.rr.ok && rerun.waits < 20 && checks.every((c) => (c.url ?? null) === rerun.urls.get(c.name))) {
3691
3699
  rerun.waits++; await sleep(20000); return null; // still the attempt that was rerun
3692
3700
  }
3693
3701
  const flakyNames = checks.filter((c) => vcfg.flaky?.includes(c.name)).map((c) => c.name);
@@ -3699,6 +3707,7 @@ export async function runCore(o) {
3699
3707
  return await needsHuman(`Required check(s) failed on PR #${pr}: ${jobs.join(", ")}${ciRounds ? ` (after ${ciRounds} CI fix round(s))` : ""}`, OUTCOME_CODES.CI_RED);
3700
3708
  }
3701
3709
  const failures = await collectFailedLogs(io, checks);
3710
+ if (ctx && failures.length) failures[0] = { ...failures[0], log: [eventLog(ctx), failures[0].log].filter(Boolean).join("\n") };
3702
3711
  ciRounds++;
3703
3712
  T.decisions.push(`Required check(s) failed on PR #${pr} (${jobs.join(", ")}); builder resumed with the failed logs (round ${ciRounds}/${vcfg.maxRounds})`);
3704
3713
  ev({ event: "CI_FIX_ROUND", trigger: "merge", round: ciRounds, jobs, pr });
@@ -3815,6 +3824,21 @@ export async function runCore(o) {
3815
3824
  } else {
3816
3825
  let startedAt = now();
3817
3826
  let pollIndex = 0, gateHead = null, conflicted = false, notStartedLogged = false;
3827
+ // #5692: step-granular CI awareness. An event only starts a fix round early; the merge gate below is still the check states.
3828
+ const watching = policy !== "all" && !isSplit && Boolean(io.ciEventsWait || io.runsForSha);
3829
+ let sig = null, sigHead = null;
3830
+ const never = new Promise(() => {});
3831
+ const onCiEvent = async (e) => {
3832
+ const cls = e.class ?? classifyCiFailure({ step: e.step, lines: e.lines, test: e.test }).class;
3833
+ if (cls === "infra" || cls === "flaky-suspect") return null; // left to the check poll and its rerun
3834
+ const d = cancelDecision({ ...e, class: cls }, o.ci ?? o.failFast);
3835
+ ev({ event: "CI_AWARE", pr, head: localHead, source: e.source ?? "router", job: e.job ?? null, step: e.step ?? null, class: cls, event_ts: e.ts ?? null, aware_ts: new Date(now()).toISOString() });
3836
+ if (d.action === "cancel" && e.run_id && io.cancelRun) {
3837
+ let ok = true; try { await io.cancelRun(e.run_id); } catch { ok = false; }
3838
+ ev({ event: "CI_FAIL_FAST", pr, run: e.run_id, class: cls, cancelled: ok, reason: d.reason });
3839
+ }
3840
+ return await mergeFixRound([{ name: e.job ?? e.step ?? "ci", url: e.run_id ? `https://github.com/${repo}/actions/runs/${e.run_id}` : null }], e);
3841
+ };
3818
3842
  for (;;) {
3819
3843
  await renew();
3820
3844
  let states = [];
@@ -3856,8 +3880,16 @@ export async function runCore(o) {
3856
3880
  return await finish("ci-pending", `PR #${pr} still waiting on CI after ${ciMaxMinutes} min`, { pr });
3857
3881
  }
3858
3882
  onProgress({ event: "phase_paused", phase: "merge", detail: `CI pending on PR #${pr}` });
3859
- await sleep(ciPollDelayMs(pollIndex++, random));
3883
+ if (!watching) { await sleep(ciPollDelayMs(pollIndex++, random)); continue; }
3884
+ if (sigHead !== localHead) { sig?.stop(); sig = ciSignal({ repo, sha: localHead, pr, io, sleep, now }); sigHead = localHead; }
3885
+ const evt = await Promise.race([sig.next().then((v) => v ?? never), sleep(ciPollDelayMs(pollIndex++, random)).then(() => null)]);
3886
+ if (evt) {
3887
+ const r = await onCiEvent(evt);
3888
+ if (r) { sig.stop(); return r; }
3889
+ startedAt = now(); pollIndex = 0; // a fix round (or none): the head gets the full wait budget
3890
+ }
3860
3891
  }
3892
+ sig?.stop();
3861
3893
  if (conflicted) {
3862
3894
  const r = await baseSync("PR became conflicting while waiting for CI"); if (r) return r;
3863
3895
  continue; // wait again on the synced head with a fresh budget
@@ -2828,6 +2828,67 @@ describe("merge_wait policy", () => {
2828
2828
  assert.ok(traj(w)[0].includes("carried forward across the CI fix round"));
2829
2829
  });
2830
2830
 
2831
+ describe("#5692 CI events start the fix round before the check completes", () => {
2832
+ /** `build` stays pending until the builder's fix lands; `evts` is what the router has for the head. */
2833
+ const evWorld = (evts) => {
2834
+ const w = world(); w.cancelled = []; w.polls = 0;
2835
+ const sleep = w.io.sleep; w.io.sleep = async (ms) => (ms === WAIT ? sleep(ms) : new Promise((r) => setTimeout(r, 25))); // poll sleeps lose the race to a ready event
2836
+ w.io.requiredChecks = async () => ["build"];
2837
+ w.io.checkStates = async () => { w.polls++; return [{ name: "build", state: w.fixed ? "success" : "pending", url: RUN(77, 1) }]; };
2838
+ w.io.failedLogs = async () => { w.fixed = true; return "log"; };
2839
+ w.io.cancelRun = async (id) => { w.cancelled.push(id); };
2840
+ let sent = false;
2841
+ w.io.ciEventsWait = async () => (sent ? new Promise(() => {}) : (sent = true, { events: evts, next: evts.length }));
2842
+ return w;
2843
+ };
2844
+ const STEP = { seq: 1, type: "step_failed", job: "build", step: "pnpm test", run_id: "77", lines: ["FAIL boom.test.ts"], ts: "2026-11-15T10:00:00Z" };
2845
+ const SETUP = { ...STEP, step: "pnpm install", lines: ["ERR_PNPM_OUTDATED_LOCKFILE frozen-lockfile"] };
2846
+ const V1 = { ...parseVerify({}), maxRounds: 1 };
2847
+
2848
+ it("a step_failed while the check is still pending starts the fix round with the event lines, and merges only once the check is green", async () => {
2849
+ const w = evWorld([STEP]), p = fixPrompts(w), dir = tmpDir("core-");
2850
+ const r = await run(w, { dir, verify: V1 });
2851
+ assert.equal(r.terminalReason, "merged", r.reason);
2852
+ assert.equal(p.length, 1); assert.match(p[0], /FAIL boom\.test\.ts/); assert.match(p[0], /step: pnpm test/);
2853
+ assert.deepEqual(events(dir, "CI_FIX_ROUND").map((e) => e.trigger), ["merge"]);
2854
+ const aware = events(dir, "CI_AWARE"); assert.equal(aware.length, 1); assert.equal(aware[0].event_ts, "2026-11-15T10:00:00Z"); assert.equal(aware[0].source, "router");
2855
+ });
2856
+ it("fake clock: the fix round starts within 30 s of the step_failed while the check is still pending", async () => {
2857
+ const w = evWorld([STEP]), dir = tmpDir("core-");
2858
+ let pendingAtRound = null, sent = false;
2859
+ w.io.ciEventsWait = async () => (sent ? new Promise(() => {}) : (sent = true, { events: [{ ...STEP, ts: new Date(w.clock).toISOString() }], next: 1 })); // the step fails when the watcher starts
2860
+ w.io.sleep = async (ms) => { await new Promise((r) => setImmediate(r)); w.clock += ms; }; // fake clock; a sleep elapses as a macrotask, so a ready event wins the race before time passes
2861
+ w.io.failedLogs = async () => { pendingAtRound = !w.fixed; w.fixed = true; return "log"; };
2862
+ const r = await run(w, { dir, verify: V1 });
2863
+ assert.equal(r.terminalReason, "merged", r.reason); assert.equal(pendingAtRound, true, "round began while the check was pending");
2864
+ const a = events(dir, "CI_AWARE")[0], lag = Date.parse(a.aware_ts) - Date.parse(a.event_ts);
2865
+ assert.ok(lag >= 0 && lag <= 30000, `awareness lag ${lag} ms`);
2866
+ });
2867
+ it("merge gating unchanged: an event for a non-actionable class never merges while the required check is pending", async () => {
2868
+ const w = evWorld([{ ...STEP, lines: ["ECONNRESET registry.npmjs.org"], class: "infra" }]), dir = tmpDir("core-");
2869
+ let greenAt = null; w.io.checkStates = async () => { w.polls++; if (w.polls === 4) greenAt = w.merges.length; return [{ name: "build", state: w.polls >= 4 ? "success" : "pending", url: RUN(77, 1) }]; };
2870
+ const r = await run(w, { dir, verify: V1 });
2871
+ assert.equal(r.terminalReason, "merged", r.reason);
2872
+ assert.equal(greenAt, 0, "nothing merged before the check turned green"); assert.equal(w.merges.length, 1);
2873
+ assert.equal(events(dir, "CI_FIX_ROUND").length, 0);
2874
+ });
2875
+ it("a pending check at the wait budget never merges on events alone", async () => {
2876
+ const w = evWorld([{ ...STEP, class: "infra" }]); w.io.checkStates = async () => [{ name: "build", state: "pending", url: RUN(77, 1) }];
2877
+ const r = await run(w, { dir: tmpDir("core-"), verify: V1, ciMaxMinutes: 0 });
2878
+ assert.equal(r.terminalReason, "ci-pending"); assert.equal(w.merges.length, 0);
2879
+ });
2880
+ it("cancels the run only for a downstream class under fail_fast deterministic", async () => {
2881
+ const on = evWorld([SETUP]); await run(on, { dir: tmpDir("core-"), verify: V1, ci: { fail_fast: "deterministic" } });
2882
+ assert.deepEqual(on.cancelled, ["77"]);
2883
+ const dir = tmpDir("core-"), on2 = evWorld([SETUP]); await run(on2, { dir, verify: V1, ci: "deterministic" });
2884
+ assert.deepEqual(events(dir, "CI_FAIL_FAST").map((e) => [e.class, e.cancelled]), [["deterministic-setup", true]]);
2885
+ const off = evWorld([SETUP]); await run(off, { dir: tmpDir("core-"), verify: V1 });
2886
+ assert.deepEqual(off.cancelled, [], "policy off");
2887
+ const code = evWorld([STEP]); await run(code, { dir: tmpDir("core-"), verify: V1, ci: { fail_fast: "deterministic" } });
2888
+ assert.deepEqual(code.cancelled, [], "code class");
2889
+ });
2890
+ });
2891
+
2831
2892
  it("a rerun that reports a new attempt still red goes to the fix round and reaches the builder", async () => {
2832
2893
  const w = redBuild("failure", RUN(77, 2)); const p = fixPrompts(w), n = waits(w), dir = tmpDir("core-");
2833
2894
  await run(w, { dir, verify: { ...parseVerify({}), maxRounds: 1 } });
@@ -8,11 +8,14 @@
8
8
  * `{blocked}`, never a throw. The engine never sets a break-glass input and never reruns a deploy while a freeze is set (I26);
9
9
  * a run that concluded `success` while live is not the merge sha (or the expected digests) is a failed deploy (I28); no deploy
10
10
  * starts without a recorded rollback target (I9). Rationale: devdocs/decisions/5560-release-deploy.md.
11
+ * With forge.yaml `deploy.engine.enabled` (`ctx.config.deployEngine`, #5712) the step records the rollback target as above and then
12
+ * hands over to the stage machine in deploy-stages.mjs; without it nothing below changes.
11
13
  */
12
14
  import { fenced } from "./release-fence.mjs";
13
15
  import { buildDispatchArgs } from "./release-control.mjs";
14
16
  import { INFRA_SIGNATURES } from "./release-flakes.mjs";
15
17
  import { verifyStep, verifyConfigured } from "./release-verify.mjs";
18
+ import { engineOn, runStages } from "./deploy-stages.mjs";
16
19
 
17
20
  export const BOUNDS = { pollMs: 10_000, runPollMs: 20_000, defaultStageS: 3600, rerunMax: 2, maxAttempts: 3 };
18
21
  const json = (s) => JSON.parse(String(s || "null"));
@@ -44,7 +47,7 @@ export async function readTarget(io, cmd) {
44
47
  }
45
48
 
46
49
  /** The freeze variable's value ("" when unset or unreadable-as-absent). A gh failure means unset: `gh variable get` exits non-zero for a missing variable. */
47
- async function freezeValue(io, repo, name) {
50
+ export async function freezeValue(io, repo, name) {
48
51
  if (!name) return "";
49
52
  try { return String(await io.gh(["variable", "get", name, "--repo", repo])).trim(); } catch { return ""; }
50
53
  }
@@ -145,12 +148,14 @@ const stageS = (d) => (typeof d.stage_timeout_s === "number" ? d.stage_timeout_s
145
148
  /** @returns {Promise<{skipped: true}|{live: true, merge, run, reruns}|{blocked: true, reason, hold?}|{stopped: true, why}>} */
146
149
  export async function deployStep(ctx) {
147
150
  const { io, repo, state } = ctx;
148
- const d = ctx.config.deploy;
149
- if (!d?.pipelines || !Object.keys(d.pipelines).length) return { skipped: true };
151
+ const engine = engineOn(ctx.config.deployEngine); // #5712: the stage machine; off = everything below as before
152
+ const d = engine ? { live_release_command: ctx.config.deployEngine.live_release_command, ...(ctx.config.deploy ?? {}) } : ctx.config.deploy;
153
+ if (!engine && state.deploy?.engine) return { ...blocked("this release is being deployed by the deploy engine, which is not enabled here; resume it on a host whose forge.yaml has deploy.engine.enabled (the workflow pipeline is never started over a staged deploy)"), hold: { kind: "deploy-engine", label: "needs-agent" } };
154
+ if (!engine && (!d?.pipelines || !Object.keys(d.pipelines).length)) return { skipped: true };
150
155
  const b = { ...BOUNDS, ...(ctx.config.deployBounds ?? {}) };
151
- const pipe = d.pipelines[ctx.config.deployPipeline ?? "full"] ?? Object.values(d.pipelines)[0];
152
- if (!pipe?.workflow) return blocked("deploy.pipelines has no workflow for this release");
153
- let sha = state.steps["post-merge"]?.result?.merge ?? null;
156
+ const pipe = d.pipelines?.[ctx.config.deployPipeline ?? "full"] ?? Object.values(d.pipelines ?? {})[0];
157
+ if (!engine && !pipe?.workflow) return blocked("deploy.pipelines has no workflow for this release");
158
+ let sha = (engine ? ctx.config.deploySha : null) ?? state.steps["post-merge"]?.result?.merge ?? null;
154
159
  if (!sha) {
155
160
  const pr = state.steps["release-pr"]?.result?.pr;
156
161
  const v = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "state,mergeCommit"]));
@@ -171,6 +176,7 @@ export async function deployStep(ctx) {
171
176
  st.target = target; st.expected = expected; st.merge = sha; st.freezeBefore = await freezeValue(io, repo, d.freeze_variable); st.phase = "DEPLOYING";
172
177
  ctx.save();
173
178
  }
179
+ if (engine) return runStages(ctx, sha, d);
174
180
 
175
181
  await reconcile(ctx, d, pipe, sha);
176
182
  if (st.phase !== "LIVE_CHECKED" && st.phase !== "LIVE") {
@@ -99,6 +99,22 @@ export function repeatedFlakes(flakes, cfg, now = Date.now()) {
99
99
  return [...groups.values()].filter((g) => g.count >= cfg.quarantineAfter);
100
100
  }
101
101
 
102
+ /**
103
+ * Quarantine report for the test engine (#5710): the targets `repeatedFlakes` finds, each still run. `mode` `report`
104
+ * (default) keeps every one blocking; `non-blocking` is the repo's opt-in, and never applies to an unskippable class
105
+ * (as a check name, or as a path segment of the test file); `off` reports nothing.
106
+ * @returns {{target, check, test, count, evidence, blocking: boolean, why: string}[]}
107
+ */
108
+ export function quarantineReport(flakes, { mode = "report", quarantineAfter = 3, windowDays = 14, unskippable = UNSKIPPABLE_CLASSES } = {}, now = Date.now()) {
109
+ if (mode === "off") return [];
110
+ return repeatedFlakes(flakes, { quarantineAfter, windowDays }, now).map((g) => {
111
+ const locked = isUnskippable(g.target, unskippable) || unskippable.some((c) => String(g.test ?? "").split("/").includes(c));
112
+ const blocking = mode !== "non-blocking" || locked;
113
+ const why = locked ? "unskippable class: stays blocking" : blocking ? "report only: still blocking" : "non-blocking by the repo's opt-in: still run";
114
+ return { ...g, blocking, why };
115
+ });
116
+ }
117
+
102
118
  const markerFor = (target) => `<!-- ${FLAKE_MARKER} target=${target} -->`;
103
119
 
104
120
  /** The open `flake` issue of `target`, else a new one (label `flake`, evidence). @returns {{issue, created}|null} null for an unskippable target. */
@@ -114,3 +114,18 @@ describe("release flakes (#5568)", () => {
114
114
  assert.deepEqual(none, { reran: [], skipped: [] }); // no ci.rerun_budget_min: no rerun
115
115
  });
116
116
  });
117
+
118
+ describe("quarantineReport (#5710)", async () => {
119
+ const { quarantineReport, flakeEntry: fe } = await import("./release-flakes.mjs");
120
+ const now = Date.parse("2026-11-15T00:00:00Z");
121
+ const flips = (check, test, n) => Array.from({ length: n }, (_, i) => fe({ check, test, kind: "flip", sha: `s${i}`, runIds: [i], at: new Date(now - i * 3_600_000).toISOString() }));
122
+ it("reports repeated flakes as quarantined and still blocking by default", () => {
123
+ const q = quarantineReport([...flips("tests", "t/a.test.js", 3), ...flips("tests", "t/b.test.js", 2)], {}, now);
124
+ assert.deepEqual(q.map((x) => [x.target, x.count, x.blocking]), [["tests:t/a.test.js", 3, true]]);
125
+ });
126
+ it("non-blocking is opt-in and never reaches an unskippable class; off is empty", () => {
127
+ const all = [...flips("tests", "t/a.test.js", 3), ...flips("migration:up", null, 3), ...flips("tests", "suite/backup-restore/test_x.py", 3)];
128
+ assert.deepEqual(quarantineReport(all, { mode: "non-blocking" }, now).map((x) => x.blocking), [false, true, true]);
129
+ assert.deepEqual(quarantineReport(all, { mode: "off" }, now), []);
130
+ });
131
+ });
@@ -7,6 +7,8 @@
7
7
  * last `gates.demote_window` runs exceeds `gates.demote_fb_rate` percent is demoted to warn through `runControl("demote")`
8
8
  * with an expiry and an issue, unless it is on the safety allowlist. `release gates` reports runs/fails/FB share/minutes
9
9
  * (FB share = FB runs / runs, the same rate the demotion uses). No catalogue file: every entry point is a no-op, zero writes.
10
+ * CI evidence (#5711): a gate that re-runs work a required check already did names it in `evidence_check`; `evidenceSkips`
11
+ * says which of those gates an accepted attestation covers. A safety gate is never covered.
10
12
  */
11
13
  import { existsSync, readFileSync } from "node:fs";
12
14
  import { join } from "node:path";
@@ -24,7 +26,7 @@ export const DEMOTE_MODES = ["warn", "inconclusive"];
24
26
  export const SAFETY_DEFAULT = ["migration-immutability", "identity-preflight", "backup-freshness", "health-auto-restore"];
25
27
  export const GATE_PATHS_DEFAULT = ["scripts/deploy/**", "scripts/lib/**", "scripts/prod-smoke-test.sh", "**/gate-fixtures/**", "tests/gates/**"];
26
28
  export const REQUIRED = ["id", "protects_against", "where", "determinism", "pre_merge_artifact", "version", "mode", "owner", "review_by"];
27
- const OPTIONAL = ["on_uncertainty", "failure_triggers", "proportionality"];
29
+ const OPTIONAL = ["on_uncertainty", "failure_triggers", "proportionality", "evidence_check"];
28
30
  const DAY_MS = 86_400_000;
29
31
 
30
32
  /** @returns {string[]} findings for a parsed catalogue `{schema: 1, gates: [...]}`; empty when valid. */
@@ -81,6 +83,27 @@ export function parseGatesConfig(policy) {
81
83
  export const isSafetyGate = (gate, safety = SAFETY_DEFAULT) =>
82
84
  isUnskippable(String(gate)) || safety.some((s) => gate === s || String(gate).startsWith(`${s}:`) || String(gate).startsWith(`${s}/`));
83
85
 
86
+ /**
87
+ * CI-evidence side (#5711, release-promote.mjs): for every catalogue gate with an `evidence_check`, whether the attestation
88
+ * `evidence` ({commit, checks: [{name, conclusion}]}) covers it. `ok` is the promote verdict (`canPromote`): without it nothing
89
+ * is skipped. A safety gate always runs, whatever the evidence says. The catalogue mode of a gate is not changed.
90
+ * @returns {{gate: string, check: string, skip: boolean, why: string, record?: object}[]} `record` is the telemetry record of a skipped gate.
91
+ */
92
+ export function evidenceSkips(catalogue, evidence, { ok = false, safety = SAFETY_DEFAULT } = {}) {
93
+ const out = [];
94
+ for (const g of catalogue?.gates ?? []) {
95
+ const check = typeof g?.evidence_check === "string" ? g.evidence_check.trim() : "";
96
+ if (!g?.id || !check) continue;
97
+ const keep = (why) => out.push({ gate: String(g.id), check, skip: false, why });
98
+ if (isSafetyGate(String(g.id), safety)) { keep("safety gate: always runs"); continue; }
99
+ if (!ok) { keep("the evidence was not accepted"); continue; }
100
+ if (!(evidence?.checks ?? []).some((c) => c?.name === check && c.conclusion === "success")) { keep(`${check} is not in the attestation as success`); continue; }
101
+ const why = `${check} passed on ${String(evidence.commit).slice(0, 12)}`;
102
+ out.push({ gate: String(g.id), check, skip: true, why, record: gateRecord({ gate: g.id, outcome: "skip", evidence: `promote: ${why}` }) });
103
+ }
104
+ return out;
105
+ }
106
+
84
107
  /** One telemetry record, or null for an unknown gate or outcome. A TP/FB class needs a non-empty `evidence`, else `unknown`. */
85
108
  export function gateRecord({ gate, outcome, class: cls, evidence, minutes = 0, gate_sha: gateSha }) {
86
109
  if (!gate || !OUTCOMES.includes(outcome)) return null;
@@ -220,3 +220,24 @@ export async function recordTrain(ctx, rec, now = Date.now()) {
220
220
  const at = new Date(now).toISOString();
221
221
  return updateActive(ctx, ["train"], (active) => ({ patch: { train: { ...(active.train ?? {}), [rec.release ?? "-"]: { ...rec, lane: "train", rollout_invalidated: true, at } } }, control: { at, verb: "train", lane: "train", release: rec.release ?? null, state: rec.state ?? null, units: rec.units?.length ?? 0, rollout_invalidated: true } }));
222
222
  }
223
+
224
+ /**
225
+ * #5718: release state for `forgedock stats --release-ledger`. One record per managed release started at or after `sinceMs`:
226
+ * `{id, pr, startedAt, status, live, deployAttempts}` (read-only; a release without a readable state is skipped). The id
227
+ * carries the start time (`rYYYYMMDD-HHMMSS-n`), so older releases cost no read.
228
+ */
229
+ export async function releaseRecords(ctx, { sinceMs = 0 } = {}) {
230
+ const out = [];
231
+ for (const id of await listLedgers(ctx)) {
232
+ const m = /^r(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-/.exec(id);
233
+ if (m && Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]) < sinceMs) continue;
234
+ let s = null;
235
+ try { s = (await readLedger(ctx, id))?.state ?? null; } catch { s = null; }
236
+ if (!s) continue;
237
+ const pr = s.steps?.["release-pr"]?.result?.pr ?? s.pr ?? null;
238
+ const phase = String(s.deploy?.phase ?? "");
239
+ out.push({ id, pr: pr == null ? null : Number(pr), startedAt: s.startedAt ?? null, status: s.status ?? null,
240
+ live: ["live", "done"].includes(String(s.status ?? "").toLowerCase()) || phase.startsWith("LIVE"), deployAttempts: Number(s.deploy?.attempts) || 0 });
241
+ }
242
+ return out;
243
+ }
@@ -0,0 +1,57 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5718: Actions timing primitives of the release ledger (pure).
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { classifyStep, criticalJob, firstFailedStep, isSelfHosted, jobRan, jobSeconds, jobSetup, minuteShares, queueSeconds } from "./release-minutes.mjs";
7
+
8
+ const T = (s) => `2026-03-01T10:${s}Z`;
9
+ const job = (o = {}) => ({ name: "test", conclusion: "success", created_at: T("00:00"), started_at: T("00:30"), completed_at: T("05:30"), labels: ["ubuntu-latest"], runner_group_name: "GitHub Actions", steps: [], ...o });
10
+ const step = (name, a, b, conclusion = "success") => ({ name, conclusion, started_at: T(a), completed_at: T(b) });
11
+
12
+ describe("step classes (#5718)", () => {
13
+ it("classifies checkout, toolchain and dependency steps of every ecosystem by name", () => {
14
+ const want = {
15
+ checkout: ["Run actions/checkout@v4", "Checkout", "Checkout repository", "git clone the sources"],
16
+ toolchain: ["Run actions/setup-node@v4", "Run actions/setup-python@v5", "Run actions/setup-go@v5", "Set up Python", "Setup Node.js", "Set up Docker Buildx", "Run pnpm/action-setup@v4", "Install Rust toolchain", "rustup update stable", "Run astral-sh/setup-uv@v3"],
17
+ deps: ["Install dependencies", "npm ci", "Run npm install", "pnpm install --frozen-lockfile", "yarn install --immutable", "Run yarn", "pip install -r requirements.txt", "poetry install --no-root", "uv sync --frozen", "uv pip install -e .", "bundle install", "composer install", "go mod download", "cargo fetch", "dotnet restore", "Install Python dependencies", "Restore dependency cache", "Run actions/cache@v4"],
18
+ "image-build": ["Build and push image", "Run docker/build-push-action@v6", "docker build -t app .", "Build web image", "docker buildx bake"],
19
+ lint: ["Run lint", "eslint", "ruff check", "Check formatting", "Typecheck", "Lockfile is up to date", "Generated files drift"],
20
+ };
21
+ for (const [cls, names] of Object.entries(want)) for (const n of names) assert.equal(classifyStep(n), cls, n);
22
+ });
23
+ it("the runner's own steps, post steps and work steps are not setup", () => {
24
+ for (const n of ["Set up job", "Complete job", "Post Run actions/checkout@v4", "Post Install dependencies", "Run tests", "Roll out", "Smoke", "", null]) assert.equal(classifyStep(n), null, String(n));
25
+ });
26
+ it("jobSetup sums the seconds of each setup class", () => {
27
+ const j = job({ steps: [step("Set up job", "00:30", "00:32"), step("Run actions/checkout@v4", "00:32", "00:40"), step("Run actions/setup-node@v4", "00:40", "01:00"), step("npm ci", "01:00", "01:45"), step("Run actions/cache@v4", "01:45", "01:50"), step("Run tests", "01:50", "05:30")] });
28
+ assert.deepEqual(jobSetup(j), { checkout: 8, toolchain: 20, deps: 50, total: 78 });
29
+ assert.deepEqual(jobSetup(job()), { checkout: 0, toolchain: 0, deps: 0, total: 0 });
30
+ });
31
+ });
32
+
33
+ describe("job timing (#5718)", () => {
34
+ it("seconds, queue and self-hosted detection", () => {
35
+ assert.equal(jobSeconds(job()), 300); assert.equal(queueSeconds(job()), 30);
36
+ const skipped = job({ conclusion: "skipped", started_at: T("00:00"), completed_at: T("00:00") });
37
+ assert.equal(jobRan(skipped), false); assert.equal(queueSeconds(skipped), null); assert.equal(jobSeconds({}), 0);
38
+ assert.equal(isSelfHosted(job()), false);
39
+ assert.equal(isSelfHosted(job({ labels: ["self-hosted", "linux"] })), true);
40
+ assert.equal(isSelfHosted(job({ labels: ["big"], runner_group_name: "Default" })), true);
41
+ assert.equal(isSelfHosted(job({ labels: ["ubuntu-latest-8-cores"], runner_group_name: "Default Larger Runners" })), false);
42
+ });
43
+ it("minute shares split failed and cancelled job time", () => {
44
+ const s = minuteShares([job(), job({ conclusion: "failure" }), job({ conclusion: "cancelled", completed_at: T("10:30") }), job({ conclusion: "timed_out", completed_at: T("03:00") })]);
45
+ assert.deepEqual([s.seconds, s.failed, s.cancelled], [1350, 450, 600]);
46
+ assert.equal(s.failedShare, 450 / 1350); assert.equal(s.cancelledShare, 600 / 1350);
47
+ assert.deepEqual(minuteShares([]), { seconds: 0, failed: 0, cancelled: 0, failedShare: null, cancelledShare: null });
48
+ });
49
+ it("the critical job ends last; the first failed step is the earliest one", () => {
50
+ const a = job({ name: "lint", completed_at: T("02:00"), conclusion: "failure", steps: [step("Run lint", "00:40", "02:00", "failure")] });
51
+ const b = job({ name: "restore", completed_at: T("25:00"), conclusion: "failure", steps: [step("Run restore", "01:00", "25:00", "failure")] });
52
+ assert.equal(criticalJob([a, b, job({ conclusion: "skipped", started_at: T("30:00"), completed_at: T("30:00") })]).name, "restore");
53
+ assert.equal(criticalJob([]), null);
54
+ assert.deepEqual(firstFailedStep([b, a]), { job: "lint", step: "Run lint", cls: "lint", at: T("02:00") });
55
+ assert.equal(firstFailedStep([job()]), null);
56
+ });
57
+ });
@@ -100,3 +100,101 @@ export function waveReport(records, cfg = parseBudgetConfig(null)) {
100
100
  const verdict = waves.length < 3 ? `${waves.length}/3 waves measured` : m.within ? "within 25% of the model" : "OUTSIDE 25% of the model: tune budget.on_exceed and the nightly cadence";
101
101
  return { ...m, waves: waves.length, lines: [...m.lines, `total: model ${m.model} min, measured ${m.measured} min (${verdict})`] };
102
102
  }
103
+
104
+ // ---- Actions timing primitives (#5718, Forge CI W8): pure readers of runs/jobs/steps payloads, shared by `forgedock stats --release-ledger`. ----
105
+
106
+ const spanMs = (a, b) => { const d = Date.parse(b) - Date.parse(a); return Number.isFinite(d) && d > 0 ? d : 0; };
107
+ const FAILED = ["failure", "timed_out", "startup_failure"];
108
+ const lc = (v) => String(v ?? "").toLowerCase();
109
+ /** A job that ran (skipped jobs carry no time and no queue). */
110
+ export const jobRan = (j) => lc(j?.conclusion) !== "skipped" && spanMs(j?.started_at, j?.completed_at) > 0;
111
+ export const jobSeconds = (j) => spanMs(j?.started_at, j?.completed_at) / 1000;
112
+ /** Seconds a job waited for a runner (created -> started); null when the job never ran or the API gave no `created_at`. */
113
+ export const queueSeconds = (j) => (jobRan(j) && j.created_at ? spanMs(j.created_at, j.started_at) / 1000 : null);
114
+ /** Self-hosted by its labels, else by a runner group that is not GitHub's own. */
115
+ export function isSelfHosted(j) {
116
+ if ((j?.labels ?? []).some((l) => lc(l) === "self-hosted")) return true;
117
+ const g = lc(j?.runner_group_name);
118
+ return Boolean(g) && !/github actions|larger runners/.test(g);
119
+ }
120
+
121
+ /**
122
+ * Step classes, by step name only (the jobs API has no `uses`), ecosystem-neutral. Order matters: dependency installs are
123
+ * tested before toolchains so "Install Python dependencies" is `deps`. `Post ...` steps and the runner's own
124
+ * "Set up job" / "Complete job" are never setup.
125
+ */
126
+ export const STEP_CLASSES = Object.freeze([
127
+ ["checkout", /(^|[\s/])checkout(@|\s|$)|\bgit clone\b|\bfetch (the )?(repo|repository|sources?)\b/i],
128
+ ["deps", /\bnpm (ci|install|i)\b|\bpnpm (install|i)\b|\byarn( install)?\s*(--|$)|\bpip3? install\b|\bpoetry install\b|\buv (sync|pip install)\b|\bpipenv (install|sync)\b|\bbundle install\b|\bcomposer install\b|\bgo mod download\b|\bcargo fetch\b|\bdotnet restore\b|\binstall (\w+ )?(dependencies|deps|packages|requirements|modules)\b|\brestore (\w+ )?(dependencies|deps|cache)\b|actions\/cache|^cache\b|\bdependency cache\b/i],
129
+ ["image-build", /docker\/build-push-action|\bdocker (buildx )?build\b|\bbuildx bake\b|\bbuild (and push )?(the )?(\S+ )?(docker )?images?\b|\bimage build\b/i],
130
+ ["toolchain", /setup-[a-z0-9-]+(@|\s|$)|\baction-setup\b|^(run )?set ?up (?!job\b)\S+|\binstall (node|python|rust|go|java|ruby|php|deno|bun|toolchain)\b|\brustup\b|\bnvm (install|use)\b|\bpyenv\b|\basdf install\b|\btoolchain\b/i],
131
+ ["lint", /\b(lint\w*|eslint|ruff|flake8|prettier|format(ting)?( check)?|typecheck|type-check|tsc|mypy|lockfile|generated|drift|shellcheck)\b/i],
132
+ ]);
133
+ export const SETUP_CLASSES = Object.freeze(["checkout", "toolchain", "deps"]);
134
+ /** Failures of these classes are mechanical: no test ran, the fix is deterministic. */
135
+ export const MECHANICAL_CLASSES = Object.freeze(["checkout", "toolchain", "deps", "lint"]);
136
+ export function classifyStep(name) {
137
+ const n = String(name ?? "").trim();
138
+ if (!n || /^post\b/i.test(n) || /^(set up|complete) job$/i.test(n)) return null;
139
+ for (const [cls, re] of STEP_CLASSES) if (re.test(n)) return cls;
140
+ return null;
141
+ }
142
+ /** Seconds one job spent per setup class: {checkout, toolchain, deps, total}. */
143
+ export function jobSetup(j) {
144
+ const out = { checkout: 0, toolchain: 0, deps: 0, total: 0 };
145
+ for (const s of j?.steps ?? []) {
146
+ const cls = classifyStep(s?.name);
147
+ if (!SETUP_CLASSES.includes(cls)) continue;
148
+ const sec = spanMs(s.started_at, s.completed_at) / 1000;
149
+ out[cls] += sec; out.total += sec;
150
+ }
151
+ return out;
152
+ }
153
+ /** Job seconds by outcome: {seconds, failed, cancelled, failedShare, cancelledShare}; shares are null with no time. */
154
+ export function minuteShares(jobs) {
155
+ let seconds = 0, failed = 0, cancelled = 0;
156
+ for (const j of jobs ?? []) {
157
+ const s = jobSeconds(j), c = lc(j?.conclusion);
158
+ seconds += s;
159
+ if (FAILED.includes(c)) failed += s; else if (c === "cancelled") cancelled += s;
160
+ }
161
+ return { seconds, failed, cancelled, failedShare: seconds ? failed / seconds : null, cancelledShare: seconds ? cancelled / seconds : null };
162
+ }
163
+ /** The job that ends last: it sets the wall time of its run. Null when no job ran. */
164
+ export function criticalJob(jobs) {
165
+ let best = null;
166
+ for (const j of jobs ?? []) if (jobRan(j) && (!best || Date.parse(j.completed_at) > Date.parse(best.completed_at))) best = j;
167
+ return best;
168
+ }
169
+ /** The earliest failed step over `jobs`: {job, step, cls, at} (`cls` from classifyStep), or null. */
170
+ export function firstFailedStep(jobs) {
171
+ let best = null;
172
+ for (const j of jobs ?? []) for (const s of j?.steps ?? []) {
173
+ if (!FAILED.includes(lc(s?.conclusion)) || !s.completed_at) continue;
174
+ if (!best || Date.parse(s.completed_at) < Date.parse(best.at)) best = { job: j.name, step: s.name, cls: classifyStep(s.name), at: s.completed_at };
175
+ }
176
+ return best;
177
+ }
178
+ export const isFailedConclusion = (c) => FAILED.includes(lc(c));
179
+
180
+ const lines = (out) => String(out ?? "").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
181
+ const RUN_JQ = ".workflow_runs[] | {id, name, path, event, status, conclusion, head_sha, head_branch, run_attempt, created_at, run_started_at, updated_at, prs: [.pull_requests[]?.number], actor: (.triggering_actor.login // .actor.login // null)} | @json";
182
+ const JOB_JQ = ".jobs[] | {id, name, run_attempt, status, conclusion, created_at, started_at, completed_at, labels, runner_group_name, steps: [.steps[]? | {name, status, conclusion, started_at, completed_at}]} | @json";
183
+ /** The runs list API returns at most this many results per query; a fuller window is split in two. */
184
+ export const RUNS_QUERY_CAP = 1000;
185
+ const iso = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
186
+ /**
187
+ * Workflow runs created in [sinceMs, untilMs], optionally one branch and one event, paginated (`gh api --paginate`, so the
188
+ * caller's retry helper covers each page). A window that hits the API's 1000-result cap is halved and fetched again, so
189
+ * nothing is silently dropped. The runs API is slow (seconds per page): callers scope by branch and event.
190
+ */
191
+ export async function listRuns({ gh, repo, sinceMs, untilMs = Date.now(), branch = null, event = null, cap = RUNS_QUERY_CAP }) {
192
+ const q = `repos/${repo}/actions/runs?per_page=100&created=${iso(sinceMs)}..${iso(untilMs)}${branch ? `&branch=${encodeURIComponent(branch)}` : ""}${event ? `&event=${encodeURIComponent(event)}` : ""}`;
193
+ const runs = lines(await gh(["api", "--paginate", q, "--jq", RUN_JQ]));
194
+ if (runs.length < cap || untilMs - sinceMs < 2000) return runs;
195
+ const mid = Math.floor((sinceMs + untilMs) / 2000) * 1000;
196
+ const [a, b] = [await listRuns({ gh, repo, sinceMs, untilMs: mid, branch, event, cap }), await listRuns({ gh, repo, sinceMs: mid + 1000, untilMs, branch, event, cap })];
197
+ return [...b, ...a];
198
+ }
199
+ /** Jobs (with steps) of one run, every attempt, paginated. */
200
+ export const listRunJobs = async ({ gh, repo, runId }) => lines(await gh(["api", "--paginate", `repos/${repo}/actions/runs/${runId}/jobs?per_page=100&filter=all`, "--jq", JOB_JQ]));