forgedock 1.60.0 → 1.61.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 (78) 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/conformance.mjs +7 -1
  21. package/bin/lean/conformance.test.mjs +7 -1
  22. package/bin/lean/depcache.mjs +38 -8
  23. package/bin/lean/deploy-stages.mjs +514 -0
  24. package/bin/lean/deploy-stages.test.mjs +580 -0
  25. package/bin/lean/effects.mjs +50 -0
  26. package/bin/lean/execution.mjs +8 -1
  27. package/bin/lean/lean.mjs +61 -12
  28. package/bin/lean/lean.test.mjs +87 -0
  29. package/bin/lean/preflight.mjs +62 -1
  30. package/bin/lean/preflight.test.mjs +30 -1
  31. package/bin/lean/release-deploy.mjs +12 -6
  32. package/bin/lean/release-flakes.mjs +16 -0
  33. package/bin/lean/release-flakes.test.mjs +15 -0
  34. package/bin/lean/release-gates.mjs +24 -1
  35. package/bin/lean/release-ledger.mjs +21 -0
  36. package/bin/lean/release-minutes-timing.test.mjs +57 -0
  37. package/bin/lean/release-minutes.mjs +98 -0
  38. package/bin/lean/release-promote.mjs +444 -0
  39. package/bin/lean/release-promote.test.mjs +470 -0
  40. package/bin/lean/release-rollback.mjs +14 -6
  41. package/bin/lean/release.mjs +31 -2
  42. package/bin/lean/sandbox-remote.mjs +11 -3
  43. package/bin/lean/testengine-recall.mjs +82 -0
  44. package/bin/lean/testengine-recall.test.mjs +103 -0
  45. package/bin/lean/testengine-shard.mjs +150 -0
  46. package/bin/lean/testengine-shard.test.mjs +111 -0
  47. package/bin/lean/testengine.mjs +486 -0
  48. package/bin/lean/testengine.test.mjs +303 -0
  49. package/bin/lean/validate-catalog.mjs +16 -0
  50. package/bin/lean/validate-catalog.test.mjs +14 -1
  51. package/bin/lean/verify-settle.test.mjs +156 -0
  52. package/bin/lean/verify.mjs +98 -3
  53. package/bin/pool/agent.mjs +65 -6
  54. package/bin/pool/ci-events.mjs +183 -0
  55. package/bin/pool/ci-events.test.mjs +143 -0
  56. package/bin/pool/docker.mjs +7 -0
  57. package/bin/pool/lane-tools.mjs +32 -0
  58. package/bin/pool/router.mjs +21 -1
  59. package/bin/pool/warm.mjs +14 -3
  60. package/bin/stats/ci-awareness.mjs +66 -0
  61. package/bin/stats/index.mjs +44 -3
  62. package/bin/stats/release-ledger.test.mjs +226 -0
  63. package/bin/stats/release.mjs +365 -1
  64. package/bin/stats/stats.test.mjs +36 -0
  65. package/docs/CI.md +31 -0
  66. package/docs/CONFIG.md +235 -2
  67. package/docs/ENV-LIBRARY.md +172 -0
  68. package/docs/STATS.md +43 -0
  69. package/docs/ci-events.md +88 -0
  70. package/docs/test-engine.md +98 -0
  71. package/package.json +1 -1
  72. package/pool/README.md +1 -0
  73. package/pool/image/entrypoint.sh +15 -3
  74. package/pool/services/docker-compose.yml +53 -0
  75. package/pool/services/git-mirror.sh +22 -0
  76. package/scripts/acceptance-red-green.sh +5 -2
  77. package/scripts/acceptance-red-green.test.sh +11 -0
  78. package/templates/github-actions/forge-env/action.yml +65 -0
@@ -0,0 +1,143 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { test } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { appendFileSync, readdirSync, readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { CI_EVENT_TYPES, createCiEvents, validateEvent } from "./ci-events.mjs";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+
10
+ const ev = (type, extra = {}) => ({ type, repo: "o/r", sha: "abc", run_id: 7, job: "unit", ts: "2026-11-15T00:00:00Z", ...extra });
11
+ const fail = (status, key) => (e) => e.status === status && (key ? e.message.includes(key) : true);
12
+
13
+ test("all 6 event types validate; optional keys are kept", () => {
14
+ for (const t of CI_EVENT_TYPES) assert.equal(validateEvent(ev(t)).type, t);
15
+ const e = validateEvent(ev("test_failed", { pr: 12, step: "s", exit_code: 1, class: "code", lines: ["a"], test: { id: "t1", file: "f.py", line: 3, message: "boom" }, junk: 1 }));
16
+ assert.deepEqual([e.pr, e.step, e.exit_code, e.class, e.lines, e.test.id, e.junk], [12, "s", 1, "code", ["a"], "t1", undefined]);
17
+ });
18
+
19
+ test("missing repo/sha/ts/run_id/job and an unknown type are 400 naming the key", () => {
20
+ for (const k of ["repo", "sha", "ts", "run_id", "job"]) { const e = ev("step_failed"); delete e[k]; assert.throws(() => validateEvent(e), fail(400, k)); }
21
+ assert.throws(() => validateEvent(ev("nope")), fail(400, "type"));
22
+ assert.throws(() => validateEvent(ev("step_failed", { pr: "x" })), fail(400, "pr"));
23
+ assert.throws(() => validateEvent(ev("step_failed", { exit_code: "1" })), fail(400, "exit_code"));
24
+ assert.throws(() => validateEvent(null), fail(400));
25
+ });
26
+
27
+ test("more than 40 lines, a line over 500 chars, or more than 200 events is 413", () => {
28
+ assert.throws(() => validateEvent(ev("step_failed", { lines: Array(41).fill("x") })), fail(413, "lines"));
29
+ assert.equal(validateEvent(ev("step_failed", { lines: Array(40).fill("x".repeat(500)) })).lines.length, 40);
30
+ assert.throws(() => validateEvent(ev("step_failed", { lines: ["x".repeat(501)] })), fail(413, "lines"));
31
+ const s = createCiEvents({});
32
+ assert.throws(() => s.ingest(Array(201).fill(ev("job_started"))), fail(413));
33
+ assert.equal(s.ingest(Array(200).fill(ev("job_started"))).accepted, 200);
34
+ });
35
+
36
+ test("a bad event rejects the whole array and stores nothing", () => {
37
+ const s = createCiEvents({});
38
+ assert.throws(() => s.ingest([ev("job_started"), ev("step_failed", { sha: undefined })]), fail(400, "sha"));
39
+ assert.equal(s.size(), 0);
40
+ assert.equal(s.seq, 0);
41
+ });
42
+
43
+ test("seq is monotonic; sha and pr filters and since work", () => {
44
+ const s = createCiEvents({});
45
+ s.ingest([ev("job_started"), ev("step_failed", { sha: "def", pr: 5 }), ev("step_failed", { pr: 5 })]);
46
+ const all = s.query({ repo: "o/r", sha: "abc" });
47
+ assert.deepEqual(all.events.map((e) => e.seq), [1, 3]);
48
+ assert.equal(all.next, 3);
49
+ assert.deepEqual(s.query({ repo: "o/r", pr: 5 }).events.map((e) => e.sha), ["def", "abc"]);
50
+ assert.equal(s.query({ repo: "o/r", sha: "abc" }, 1).events.length, 1);
51
+ const none = s.query({ repo: "o/r", sha: "abc" }, 3);
52
+ assert.deepEqual([none.events.length, none.next], [0, 3]);
53
+ assert.equal(s.query({ repo: "other", sha: "abc" }).events.length, 0);
54
+ });
55
+
56
+ test("ring cap keeps the newest events; TTL expires old ones", () => {
57
+ let t = 1_000_000;
58
+ const s = createCiEvents({ cap: 5, ttlMs: 1000, now: () => t });
59
+ for (let i = 0; i < 8; i++) s.ingest(ev("step_started", { step: `s${i}` }));
60
+ assert.deepEqual(s.query({ repo: "o/r", sha: "abc" }).events.map((e) => e.step), ["s3", "s4", "s5", "s6", "s7"]);
61
+ t += 1500;
62
+ assert.equal(s.query({ repo: "o/r", sha: "abc" }).events.length, 0);
63
+ t += 61000;
64
+ s.query({ repo: "o/r", sha: "abc" });
65
+ assert.equal(s.size(), 0);
66
+ });
67
+
68
+ test("NDJSON is written, rotates on a new UTC day, and a restart reloads and resumes seq", () => {
69
+ const dir = tmpDir("ci-ev-");
70
+ let t = Date.parse("2026-11-15T10:00:00Z");
71
+ const a = createCiEvents({ dir, now: () => t });
72
+ a.ingest([ev("job_started"), ev("step_failed")]);
73
+ const [f] = readdirSync(dir);
74
+ assert.match(f, /^o_r-[0-9a-f]{8}\.ndjson$/);
75
+ assert.equal(readFileSync(join(dir, f), "utf8").trim().split("\n").length, 2);
76
+ t = Date.parse("2026-11-16T01:00:00Z");
77
+ a.ingest(ev("job_finished"));
78
+ assert.ok(readdirSync(dir).some((n) => /\.2026-11-15\.ndjson$/.test(n)), "yesterday's file rotated");
79
+ assert.equal(readFileSync(join(dir, f), "utf8").trim().split("\n").length, 1);
80
+ t += 3600000;
81
+ const b = createCiEvents({ dir, now: () => t });
82
+ assert.equal(b.seq, 3);
83
+ assert.deepEqual(b.query({ repo: "o/r", sha: "abc" }, 1).events.map((e) => e.type), ["step_failed", "job_finished"]);
84
+ assert.equal(b.ingest(ev("job_started")).seq, 4);
85
+ t += 25 * 3600000; // past the TTL
86
+ assert.equal(createCiEvents({ dir, now: () => t }).size(), 0);
87
+ });
88
+
89
+ test("a restart ignores a torn trailing line", () => {
90
+ const dir = tmpDir("ci-ev-");
91
+ createCiEvents({ dir }).ingest(ev("job_started"));
92
+ appendFileSync(join(dir, readdirSync(dir)[0]), '{"seq":2,"rec');
93
+ const b = createCiEvents({ dir });
94
+ assert.deepEqual([b.size(), b.seq], [1, 1]);
95
+ });
96
+
97
+ test("long-poll wakes within 200 ms of a matching POST and ignores non-matching ones", async () => {
98
+ const s = createCiEvents({});
99
+ const t0 = performance.now();
100
+ const p = s.wait({ repo: "o/r", sha: "abc" }, 0, 30);
101
+ setTimeout(() => { s.ingest(ev("step_failed", { sha: "zzz" })); s.ingest(ev("step_failed")); }, 20);
102
+ const r = await p;
103
+ assert.ok(performance.now() - t0 < 200);
104
+ assert.deepEqual([r.events.length, r.events[0].sha, r.next], [1, "abc", 2]);
105
+ const empty = await s.wait({ repo: "o/r", sha: "abc" }, 2, 0.05);
106
+ assert.deepEqual([empty.events.length, empty.next], [0, 2]);
107
+ assert.equal((await s.wait({ repo: "o/r", sha: "abc" }, 0, 30)).events.length, 1, "existing events return at once");
108
+ });
109
+
110
+ test("bench: 10000 events ingest at 2000+/s with under 50 MB RSS growth", () => {
111
+ const s = createCiEvents({ dir: tmpDir("ci-ev-") });
112
+ const batch = (i) => Array.from({ length: 200 }, (_, j) => ev("test_failed", { sha: `sha${(i + j) % 5}`, lines: ["AssertionError: x".repeat(4)], test: { id: `t${i}-${j}`, file: "a.py", line: 1, message: "m" } }));
113
+ const rss0 = process.memoryUsage().rss, t0 = performance.now();
114
+ for (let i = 0; i < 50; i++) s.ingest(batch(i));
115
+ const secs = (performance.now() - t0) / 1000, rate = 10000 / secs, grow = (process.memoryUsage().rss - rss0) / 1048576;
116
+ console.log(`# ci-events bench: ${rate.toFixed(0)} events/s, rss +${grow.toFixed(1)} MB`);
117
+ assert.equal(s.seq, 10000);
118
+ assert.ok(rate >= 2000, `${rate} events/s`);
119
+ assert.ok(grow < 50, `rss +${grow} MB`);
120
+ });
121
+
122
+ test("ingest classifies step_failed/test_failed without a class (#5690)", () => {
123
+ const ci = createCiEvents({ dir: tmpDir("ci-class") });
124
+ ci.ingest([
125
+ ev("step_failed", { lines: ["sh: tsc: command not found"] }),
126
+ ev("test_failed", { test: { id: "t1", message: "AssertionError: 1 !== 2" } }),
127
+ ev("step_failed", { lines: ["sh: tsc: command not found"], class: "infra" }),
128
+ ev("step_failed"),
129
+ ev("job_started", { lines: ["sh: tsc: command not found"] }),
130
+ ]);
131
+ const got = ci.query({ repo: "o/r", sha: "abc" }).events;
132
+ assert.deepEqual(got.map((e) => e.class), ["deterministic-setup", "code", "infra", undefined, undefined]);
133
+ });
134
+
135
+ test("ingest uses an injected classifier and flake ledger; a throwing classifier never rejects the batch (#5690)", () => {
136
+ let seen;
137
+ const ci = createCiEvents({ dir: tmpDir("ci-class2"), classify: (x) => { seen = x; return { class: "flaky-suspect" }; }, flakes: () => ["f"] });
138
+ ci.ingest(ev("step_failed", { lines: ["x"] }));
139
+ assert.deepEqual(seen.flakes, ["f"]);
140
+ assert.equal(ci.query({ repo: "o/r", sha: "abc" }).events[0].class, "flaky-suspect");
141
+ const bad = createCiEvents({ dir: tmpDir("ci-class3"), classify: () => { throw new Error("x"); } });
142
+ assert.equal(bad.ingest(ev("step_failed", { lines: ["x"] })).accepted, 1);
143
+ });
@@ -56,6 +56,13 @@ export const dockerCli = {
56
56
  return res;
57
57
  },
58
58
  async build(dir, tag, buildArgs = {}) { return docker(["build", "-q", "-t", tag, ...Object.entries(buildArgs).flatMap(([k, v]) => ["--build-arg", `${k}=${v}`]), dir], { timeoutMs: 45 * 60000 }); },
59
+ /** #5696: removes one lane worktree (/cache/work/<id>) from a cache volume. */
60
+ async removeWorkDir(volume, image, workDir) { await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", 'rm -rf -- "$1"', "sh", workDir], { timeoutMs: 120000 }); },
61
+ /** #5696: removes every /cache/work/* dir of a cache volume except the kept ones (full paths). */
62
+ async pruneWorkDirs(volume, image, keep) {
63
+ const script = 'for d in /cache/work/* /cache/work/.[!.]*; do [ -e "$d" ] || continue; for k in "$@"; do [ "$d" = "$k" ] && continue 2; done; rm -rf -- "$d"; done';
64
+ await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", script, "sh", ...keep], { timeoutMs: 120000 });
65
+ },
59
66
  /** Removes files the root-owned lane container wrote into a bind mount, using the lane image itself. */
60
67
  async wipe(dir, image) { await docker(["run", "--rm", "--network", "none", "-v", `${dir}:/d`, "--entrypoint", "sh", image, "-c", "rm -rf /d/* /d/.[!.]* 2>/dev/null; true"], { timeoutMs: 120000 }); },
61
68
  };
@@ -15,6 +15,7 @@ const apt = (...pkgs) => `RUN apt-get update && apt-get install -y --no-install-
15
15
  export const RECIPES = {
16
16
  "postgresql-client": { versioned: true, steps: (v) => [apt(v ? `postgresql-client-${v}` : "postgresql-client")] },
17
17
  python: { versioned: true, steps: (v) => [apt(v ? `python${v} python${v}-venv` : "python3 python3-venv")] },
18
+ xvfb: { versioned: false, steps: () => [apt("xvfb xauth")] }, // headless X for browser/GUI tests that call xvfb-run
18
19
  playwright: { versioned: true, steps: (v) => [`RUN npx --yes playwright${v ? `@${v}` : ""} install --with-deps chromium`] },
19
20
  // Example of a release-tarball tool; the version is required.
20
21
  promtool: { versioned: true, steps: (v) => [`RUN curl -fsSL https://github.com/prometheus/prometheus/releases/download/v${v ?? "2.54.1"}/prometheus-${v ?? "2.54.1"}.linux-amd64.tar.gz | tar -xz --strip-components=1 -C /usr/local/bin --wildcards '*/promtool'`] },
@@ -92,6 +93,12 @@ export function laneToolsDockerfile(baseImage, tools) {
92
93
  return [`FROM ${baseImage}`, "USER root", ...steps, ""].join("\n");
93
94
  }
94
95
 
96
+ /** One in-flight build per tag (shared by every launch and the warm pool), and the last failure per tag. */
97
+ const BUILDS = new Map();
98
+ const FAILED = new Map();
99
+ /** How long a failed build is reported instead of retried. */
100
+ export const LANE_BUILD_RETRY_MS = 10 * 60000;
101
+
95
102
  /**
96
103
  * The image a launch runs: `baseImage` when no tools; else the per-repo tag, reused when present, built from the base
97
104
  * otherwise. `docker.hasImage` and `docker.build(dir, tag, args)` are injected. Throws typed lane_tools.unknown_recipe
@@ -102,6 +109,31 @@ export async function resolveLaneImage({ tools = [], baseImage, docker, buildTim
102
109
  checkRecipes(tools);
103
110
  const tag = laneToolsTag(baseImage, tools);
104
111
  if (await docker.hasImage?.(tag)) return tag;
112
+ if (!BUILDS.has(tag)) BUILDS.set(tag, buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs }).finally(() => BUILDS.delete(tag)));
113
+ return BUILDS.get(tag); // concurrent callers share one build of a tag
114
+ }
115
+
116
+ /**
117
+ * Non-blocking form for a launch (the router waits ~120 s, a build can take many minutes): {image} when the tag exists,
118
+ * {building: true} after starting (or joining) a background build, {failed: message} for a build that failed in the last
119
+ * LANE_BUILD_RETRY_MS. Throws typed lane_tools.unknown_recipe.
120
+ */
121
+ export async function laneImageNow({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000, now = Date.now }) {
122
+ if (!tools.length) return { image: baseImage };
123
+ checkRecipes(tools);
124
+ const tag = laneToolsTag(baseImage, tools);
125
+ if (await docker.hasImage?.(tag)) return { image: tag };
126
+ const f = FAILED.get(tag);
127
+ if (f && now() - f.at < LANE_BUILD_RETRY_MS) return { failed: f.message };
128
+ if (!BUILDS.has(tag)) {
129
+ FAILED.delete(tag);
130
+ const p = buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs }).catch((e) => { FAILED.set(tag, { at: now(), message: e.message }); }).finally(() => BUILDS.delete(tag));
131
+ BUILDS.set(tag, p);
132
+ }
133
+ return { building: true, tag };
134
+ }
135
+
136
+ async function buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs }) {
105
137
  const dir = mkdtempSync(join(tmpdir(), "lane-tools-"));
106
138
  let timer;
107
139
  try {
@@ -8,6 +8,7 @@ import { execFile, spawn } from "node:child_process";
8
8
  import { promisify } from "node:util";
9
9
  import { join } from "node:path";
10
10
  import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
11
+ import { createCiEvents, MAX_WAIT_S } from "./ci-events.mjs";
11
12
  import { jsonStore } from "./store.mjs";
12
13
  import { versionOf } from "./version.mjs";
13
14
 
@@ -29,6 +30,17 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
29
30
  const store = jsonStore(join(cfg.state_dir, "router-state.json"), { agents: {}, sandboxes: {} });
30
31
  const agents = () => store.data.agents;
31
32
  const sbx = () => store.data.sandboxes;
33
+ // #5688: CI runner events (POST by a `ci` token or the fd token, GET long-poll by the fd token); state in <state_dir>/ci-events/.
34
+ const ciEvents = createCiEvents({ dir: join(cfg.state_dir, "ci-events"), now });
35
+ const ciOk = (req) => bearerOk(req, cfg.forgedock_token) || (cfg.ci_tokens ?? []).some((t) => bearerOk(req, t));
36
+ const ciQuery = (url) => {
37
+ const repo = url.searchParams.get("repo"), sha = url.searchParams.get("sha"), pr = url.searchParams.get("pr");
38
+ if (!repo || (!sha && !pr)) return { status: 400, body: { error: "repo and one of sha or pr are required" } };
39
+ if (pr && !/^\d{1,9}$/.test(pr)) return { status: 400, body: { error: "pr must be an integer" } };
40
+ const since = Number(url.searchParams.get("since") ?? 0), waitS = Number(url.searchParams.get("wait") ?? 0);
41
+ if (!Number.isInteger(since) || since < 0 || !Number.isFinite(waitS) || waitS < 0 || waitS > MAX_WAIT_S) return { status: 400, body: { error: `since must be a non-negative integer and wait 0-${MAX_WAIT_S}` } };
42
+ return { q: { repo, ...(sha ? { sha } : {}), ...(pr ? { pr: Number(pr) } : {}) }, since, waitS };
43
+ };
32
44
  const lane = { cpus: cfg.lane?.cpus ?? 2, mem_gb: cfg.lane?.mem_gb ?? 3 };
33
45
  const abandonMs = (cfg.abandon_after_s ?? 1800) * 1000;
34
46
  const codes = () => (store.data.codes ??= {});
@@ -190,12 +202,14 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
190
202
  const size = sizeFor(spec);
191
203
  const fits = (await capacities()).filter((c) => c.ok && !c.paused && c.cpus_free >= size.cpus && c.mem_free_gb >= size.mem_gb)
192
204
  .sort((a, b) => b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
205
+ let busy = null; // the last agent 503 (e.g. lane_tools image building): its body and Retry-After are passed back
193
206
  for (const c of fits) {
194
207
  const r = await agentCall(own(agents(), c.name), "POST", "/sandboxes", { spec: withForgeYaml(spec), ...size }, 120000);
195
- if (r.status === 503) continue; // raced with another launch; try the next host
208
+ if (r.status === 503) { busy = { r, name: c.name }; continue; } // raced with another launch, or still building; try the next host
196
209
  if (r.ok) { sbx()[spec.id] = { agent: c.name, issue: spec.issue ?? null, batch: spec.batch ?? null, createdAt: now(), touched: now() }; store.save(); }
197
210
  return { status: r.status, body: { ...agentBody(r, c.name), agent: c.name } };
198
211
  }
212
+ if (busy) return { status: 503, body: { ...agentBody(busy.r, busy.name), agent: busy.name }, retryAfter: busy.r.retryAfter ?? cfg.retry_after_s ?? 60 };
199
213
  return { status: 503, body: { error: "no host has a free reservation", lane: size }, retryAfter: cfg.retry_after_s ?? 60 };
200
214
  }
201
215
 
@@ -352,6 +366,11 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
352
366
  return { status: r.status, body: r.data };
353
367
  })],
354
368
  [route("GET", "/version"), fd(async () => ({ status: 200, body: versionOf(cfg.repo_root) }))],
369
+ [route("POST", "/ci/events"), { fn: async (_p, body) => ({ status: 202, body: ciEvents.ingest(body) }), auth: "ci" }], // #5688
370
+ [route("GET", "/ci/events"), fd(async (_p, _b, url) => {
371
+ const c = ciQuery(url);
372
+ return c.q ? { status: 200, body: await ciEvents.wait(c.q, c.since, c.waitS) } : c;
373
+ })],
355
374
  [route("POST", "/enroll"), { fn: async (_p, body) => enroll(body), auth: "none" }],
356
375
  [route("GET", "/bootstrap/install.ps1"), { fn: async (_p, _b, url) => ({ status: 200, body: bootstrapScript(url.searchParams.get("token"), url) }), auth: "enroll" }],
357
376
  [route("GET", "/bootstrap/bundle.tar.gz"), { fn: async () => ({ bundle: true }), auth: "enroll" }],
@@ -372,6 +391,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
372
391
  const p = match(req, url);
373
392
  if (!p) continue;
374
393
  if (r.auth === "forgedock" && !bearerOk(req, cfg.forgedock_token)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
394
+ if (r.auth === "ci" && !ciOk(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
375
395
  if (r.auth === "agent" && !agentFor(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
376
396
  if (r.auth === "enroll" && !enrollOk(url.searchParams.get("token"))) return send(res, 401, "unauthorized\n");
377
397
  const body = req.method === "POST" ? await readJson(req) : null;
package/bin/pool/warm.mjs CHANGED
@@ -23,13 +23,24 @@ export function makeWarm({ store, sb, own, now, launch, destroy, view, log = con
23
23
  function configure({ spec, cpus, mem_gb, limit = null, n }) {
24
24
  const key = keyOf(spec), want = Math.min(MAX_WARM, Number.isInteger(n) ? n : 0);
25
25
  if (want <= 0) { delete wanted()[key]; store.save(); return { key, n: 0 }; }
26
- wanted()[key] = { n: want, cpus, mem_gb, limit, spec: { image: spec.image ?? null, repo: spec.repo ?? null, cache: spec.cache ?? null, docker: Boolean(spec.docker), ...(spec.lane_tools?.length ? { lane_tools: spec.lane_tools } : {}) } };
26
+ wanted()[key] = { n: want, cpus, mem_gb, limit, spec: { image: spec.image ?? null, repo: spec.repo ?? null, cache: spec.cache ?? null, docker: Boolean(spec.docker), ...(spec.lane_tools?.length ? { lane_tools: spec.lane_tools } : {}), ...(spec.env_snapshots?.enabled ? { env_snapshots: spec.env_snapshots } : {}) } };
27
27
  store.save();
28
28
  return { key, n: want };
29
29
  }
30
30
  const list = () => recs().map((r) => ({ id: r.id, key: r.warm, state: r.state, ready: isReady(r), cpus: r.cpus, mem_gb: r.mem_gb }));
31
- /** Start sandboxes until each repo has its n (ready or still preparing). Refused launches (capacity) are retried on the next call. */
32
- async function replenish() {
31
+ /**
32
+ * Start sandboxes until each repo has its n (ready or still preparing). Refused launches (capacity) are retried on the next call.
33
+ * Single-flight: a sandbox counts as warm only once its launch returns, so concurrent passes (every lane launch, claim and
34
+ * reaper tick calls this) each saw 0 and over-filled the pool (11 for n=1 when launches were slow). A call during a pass
35
+ * joins it and schedules one more pass for config that changed meanwhile.
36
+ */
37
+ let inflight = null, again = false;
38
+ function replenish() {
39
+ if (inflight) { again = true; return inflight; }
40
+ inflight = (async () => { do { again = false; await replenishPass(); } while (again); })().finally(() => { inflight = null; });
41
+ return inflight;
42
+ }
43
+ async function replenishPass() {
33
44
  for (const [key, w] of Object.entries(wanted())) {
34
45
  for (let have = recs(key).length; have < w.n; have++) {
35
46
  const id = `warm-${key}-${randomBytes(3).toString("hex")}`;
@@ -0,0 +1,66 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5692: `forgedock stats --ci-awareness`. Per lane (one RUN_START slice of a run log): time from the failing step's
5
+ * completion (CI_AWARE `event_ts`) to the lane's awareness (`aware_ts`), CI fix rounds per PR and wall time per round
6
+ * (CI_FIX_ROUND to the next round, or to RUN_TERMINAL for the last). Grouped by engine version, so the lanes before and
7
+ * after the event-driven wait are separate rows. Local run logs only; no network, no model.
8
+ */
9
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { runsDir } from "./local-source.mjs";
12
+
13
+ const ms = (t) => { const v = Date.parse(t ?? ""); return Number.isFinite(v) ? v : null; };
14
+ const quant = (xs, q) => { if (!xs.length) return null; const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.ceil(q * s.length) - 1)]; };
15
+ const round1 = (x) => (x == null ? null : Math.round(x * 10) / 10);
16
+ const dist = (xs) => ({ n: xs.length, median: round1(quant(xs, 0.5)), p90: round1(quant(xs, 0.9)) });
17
+
18
+ /** Lanes of one parsed log: [{version, awareness_s: [], rounds: {pr: n}, round_wall_s: []}]. */
19
+ export function lanesOf(events) {
20
+ const lanes = [];
21
+ let cur = null;
22
+ const closeRound = (endTs) => { if (cur?.openRound != null && endTs != null) cur.round_wall_s.push((endTs - cur.openRound) / 1000); if (cur) cur.openRound = null; };
23
+ for (const e of events) {
24
+ const t = ms(e.ts);
25
+ if (e.event === "RUN_START") { closeRound(null); cur = { version: e.version ?? null, start: t, awareness_s: [], rounds: {}, round_wall_s: [], openRound: null }; lanes.push(cur); continue; }
26
+ if (!cur) continue;
27
+ if (e.event === "CI_AWARE") { const a = ms(e.aware_ts) ?? t, b = ms(e.event_ts); if (a != null && b != null && a >= b) cur.awareness_s.push((a - b) / 1000); }
28
+ else if (e.event === "CI_FIX_ROUND") { closeRound(t); const k = String(e.pr ?? "?"); cur.rounds[k] = (cur.rounds[k] ?? 0) + 1; cur.openRound = t; }
29
+ else if (e.event === "RUN_TERMINAL") closeRound(t);
30
+ }
31
+ return lanes.filter((l) => l.awareness_s.length || Object.keys(l.rounds).length || true);
32
+ }
33
+
34
+ /**
35
+ * Report over parsed logs `[{events}]`: per version, awareness latency (median/p90), rounds per PR and wall per round.
36
+ * `sinceMs` keeps only the lanes whose RUN_START is at or after it (`--since <date>`); a lane with no start time is dropped then.
37
+ */
38
+ export function ciAwarenessReport(logs, { sinceMs = null } = {}) {
39
+ const by = new Map();
40
+ for (const lg of logs) for (const l of lanesOf(lg)) {
41
+ if (sinceMs != null && !(l.start >= sinceMs)) continue;
42
+ const g = by.get(l.version ?? "unknown") ?? { version: l.version ?? "unknown", lanes: 0, awareness_s: [], rounds_per_pr: [], round_wall_s: [] };
43
+ g.lanes++; g.awareness_s.push(...l.awareness_s); g.round_wall_s.push(...l.round_wall_s);
44
+ g.rounds_per_pr.push(...Object.values(l.rounds));
45
+ by.set(g.version, g);
46
+ }
47
+ const versions = [...by.values()].sort((a, b) => String(a.version).localeCompare(String(b.version), undefined, { numeric: true }))
48
+ .map((g) => ({ version: g.version, lanes: g.lanes, awareness_s: dist(g.awareness_s), rounds_per_pr: { ...dist(g.rounds_per_pr), mean: g.rounds_per_pr.length ? round1(g.rounds_per_pr.reduce((a, b) => a + b, 0) / g.rounds_per_pr.length) : null }, round_wall_s: dist(g.round_wall_s), event_driven: g.awareness_s.length > 0 }));
49
+ const all = [...by.values()], aw = all.flatMap((g) => g.awareness_s), rp = all.flatMap((g) => g.rounds_per_pr), rw = all.flatMap((g) => g.round_wall_s);
50
+ return { total: { lanes: all.reduce((n, g) => n + g.lanes, 0), awareness_s: dist(aw), rounds_per_pr: { ...dist(rp), mean: rp.length ? round1(rp.reduce((a, b) => a + b, 0) / rp.length) : null }, round_wall_s: dist(rw) }, versions };
51
+ }
52
+
53
+ /** Parse the `*.jsonl` run logs of `dir` (optionally only this repo's `<owner>__<repo>__<issue>.jsonl`); unreadable files are skipped. */
54
+ export function readCiLogs(dir = runsDir(), repo = null) {
55
+ if (!existsSync(dir)) return [];
56
+ const slug = repo ? `${repo.replace("/", "__")}__` : null;
57
+ return readdirSync(dir).sort().filter((f) => f.endsWith(".jsonl") && (!slug || f.startsWith(slug))).flatMap((f) => {
58
+ try { return [readFileSync(join(dir, f), "utf8").split("\n").flatMap((l) => { try { return l.trim() ? [JSON.parse(l)] : []; } catch { return []; } })]; } catch { return []; }
59
+ });
60
+ }
61
+
62
+ const fmt = (d, u = "s") => (d.n ? `median ${d.median}${u}, p90 ${d.p90}${u} (n=${d.n})` : "no data");
63
+ export function renderCiAwareness(r) {
64
+ const row = (x, label) => [`${label}${x.lanes != null ? ` (${x.lanes} lanes)` : ""}`, ` awareness latency: ${fmt(x.awareness_s)}`, ` CI rounds per PR: ${x.rounds_per_pr.n ? `median ${x.rounds_per_pr.median}, mean ${x.rounds_per_pr.mean}, p90 ${x.rounds_per_pr.p90} (n=${x.rounds_per_pr.n})` : "no data"}`, ` wall per round: ${fmt(x.round_wall_s)}`].join("\n");
65
+ return ["CI awareness (#5692)", row(r.total, "all"), ...r.versions.map((v) => row(v, `version ${v.version}${v.event_driven ? " [event-driven]" : ""}`))].join("\n");
66
+ }
@@ -17,11 +17,12 @@ import { renderCompact, renderJson, renderMarkdown } from "./render.mjs";
17
17
  import { buildCard, renderCardMarkdown, renderCardPng, renderCardSvg } from "./card.mjs";
18
18
  import { edgeQuery, parseEdge, verdictMix, contextPackAb, renderContextAb, builderTierReport, renderTiers, exploreAb, renderExploreAb, laneProfileReport, renderLaneProfiles } from "./query.mjs";
19
19
  import { batchEfficiency, windowEfficiency, compareEfficiency, formatEfficiencyLines, formatCompareLines, parseWindows } from "./efficiency.mjs";
20
- import { releaseMetrics, renderReleaseMetrics, metricsComment, postMetrics } from "./release.mjs";
20
+ import { releaseMetrics, renderReleaseMetrics, metricsComment, postMetrics, runReleaseLedger, parseLedgerConfig, ledgerSince } from "./release.mjs";
21
21
  import { experimentReport, renderExperiment } from "./experiment.mjs";
22
22
  import { readExperiment } from "../experiment.mjs";
23
23
  import { compoundingReport, gatherCompounding, renderCompounding, DEFAULT_BUCKETS, DEFAULT_WINDOW_MS } from "./compounding.mjs";
24
24
  import { poolUtilisation, formatPoolLines } from "./pool.mjs";
25
+ import { ciAwarenessReport, readCiLogs, renderCiAwareness } from "./ci-awareness.mjs";
25
26
  import { gatherIssues, selfFiledReport, renderSelfFiled } from "./selffiled.mjs";
26
27
  import { firstReviewReport, renderFirstReview } from "./first-review.mjs";
27
28
  import { firstMergeReport, gatherFirstRunIssues, medianMinutes, renderFirstMerge } from "./firstmerge.mjs";
@@ -40,6 +41,7 @@ export const HELP = `Usage: forgedock stats [--since <version|date>] [--repo <ow
40
41
  forgedock stats --experiment <id> [--require-met] [--min-n N] [--repo <owner/repo>] [--json]
41
42
  forgedock stats --by version [--post-metrics <pr>] [--min-n N] [--repo <owner/repo>] [--json]
42
43
  forgedock stats --pool [--window 7d,30d] [--repo <owner/repo>] [--json]
44
+ forgedock stats --ci-awareness [--repo <owner/repo>] [--since <date>] [--json]
43
45
  forgedock stats --first-review [--repo <owner/repo>] [--since <date>] [--min-n 20] [--json]
44
46
  forgedock stats --first-merge [--repo <owner/repo>[,<owner/repo>...]] [--json]
45
47
  forgedock stats --self-filed [--repo <owner/repo>] [--since <date>] [--json]
@@ -49,6 +51,8 @@ export const HELP = `Usage: forgedock stats [--since <version|date>] [--repo <ow
49
51
  forgedock stats --efficiency [--batch <id>] [--window 7d,30d] [--compare <date|version>] [--offline] [--repo <owner/repo>] [--json]
50
52
  forgedock stats --card [--week|--month] [--include-repo-names] [--public-repo] [--out <dir>] [--repo <owner/repo>]
51
53
  forgedock stats --depth [--since <version|date>] [--min-n N] [--offline] [--repo <owner/repo>] [--json]
54
+ forgedock stats --release-ledger [--repo <owner/repo>] [--since <date|21d>] [--baseline save|compare] [--baseline-file <path>]
55
+ [--deploy-workflow <name|file>] [--release-head <branch|any>] [--no-cache] [--json]
52
56
 
53
57
  Version-over-version report: Cost, Time, Flow, Review funnel, Gates and Issue flow per (version, repo), with a
54
58
  delta against the previous version and a low-n flag for samples under 10. Missing data prints n/a.
@@ -96,6 +100,8 @@ Explorer A/B (forge#4418; local run logs only, every run of each log, no GitHub
96
100
  lean.explore mode (on, off), plus the same issues run in both modes; --json for JSON
97
101
 
98
102
  Pool (forge#4549; local batch reports, no gh):
103
+ --ci-awareness median/p90 CI awareness latency, CI rounds per PR and wall per round, per engine version, from local run logs (#5692);
104
+ --since <date> keeps only the lanes started on/after that date
99
105
  --pool remote lane minutes, lanes and share per pool agent over --window (default 7d,30d)
100
106
 
101
107
  Efficiency (forge#4402; local batch dirs and run logs, gh only for merged issues' bodies, labels and probes):
@@ -165,7 +171,7 @@ Lane profile baseline (forge#4436; local run logs only, every run of each issue,
165
171
  export function experimentExit(opts, report) { return opts.requireMet && report.targets_met !== true ? 1 : 0; }
166
172
 
167
173
  export function parseArgs(argv) {
168
- const o = { card: false, week: false, month: false, includeRepoNames: false, publicRepo: false, out: null, depth: false, conformanceOutcomes: false, windowDays: null, since: null, repo: null, edge: null, milestone: null, contextAb: false, exploreAb: false, tiers: false, compounding: false, selfFiled: false, origin: false, firstMerge: false, bucket: null, laneProfile: false, issues: null, efficiency: false, pool: false, batch: null, windows: null, compare: null, by: null, experiment: null, emitEvent: false, requireMet: false, postMetrics: null, offline: false, json: false, refresh: false, compact: false, local: true, cache: true, minN: DEFAULT_MIN_N, releaseTimes: null, help: false };
174
+ const o = { card: false, week: false, month: false, includeRepoNames: false, publicRepo: false, out: null, depth: false, conformanceOutcomes: false, windowDays: null, since: null, repo: null, edge: null, milestone: null, contextAb: false, exploreAb: false, tiers: false, compounding: false, selfFiled: false, origin: false, firstMerge: false, bucket: null, laneProfile: false, issues: null, efficiency: false, pool: false, ciAwareness: false, batch: null, windows: null, compare: null, by: null, experiment: null, emitEvent: false, requireMet: false, postMetrics: null, offline: false, json: false, refresh: false, compact: false, local: true, cache: true, minN: DEFAULT_MIN_N, releaseTimes: null, help: false };
169
175
  const val = (i, name) => {
170
176
  const v = argv[i + 1];
171
177
  if (v == null || v.startsWith("--")) throw new Error(`${name} needs a value`);
@@ -200,6 +206,12 @@ export function parseArgs(argv) {
200
206
  else if (name === "--efficiency") o.efficiency = true;
201
207
  else if (name === "--depth") o.depth = true;
202
208
  else if (name === "--pool") o.pool = true;
209
+ else if (name === "--release-ledger") o.releaseLedger = true;
210
+ else if (name === "--baseline") { const v = take(); if (v !== "save" && v !== "compare") throw new Error("--baseline must be save or compare"); o.baseline = v; }
211
+ else if (name === "--baseline-file") o.baselineFile = take();
212
+ else if (name === "--deploy-workflow") o.deployWorkflow = take();
213
+ else if (name === "--release-head") o.releaseHead = take();
214
+ else if (name === "--ci-awareness") o.ciAwareness = true;
203
215
  else if (name === "--batch") { const v = take(); if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(v)) throw new Error(`invalid --batch id: ${v}`); o.batch = v; }
204
216
  else if (name === "--window") o.windows = parseWindows(take());
205
217
  else if (name === "--compare") { // #4491
@@ -230,7 +242,7 @@ export function parseArgs(argv) {
230
242
  }
231
243
  if ((o.week || o.month || o.includeRepoNames || o.publicRepo || o.out) && !o.card) throw new Error("--week, --month, --include-repo-names, --public-repo and --out need --card");
232
244
  if (o.week && o.month) throw new Error("--week and --month are mutually exclusive");
233
- if (o.card && (o.depth || o.pool || o.efficiency || o.compounding || o.selfFiled || o.conformanceOutcomes || o.contextAb || o.exploreAb || o.tiers || o.laneProfile || o.edge || o.milestone || o.experiment || o.by)) throw new Error("--card cannot be combined with another query mode");
245
+ if (o.card && (o.depth || o.pool || o.ciAwareness || o.efficiency || o.compounding || o.selfFiled || o.conformanceOutcomes || o.contextAb || o.exploreAb || o.tiers || o.laneProfile || o.edge || o.milestone || o.experiment || o.by)) throw new Error("--card cannot be combined with another query mode");
234
246
  if (o.card && (o.week || o.month) && o.since) throw new Error("--week/--month and --since are mutually exclusive");
235
247
  if (o.batch && !o.efficiency) throw new Error("--batch and --window need --efficiency");
236
248
  if (o.windows && !o.efficiency && !o.pool && !o.compounding) throw new Error("--batch and --window need --efficiency");
@@ -241,6 +253,7 @@ export function parseArgs(argv) {
241
253
  if ((o.replay || o.enforceDomains || o.riskPaths) && !o.conformanceOutcomes) throw new Error("--replay, --enforce-domains and --risk-paths need --conformance-outcomes");
242
254
  if ((o.enforceDomains || o.riskPaths) && !o.replay) throw new Error("--enforce-domains and --risk-paths need --replay");
243
255
  if (o.postMetrics && !o.by) throw new Error("--post-metrics needs --by version");
256
+ if ((o.baseline || o.baselineFile || o.deployWorkflow || o.releaseHead) && !o.releaseLedger) throw new Error("--baseline, --baseline-file, --deploy-workflow and --release-head need --release-ledger");
244
257
  return o;
245
258
  }
246
259
 
@@ -350,6 +363,21 @@ export function readAlertConfig(cwd = process.cwd()) {
350
363
  return out;
351
364
  }
352
365
 
366
+ /** forge.yaml `stats.ledger_*` (+ `branches.staging` as the default release head) for `--release-ledger`. */
367
+ export function readLedgerConfig(cwd = process.cwd()) {
368
+ try { const y = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8")); return parseLedgerConfig(y?.stats, y?.branches); } catch { return parseLedgerConfig(null, null); }
369
+ }
370
+
371
+ /** Release state of a managed repo (`release.managed: true`) from its GitHub ledger; [] otherwise or when it cannot be read. */
372
+ async function managedReleaseRecords(gh, repo, sinceMs, cwd = process.cwd()) {
373
+ try {
374
+ if (String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.release?.managed ?? "").trim().toLowerCase() !== "true") return [];
375
+ const { releaseRecords } = await import("../lean/release-ledger.mjs");
376
+ const api = async (_method, path) => { try { return JSON.parse(await gh(["api", path])); } catch (e) { if (/HTTP 404/.test(String(e?.stderr ?? e?.message ?? ""))) e.status = 404; throw e; } };
377
+ return await releaseRecords({ io: { api }, repo }, { sinceMs });
378
+ } catch { return []; }
379
+ }
380
+
353
381
  /** forge.yaml `branding.show_attribution` (default true): the card footer link. */
354
382
  export function readAttribution(cwd = process.cwd()) {
355
383
  try { return String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.branding?.show_attribution ?? "true") !== "false"; } catch { return true; }
@@ -388,6 +416,11 @@ export async function buildReport(opts, deps = {}) {
388
416
  if (opts.releaseTimes) releaseTimes = parseReleaseTimes(readFileSync(opts.releaseTimes, "utf8"));
389
417
  else if (deps.releaseTimes) releaseTimes = deps.releaseTimes;
390
418
  else releaseTimes = gitTagTimes();
419
+ if (opts.ciAwareness) { // #5692: local run logs only
420
+ const p = parseSince(opts.since);
421
+ if (p.sinceVersion) throw new Error("--ci-awareness: --since must be a date (YYYY-MM-DD)");
422
+ return { repo, query: { ci_awareness: ciAwarenessReport(readCiLogs(deps.runsDir ?? runsDir(env), repo), { sinceMs: p.sinceMs ?? null }) } };
423
+ }
391
424
  if (opts.pool) { // forge#4549: local batch reports only
392
425
  const pool = poolUtilisation({ batchRoot: deps.batchRoot ?? batchRoot(env), repo, windows: opts.windows ?? parseWindows("7d,30d"), now: deps.now?.() ?? Date.now() });
393
426
  return { repo, query: { pool } };
@@ -502,6 +535,13 @@ export async function runStats(argv, deps = {}) {
502
535
  process.stderr.write(`forgedock stats: could not resolve a valid owner/repo (pass --repo owner/repo)\n`);
503
536
  return 2;
504
537
  }
538
+ if (opts.releaseLedger) { // #5718: its own read path (Actions runs/jobs/steps), no telemetry crawl
539
+ try {
540
+ const gh = deps.gh ?? defaultGh;
541
+ const ledger = deps.ledger ?? await managedReleaseRecords(gh, opts.repo, ledgerSince(opts.since, deps.now?.() ?? Date.now()));
542
+ return await runReleaseLedger(opts, { gh, config: deps.ledgerConfig ?? readLedgerConfig(), ...deps, ledger });
543
+ } catch (err) { process.stderr.write(`forgedock stats: ${err.message}\n`); return 1; }
544
+ }
505
545
  if (opts.card && (opts.week || opts.month)) opts.since = new Date((deps.now?.() ?? Date.now()) - (opts.week ? 7 : 30) * 86400000).toISOString().slice(0, 10);
506
546
  try {
507
547
  const report = await buildReport(opts, { onProgress: makeProgressPrinter(), ...deps });
@@ -535,6 +575,7 @@ export async function runStats(argv, deps = {}) {
535
575
  if (report.query?.origin && !opts.json) { process.stdout.write(`${renderOrigin(report.query.origin)}\n`); return 0; }
536
576
  if (report.query?.self_filed && !opts.json) { process.stdout.write(`${renderSelfFiled(report.query.self_filed)}\n`); return 0; }
537
577
  if (report.query?.depth && !opts.json) { process.stdout.write(`${renderDepth(report.query.depth, { repo: report.repo, since: opts.since })}\n`); return 0; }
578
+ if (report.query?.ci_awareness && !opts.json) { process.stdout.write(`${renderCiAwareness(report.query.ci_awareness)}\n`); return 0; }
538
579
  if (report.query?.pool && !opts.json) { process.stdout.write(`${formatPoolLines(report.query.pool).join("\n")}\n`); return 0; }
539
580
  if (report.query?.efficiency && !opts.json) {
540
581
  const e = report.query.efficiency;