forgedock 1.70.0 → 1.72.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.
- package/bin/config-schema.mjs +1 -1
- package/bin/engine/outcome-codes.mjs +5 -4
- package/bin/init-detect.mjs +35 -2
- package/bin/lean/admit.mjs +118 -0
- package/bin/lean/admit.test.mjs +78 -0
- package/bin/lean/attempts.mjs +1 -1
- package/bin/lean/batch.mjs +8 -0
- package/bin/lean/batch.test.mjs +17 -0
- package/bin/lean/concurrency.mjs +7 -2
- package/bin/lean/concurrency.test.mjs +16 -3
- package/bin/lean/conformance.mjs +2 -0
- package/bin/lean/conformance.test.mjs +9 -0
- package/bin/lean/effects.mjs +8 -0
- package/bin/lean/failure-census.mjs +1 -1
- package/bin/lean/lean.mjs +93 -4
- package/bin/lean/lean.test.mjs +38 -0
- package/bin/lean/orchestrate-envhold.test.mjs +14 -0
- package/bin/lean/orchestrate-heldroot.test.mjs +32 -0
- package/bin/lean/orchestrate.mjs +33 -11
- package/bin/lean/queuecause.mjs +42 -0
- package/bin/lean/release-cigreen.mjs +18 -4
- package/bin/lean/release-cigreen.test.mjs +23 -0
- package/bin/lean/release-review.mjs +24 -10
- package/bin/lean/release-review.test.mjs +65 -0
- package/bin/lean/release.mjs +1 -1
- package/bin/lean/release.test.mjs +19 -0
- package/bin/lean/schedd.mjs +24 -1
- package/bin/lean/schedd.test.mjs +38 -0
- package/bin/pool/agent.mjs +36 -18
- package/bin/pool/docker-dns.mjs +23 -0
- package/bin/pool/docker.mjs +9 -3
- package/bin/pool/engine-placement.test.mjs +2 -2
- package/bin/pool/image-manifest.test.mjs +13 -0
- package/bin/pool/lane-image.mjs +125 -0
- package/bin/pool/lane-tools.mjs +26 -12
- package/bin/pool/lane-tools.test.mjs +63 -1
- package/bin/pool/project-layer.mjs +2 -2
- package/bin/pool/router.mjs +2 -1
- package/bin/pool/version.mjs +1 -1
- package/bin/review-staging.mjs +14 -11
- package/bin/review-staging.test.mjs +20 -1
- package/bin/stats/escapes.mjs +124 -0
- package/bin/stats/index.mjs +5 -1
- package/bin/stats/quality-ledger.mjs +49 -0
- package/bin/stats/quality-ledger.test.mjs +84 -0
- package/bin/stats/weekly.mjs +230 -0
- package/docs/OUTCOME-CODES.md +2 -1
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/pool/image/Dockerfile +10 -4
- package/pool/image/lane-tools-sets.json +6 -0
- package/scripts/lane-variants.mjs +51 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #6166: a pool host gets the lane image by PULLING the one publish.yml built (ghcr.io), and builds locally only when the pull fails.
|
|
4
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { resolve4 } from "node:dns/promises";
|
|
6
|
+
import { DNS_FAIL_RE } from "./docker-dns.mjs";
|
|
7
|
+
|
|
8
|
+
export const LANE_REGISTRY_IMAGE = "ghcr.io/rapiercraftstudios/forgedock-lane";
|
|
9
|
+
/** Label the Dockerfile stamps with the recipe hash (versionOf().image); checked after a pull. */
|
|
10
|
+
export const RECIPE_LABEL = "forgedock.recipe";
|
|
11
|
+
/** Hosts dockerd contacts for a pull from ghcr.io and for a build FROM docker.io (the IPv4 pins cover exactly these). */
|
|
12
|
+
export const REGISTRY_HOSTS = ["ghcr.io", "pkg-containers.githubusercontent.com", "registry-1.docker.io", "auth.docker.io", "production.cloudflare.docker.com"];
|
|
13
|
+
/** dockerd/BuildKit dial the AAAA record and do not fall back to A (WSL mirrored networking has no IPv6 route). */
|
|
14
|
+
export const IPV6_DIAL_RE = /cannot assign requested address|network is unreachable|dial tcp \[[0-9a-f:]+\]/i;
|
|
15
|
+
const PIN_MARK = "# forgedock-ipv4-pin";
|
|
16
|
+
|
|
17
|
+
const errText = (e) => String(e?.stderr || e?.stdout || e?.message || e || "");
|
|
18
|
+
|
|
19
|
+
/** Remote ref of the lane image for a ForgeDock version. */
|
|
20
|
+
export const remoteLaneImage = (version) => `${LANE_REGISTRY_IMAGE}:${version}`;
|
|
21
|
+
/** Tag carrying the image recipe hash, pushed beside the version tag (identifies the recipe independent of a version bump). */
|
|
22
|
+
export const remoteRecipeImage = (recipe) => `${LANE_REGISTRY_IMAGE}:r-${recipe}`;
|
|
23
|
+
|
|
24
|
+
/** Remote ref of a lane_tools variant: the local tag `<base>-t<12 hex>` published as `forgedock-lane:<version>-t<12 hex>` (#6187). */
|
|
25
|
+
export const remoteVariantImage = (version, tag) => `${LANE_REGISTRY_IMAGE}:${version}${String(tag).slice(String(tag).lastIndexOf("-t"))}`;
|
|
26
|
+
|
|
27
|
+
let pinDepth = 0; // concurrent pins share one /etc/hosts edit; the last one out removes it
|
|
28
|
+
/**
|
|
29
|
+
* Run `fn` with temporary /etc/hosts IPv4 pins for the registry hosts (lines tagged `# forgedock-ipv4-pin`), removed afterwards,
|
|
30
|
+
* also stale ones left by a crashed agent. Needs write access to the hosts file (the agent runs as root); throws when it has none.
|
|
31
|
+
*/
|
|
32
|
+
export async function withIpv4Pins(fn, { hosts = REGISTRY_HOSTS, file = "/etc/hosts", resolve = resolve4, log = null } = {}) {
|
|
33
|
+
const strip = (t) => t.split("\n").filter((l) => !l.includes(PIN_MARK)).join("\n");
|
|
34
|
+
if (pinDepth === 0) {
|
|
35
|
+
const lines = [];
|
|
36
|
+
for (const h of hosts) { try { const [ip] = await resolve(h); if (ip) lines.push(`${ip} ${h} ${PIN_MARK}`); } catch { /* no A record: leave that host alone */ } }
|
|
37
|
+
if (!lines.length) throw new Error("ipv4 pins: no A records resolved");
|
|
38
|
+
const cur = readFileSync(file, "utf8");
|
|
39
|
+
writeFileSync(file, `${strip(cur).replace(/\n*$/, "\n")}${lines.join("\n")}\n`);
|
|
40
|
+
log?.info?.(`pinned IPv4 for ${lines.length} registry hosts in ${file}`);
|
|
41
|
+
}
|
|
42
|
+
pinDepth++;
|
|
43
|
+
try { return await fn(); } finally {
|
|
44
|
+
if (--pinDepth === 0) { try { writeFileSync(file, strip(readFileSync(file, "utf8")).replace(/\n*$/, "\n")); } catch (e) { log?.warn?.(`could not remove IPv4 pins from ${file}: ${errText(e)}`); } }
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Run `op`; on a docker DNS failure repair the daemon DNS and retry once (#6195); on an IPv6 dial error retry it once under temporary IPv4 pins. A host that cannot pin reports the original error. */
|
|
49
|
+
export async function withIpv4Fallback(op, pinOpts = {}) {
|
|
50
|
+
try { return await op(); } catch (e) {
|
|
51
|
+
if (DNS_FAIL_RE.test(errText(e)) && pinOpts.ensureDns) {
|
|
52
|
+
// #6195: dockerd's resolver is broken; set daemon DNS and retry once when docker was restarted.
|
|
53
|
+
pinOpts.log?.warn?.(`docker DNS error; repairing daemon DNS: ${errText(e).slice(-300)}`);
|
|
54
|
+
let fixed = null;
|
|
55
|
+
try { fixed = await pinOpts.ensureDns(); } catch { /* report the original error */ }
|
|
56
|
+
if (!fixed?.restarted) throw e;
|
|
57
|
+
return withIpv4Fallback(op, { ...pinOpts, ensureDns: null });
|
|
58
|
+
}
|
|
59
|
+
if (!IPV6_DIAL_RE.test(errText(e))) throw e;
|
|
60
|
+
pinOpts.log?.warn?.(`IPv6 dial error; retrying with IPv4 pins: ${errText(e).slice(-300)}`);
|
|
61
|
+
try { return await withIpv4Pins(op, pinOpts); } catch (e2) { if (e2 === e || IPV6_DIAL_RE.test(errText(e2))) throw e2; throw e; }
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Release holding the lane-image.json asset ({version, recipe, digest}) that publish.yml/lane-image.yml write after the push (#6185). */
|
|
66
|
+
export const laneDigestUrl = (version) => `https://github.com/rapiercraftstudios/forgedock/releases/download/lane-image-v${version}/lane-image.json`;
|
|
67
|
+
const DIGEST_RE = /^sha256:[0-9a-f]{64}$/;
|
|
68
|
+
|
|
69
|
+
/** Read the publisher-recorded digest of the lane image for `version`: {digest, recipe} or null on any failure (no asset, network, bad JSON). */
|
|
70
|
+
export async function fetchLaneDigest(version, { fetch: doFetch = globalThis.fetch, timeoutMs = 15000 } = {}) {
|
|
71
|
+
try {
|
|
72
|
+
const res = await doFetch(laneDigestUrl(version), { signal: AbortSignal.timeout(timeoutMs) });
|
|
73
|
+
if (!res.ok) return null;
|
|
74
|
+
const j = await res.json();
|
|
75
|
+
if (!DIGEST_RE.test(j?.digest ?? "") || (j.version != null && j.version !== version)) return null;
|
|
76
|
+
return { digest: j.digest, recipe: typeof j.recipe === "string" ? j.recipe : "" };
|
|
77
|
+
} catch { return null; }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Pull the published lane image BY DIGEST (the one publish recorded), confirm the pulled image's RepoDigests contain it, retag it as
|
|
82
|
+
* `image`, and check its recipe label equals `recipe` as a secondary consistency check. A mismatching image is removed again (it must
|
|
83
|
+
* never serve lanes) and rejects. Resolves true on success.
|
|
84
|
+
*/
|
|
85
|
+
export async function pullLaneImage({ docker, image, version, recipe, digest, log = null, pinOpts = {} }) {
|
|
86
|
+
if (!DIGEST_RE.test(digest ?? "")) throw new Error(`no trusted digest for ${remoteLaneImage(version)}`);
|
|
87
|
+
const remote = `${LANE_REGISTRY_IMAGE}@${digest}`;
|
|
88
|
+
const drop = async () => { try { await docker.removeImage?.(remote); } catch { /* best effort */ } };
|
|
89
|
+
await withIpv4Fallback(() => docker.pull(remote), { ...pinOpts, log });
|
|
90
|
+
const digests = (await docker.imageRepoDigests?.(remote)) ?? [];
|
|
91
|
+
if (!digests.some((d) => d === remote || d.endsWith(`@${digest}`))) { await drop(); throw new Error(`pulled ${remote} reports digests [${digests.join(", ")}], want ${digest}`); }
|
|
92
|
+
const got = await docker.imageLabel(remote, RECIPE_LABEL);
|
|
93
|
+
if (got !== recipe) { await drop(); throw new Error(`pulled ${remote} has recipe ${got || "(none)"}, want ${recipe}`); }
|
|
94
|
+
await docker.tag(remote, image);
|
|
95
|
+
// #6184: the ghcr tag is invisible to pruneLaneImages and would pin the image's layers forever; untagging it frees nothing yet keeps `image`.
|
|
96
|
+
try { await docker.removeImage?.(remote); } catch (e) { log?.warn?.(`could not drop ${remote} tag: ${errText(e).slice(-200)}`); }
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Make `image` exist locally: already present, else pulled by recorded digest (only the default `forgedock-lane:<version>` tag has a published
|
|
102
|
+
* counterpart), else built by `build()`. Resolves "present" | "pulled" | "built". `build` is wrapped in the IPv4 fallback too.
|
|
103
|
+
*/
|
|
104
|
+
export async function provideLaneImage({ docker, image, version, recipe, digest = null, publishable = true, build, log = null, pinOpts = {} }) {
|
|
105
|
+
if (await docker.hasImage?.(image)) return "present";
|
|
106
|
+
// #6185: no known digest -> no pull (the recipe label is self-declared by the image); build locally.
|
|
107
|
+
if (publishable && recipe && digest && docker.pull && docker.tag && docker.imageLabel) {
|
|
108
|
+
try {
|
|
109
|
+
await pullLaneImage({ docker, image, version, recipe, digest, log, pinOpts });
|
|
110
|
+
log?.info?.(`${image} pulled from ${LANE_REGISTRY_IMAGE}@${digest}; no build`);
|
|
111
|
+
return "pulled";
|
|
112
|
+
} catch (e) { log?.warn?.(`pull of ${LANE_REGISTRY_IMAGE}@${digest} failed, building locally: ${errText(e).slice(-300)}`); }
|
|
113
|
+
}
|
|
114
|
+
await withIpv4Fallback(build, { ...pinOpts, log });
|
|
115
|
+
return "built";
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Pull the published variant for local `tag` and retag it as `tag` (#6187). Rejects when the registry has none; the caller builds. */
|
|
119
|
+
export async function pullVariantImage({ docker, tag, version, log = null, pinOpts = {} }) {
|
|
120
|
+
const remote = remoteVariantImage(version, tag);
|
|
121
|
+
await withIpv4Fallback(() => docker.pull(remote), { ...pinOpts, log });
|
|
122
|
+
await docker.tag(remote, tag);
|
|
123
|
+
log?.info?.(`${tag} pulled from ${remote}; no build`);
|
|
124
|
+
return true;
|
|
125
|
+
}
|
package/bin/pool/lane-tools.mjs
CHANGED
|
@@ -160,52 +160,66 @@ export function laneToolsDockerfile(baseImage, tools) {
|
|
|
160
160
|
/** One in-flight build per tag (shared by every launch and the warm pool), and the last failure per tag. */
|
|
161
161
|
const BUILDS = new Map();
|
|
162
162
|
const FAILED = new Map();
|
|
163
|
-
/**
|
|
163
|
+
/** Longest a failed build is reported instead of retried; the window grows 1, 2, 5, 10 min with consecutive failures of a tag. */
|
|
164
164
|
export const LANE_BUILD_RETRY_MS = 10 * 60000;
|
|
165
|
+
const BACKOFF_MS = [60000, 120000, 300000, LANE_BUILD_RETRY_MS];
|
|
166
|
+
/** Reporting window after the `count`-th consecutive failure of a tag. */
|
|
167
|
+
export const laneBuildBackoffMs = (count) => BACKOFF_MS[Math.min(Math.max(count, 1), BACKOFF_MS.length) - 1];
|
|
165
168
|
|
|
166
169
|
/**
|
|
167
170
|
* The image a launch runs: `baseImage` when no tools; else the per-repo tag, reused when present, built from the base
|
|
168
|
-
* otherwise.
|
|
171
|
+
* otherwise. A published variant is pulled first when `docker.pullVariant(tag)` (optional) resolves true; `docker.withFallback(op)`
|
|
172
|
+
* (optional) wraps the build in the IPv4 fallback (#6187). `docker.hasImage` and `docker.build(dir, tag, args)` are injected. Throws typed lane_tools.unknown_recipe
|
|
169
173
|
* (nothing built) or lane_tools.build_failed (build error or timeout, never a hang).
|
|
170
174
|
*/
|
|
171
|
-
export async function resolveLaneImage({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000 }) {
|
|
175
|
+
export async function resolveLaneImage({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000, sleep }) {
|
|
172
176
|
if (!tools.length) return baseImage;
|
|
173
177
|
checkRecipes(tools);
|
|
174
178
|
const tag = laneToolsTag(baseImage, tools);
|
|
175
179
|
if (await docker.hasImage?.(tag)) return tag;
|
|
176
|
-
if (!BUILDS.has(tag)) BUILDS.set(tag, buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs }).finally(() => BUILDS.delete(tag)));
|
|
180
|
+
if (!BUILDS.has(tag)) BUILDS.set(tag, buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs, ...(sleep ? { sleep, retryDelayMs: 0 } : {}) }).finally(() => BUILDS.delete(tag)));
|
|
177
181
|
return BUILDS.get(tag); // concurrent callers share one build of a tag
|
|
178
182
|
}
|
|
179
183
|
|
|
180
184
|
/**
|
|
181
185
|
* Non-blocking form for a launch (the router waits ~120 s, a build can take many minutes): {image} when the tag exists,
|
|
182
186
|
* {building: true} after starting (or joining) a background build, {failed: message} for a build that failed in the last
|
|
183
|
-
*
|
|
187
|
+
* window `laneBuildBackoffMs` of its consecutive failures. Throws typed lane_tools.unknown_recipe.
|
|
184
188
|
*/
|
|
185
|
-
export async function laneImageNow({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000, now = Date.now }) {
|
|
189
|
+
export async function laneImageNow({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000, now = Date.now, sleep }) {
|
|
186
190
|
if (!tools.length) return { image: baseImage };
|
|
187
191
|
checkRecipes(tools);
|
|
188
192
|
const tag = laneToolsTag(baseImage, tools);
|
|
189
193
|
if (await docker.hasImage?.(tag)) return { image: tag };
|
|
190
194
|
const f = FAILED.get(tag);
|
|
191
|
-
if (f && now() - f.at <
|
|
195
|
+
if (f && now() - f.at < laneBuildBackoffMs(f.count)) return { failed: f.message };
|
|
192
196
|
if (!BUILDS.has(tag)) {
|
|
193
|
-
|
|
194
|
-
|
|
197
|
+
const p = buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs, ...(sleep ? { sleep, retryDelayMs: 0 } : {}) })
|
|
198
|
+
.then(() => { FAILED.delete(tag); }, (e) => { FAILED.set(tag, { at: now(), message: e.message, count: (f?.count ?? 0) + 1 }); }) // a failure is never permanent: it expires on a growing backoff
|
|
199
|
+
.finally(() => BUILDS.delete(tag));
|
|
195
200
|
BUILDS.set(tag, p);
|
|
196
201
|
}
|
|
197
202
|
return { building: true, tag };
|
|
198
203
|
}
|
|
199
204
|
|
|
200
|
-
|
|
205
|
+
/** #6189: the last ~20 lines of a build error (the failing step's own output), bounded to `max` chars. */
|
|
206
|
+
export function buildErrorTail(e, max = 1500) {
|
|
207
|
+
const t = String(e?.stderr || e?.message || e || "").trim().split("\n").slice(-20).join("\n");
|
|
208
|
+
return t.length <= max ? t : `…${t.slice(t.length - max + 1)}`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function buildLaneImage({ tag, baseImage, tools, docker, buildTimeoutMs, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), retryDelayMs = 15000 }) {
|
|
212
|
+
try { if (await docker.pullVariant?.(tag)) return tag; } catch { /* no published variant (or no route): build it */ }
|
|
201
213
|
const dir = mkdtempSync(join(tmpdir(), "lane-tools-"));
|
|
202
214
|
let timer;
|
|
203
215
|
try {
|
|
204
216
|
writeFileSync(join(dir, "Dockerfile"), laneToolsDockerfile(baseImage, tools));
|
|
205
217
|
const timeout = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`build timed out after ${buildTimeoutMs}ms`)), buildTimeoutMs); });
|
|
206
|
-
|
|
218
|
+
const build = () => docker.build(dir, tag, {});
|
|
219
|
+
const attempt = () => Promise.race([docker.withFallback ? docker.withFallback(build) : build(), timeout]);
|
|
220
|
+
try { await attempt(); } catch { await sleep(retryDelayMs); await attempt(); } // #6189: one retry, a failed build is often transient
|
|
207
221
|
} catch (e) {
|
|
208
|
-
throw typed("lane_tools.build_failed", `lane_tools image ${tag} build failed: ${
|
|
222
|
+
throw typed("lane_tools.build_failed", `lane_tools image ${tag} build failed: ${buildErrorTail(e)}`);
|
|
209
223
|
} finally { clearTimeout(timer); rmSync(dir, { recursive: true, force: true }); }
|
|
210
224
|
return tag;
|
|
211
225
|
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
|
-
import { RECIPES, hasRecipe, recipeFor, installCommands, installLaneTools, laneToolsDockerfile } from "./lane-tools.mjs";
|
|
5
|
+
import { RECIPES, hasRecipe, recipeFor, installCommands, installLaneTools, laneToolsDockerfile, laneToolsTag, laneBuildBackoffMs, resolveLaneImage, laneImageNow } from "./lane-tools.mjs";
|
|
6
6
|
|
|
7
7
|
describe("#5652 in-sandbox lane tool install", () => {
|
|
8
8
|
it("installCommands strips RUN, prefixes sudo when not root, and is empty without a recipe", () => {
|
|
@@ -64,3 +64,65 @@ describe("#6037 image manifest tools skip the fallback installers", () => {
|
|
|
64
64
|
assert.ok((src.match(/@deprecated/g) ?? []).length >= 4);
|
|
65
65
|
});
|
|
66
66
|
});
|
|
67
|
+
|
|
68
|
+
describe("#6187 pulled variants, backoff and error tail", () => {
|
|
69
|
+
const dock = (over = {}) => { const images = new Set(); return { builds: [], pulls: [], async hasImage(r) { return images.has(r); }, async build(d, t) { this.builds.push(t); if (over.failBuild) throw Object.assign(new Error("x"), { stderr: `${"head ".repeat(600)}REAL-CAUSE` }); images.add(t); }, ...over }; };
|
|
70
|
+
const settle = async () => { for (let i = 0; i < 20; i++) await new Promise((r) => setImmediate(r)); };
|
|
71
|
+
it("a pulled variant skips the build, and its tag is laneToolsTag", async () => {
|
|
72
|
+
const pulled = [], docker = dock({ pullVariant: async (t) => { pulled.push(t); return true; } });
|
|
73
|
+
const img = await resolveLaneImage({ tools: ["xvfb"], baseImage: "pv:1", docker });
|
|
74
|
+
assert.equal(img, laneToolsTag("pv:1", ["xvfb"]));
|
|
75
|
+
assert.deepEqual(pulled, [img]);
|
|
76
|
+
assert.equal(docker.builds.length, 0);
|
|
77
|
+
});
|
|
78
|
+
it("a failed pull falls back to the build, wrapped by withFallback", async () => {
|
|
79
|
+
let wrapped = 0;
|
|
80
|
+
const docker = dock({ pullVariant: async () => { throw new Error("404"); }, withFallback: (op) => { wrapped++; return op(); } });
|
|
81
|
+
await resolveLaneImage({ tools: ["xvfb"], baseImage: "pv:2", docker, sleep: async () => {} });
|
|
82
|
+
assert.equal(docker.builds.length, 1);
|
|
83
|
+
assert.equal(wrapped, 1);
|
|
84
|
+
});
|
|
85
|
+
it("a failed build message keeps the tail, and the retry window grows 1, 2, 5, 10 min", async () => {
|
|
86
|
+
assert.deepEqual([1, 2, 3, 4, 9].map(laneBuildBackoffMs), [60000, 120000, 300000, 600000, 600000]);
|
|
87
|
+
let t = 0;
|
|
88
|
+
const now = () => t, docker = dock({ failBuild: true }), a = { tools: ["shellcheck"], baseImage: "pv:3", docker, now, sleep: async () => {} };
|
|
89
|
+
await laneImageNow(a); await settle();
|
|
90
|
+
assert.match((await laneImageNow(a)).failed, /REAL-CAUSE$/);
|
|
91
|
+
t += 60001; await laneImageNow(a); await settle(); // 2nd failure
|
|
92
|
+
t += 60001;
|
|
93
|
+
assert.ok((await laneImageNow(a)).failed, "still inside the 2 min window");
|
|
94
|
+
assert.equal(docker.builds.length, 4); // 2 failures x (build + retry)
|
|
95
|
+
t += 60001;
|
|
96
|
+
assert.ok((await laneImageNow(a)).building);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe("lane image build errors and retry (#6189)", async () => {
|
|
101
|
+
const { laneImageNow, resolveLaneImage } = await import("./lane-tools.mjs");
|
|
102
|
+
const tools = ["shellcheck"];
|
|
103
|
+
const longErr = () => Object.assign(new Error("failed"), { stderr: `Dockerfile:5\n${Array.from({ length: 30 }, (_, i) => `line ${i}`).join("\n")}\nE: apt failed` });
|
|
104
|
+
const settle = () => new Promise((r) => setTimeout(r, 20));
|
|
105
|
+
const mk = (build) => ({ hasImage: async () => false, build });
|
|
106
|
+
|
|
107
|
+
it("failure message carries the tail of a long stderr", async () => {
|
|
108
|
+
const docker = mk(async () => { throw longErr(); });
|
|
109
|
+
await laneImageNow({ tools, baseImage: "base:tail", docker, sleep: async () => {} });
|
|
110
|
+
await settle();
|
|
111
|
+
const r = await laneImageNow({ tools, baseImage: "base:tail", docker, sleep: async () => {} });
|
|
112
|
+
assert.match(r.failed, /E: apt failed/);
|
|
113
|
+
assert.doesNotMatch(r.failed, /Dockerfile:5/);
|
|
114
|
+
});
|
|
115
|
+
it("retries a failed build once and yields the image", async () => {
|
|
116
|
+
let calls = 0;
|
|
117
|
+
const docker = mk(async () => { if (++calls === 1) throw longErr(); });
|
|
118
|
+
const img = await resolveLaneImage({ tools, baseImage: "base:retry", docker, sleep: async () => {} });
|
|
119
|
+
assert.equal(calls, 2);
|
|
120
|
+
assert.match(img, /base|lane/);
|
|
121
|
+
});
|
|
122
|
+
it("a persistent failure gives build_failed after 2 calls", async () => {
|
|
123
|
+
let calls = 0;
|
|
124
|
+
const docker = mk(async () => { calls++; throw longErr(); });
|
|
125
|
+
await assert.rejects(resolveLaneImage({ tools, baseImage: "base:fail", docker, sleep: async () => {} }), (e) => e.code === "lane_tools.build_failed" && /E: apt failed/.test(e.message));
|
|
126
|
+
assert.equal(calls, 2);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
@@ -12,7 +12,7 @@ import { join, posix } from "node:path";
|
|
|
12
12
|
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
|
13
13
|
import { tmpdir } from "node:os";
|
|
14
14
|
import { detect, pyHint, depCommands } from "../lean/depcache.mjs";
|
|
15
|
-
import { isLaneToolsTagOf } from "./lane-tools.mjs";
|
|
15
|
+
import { isLaneToolsTagOf, buildErrorTail } from "./lane-tools.mjs";
|
|
16
16
|
|
|
17
17
|
const JS = new Set(["pnpm", "npm", "yarn"]);
|
|
18
18
|
const MANIFESTS = ["package.json", "pnpm-workspace.yaml", ".npmrc", ".yarnrc.yml", "pyproject.toml", ".python-version"];
|
|
@@ -116,7 +116,7 @@ async function buildLayer({ tag, baseImage, deps, docker, buildTimeoutMs }) {
|
|
|
116
116
|
const timeout = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`build timed out after ${buildTimeoutMs}ms`)), buildTimeoutMs); });
|
|
117
117
|
await Promise.race([docker.build(dir, tag, {}), timeout]);
|
|
118
118
|
} catch (e) {
|
|
119
|
-
throw new Error(`project layer ${tag} build failed: ${
|
|
119
|
+
throw new Error(`project layer ${tag} build failed: ${buildErrorTail(e)}`);
|
|
120
120
|
} finally { clearTimeout(timer); rmSync(dir, { recursive: true, force: true }); }
|
|
121
121
|
return tag;
|
|
122
122
|
}
|
package/bin/pool/router.mjs
CHANGED
|
@@ -360,7 +360,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
360
360
|
const elastic = c.elastic_lanes === true && Number.isFinite(c.cpus_free_elastic) && Number.isFinite(c.mem_free_gb_elastic); // #6047: base reservations plus held heavy tokens
|
|
361
361
|
const cpusFree = prio === "normal" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : elastic ? c.cpus_free_elastic : c.cpus_free;
|
|
362
362
|
const memFree = prio === "normal" && Number.isFinite(c.mem_free_unreserved_gb) ? c.mem_free_unreserved_gb : elastic ? c.mem_free_gb_elastic : c.mem_free_gb;
|
|
363
|
-
|
|
363
|
+
const eb = elastic && c.elastic_base && Number.isFinite(c.elastic_base.cpus) && Number.isFinite(c.elastic_base.mem_gb) ? c.elastic_base : null; // #6204: elastic hosts charge a lane its measured footprint
|
|
364
|
+
return cpusFree >= (eb ? Math.min(size.cpus, eb.cpus) : size.cpus) && memFree >= (eb ? Math.min(size.mem_gb, eb.mem_gb) : size.mem_gb);
|
|
364
365
|
};
|
|
365
366
|
const headroom = (c, spec) => (spec?.priority === "borrow" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : 0);
|
|
366
367
|
// #5949: the dispatcher seeds a repo mirror before launch. The agent that will own the sandbox is picked here (the placing agent
|
package/bin/pool/version.mjs
CHANGED
|
@@ -25,7 +25,7 @@ export function versionOf(root = repoRoot) {
|
|
|
25
25
|
|
|
26
26
|
/** The lane image is tagged and built from the ForgeDock package version (no separate pin). */
|
|
27
27
|
export const laneImageTag = (version) => `forgedock-lane:${version}`;
|
|
28
|
-
export const laneBuildArgs = (version) => ({ FORGEDOCK_VERSION: version });
|
|
28
|
+
export const laneBuildArgs = (version, recipe) => ({ FORGEDOCK_VERSION: version, ...(recipe ? { FORGEDOCK_RECIPE: recipe } : {}) });
|
|
29
29
|
|
|
30
30
|
/** Numeric dotted-version compare (1.10 > 1.9): negative, 0 or positive; null when either side is not a version. */
|
|
31
31
|
export function cmpVersion(a, b) {
|
package/bin/review-staging.mjs
CHANGED
|
@@ -152,7 +152,7 @@ export function readConfig(io) {
|
|
|
152
152
|
try { cfg = parseForgeYaml(io.readFile(path)) ?? {}; } catch { /* absent config: owner/repo check below fails */ }
|
|
153
153
|
const owner = cfg.project?.owner, repo = cfg.project?.repo;
|
|
154
154
|
if (!owner || !repo) throw new Stop(1, [`review-staging: project.owner/project.repo not set in ${path}`]);
|
|
155
|
-
return { ghRepo: `${owner}/${repo}`, defaultBranch: cfg.branches?.default || "main", stagingBranch: cfg.branches?.staging || "staging", featurePattern: typeof cfg.branches?.feature_pattern === "string" && cfg.branches.feature_pattern.includes("{slug}") ? cfg.branches.feature_pattern : null, configPath: path, extraRequiredChecks: Array.isArray(cfg.gate?.required_checks) ? cfg.gate.required_checks.map((x) => String(x).trim()).filter(Boolean) : [], sandboxRepo: SANDBOX_RE.test(String(cfg.selftest?.sandbox_repo ?? "").trim()) ? String(cfg.selftest.sandbox_repo).trim() : "", sandboxRaw: String(cfg.selftest?.sandbox_repo ?? "").trim() };
|
|
155
|
+
return { blockSeverity: ["CRITICAL", "HIGH", "MEDIUM"].includes(String(cfg.release?.block_severity ?? "").trim().toUpperCase()) ? String(cfg.release.block_severity).trim().toUpperCase() : "HIGH", ghRepo: `${owner}/${repo}`, defaultBranch: cfg.branches?.default || "main", stagingBranch: cfg.branches?.staging || "staging", featurePattern: typeof cfg.branches?.feature_pattern === "string" && cfg.branches.feature_pattern.includes("{slug}") ? cfg.branches.feature_pattern : null, configPath: path, extraRequiredChecks: Array.isArray(cfg.gate?.required_checks) ? cfg.gate.required_checks.map((x) => String(x).trim()).filter(Boolean) : [], sandboxRepo: SANDBOX_RE.test(String(cfg.selftest?.sandbox_repo ?? "").trim()) ? String(cfg.selftest.sandbox_repo).trim() : "", sandboxRaw: String(cfg.selftest?.sandbox_repo ?? "").trim() };
|
|
156
156
|
}
|
|
157
157
|
|
|
158
158
|
/** Same derivation as commands/review-pr-staging.md Phase -1 (and scripts/lib/fence-bootstrap.sh). */
|
|
@@ -596,12 +596,13 @@ export function ciState(checks, required = []) {
|
|
|
596
596
|
return { pending, failing: names((k) => k.bucket === "fail" || k.bucket === "cancel").filter((n) => !pending.includes(n)), green: !pending.length && !rows.length };
|
|
597
597
|
}
|
|
598
598
|
|
|
599
|
-
/** Pre-dispatch CI read: `null` when green (or
|
|
600
|
-
async function ciNotGreen(io, c, pr, env) {
|
|
599
|
+
/** Pre-dispatch CI read: `null` when green (or no checks are required), else `{pending, failing}`. An unreadable read fails closed. */
|
|
600
|
+
export async function ciNotGreen(io, c, pr, env) {
|
|
601
601
|
const r = await io.run("gh", ["pr", "checks", String(pr), "-R", c.ghRepo, "--json", "name,bucket,link"], { env, cwd: io.cwd });
|
|
602
|
-
|
|
602
|
+
let checks = r.code === 0 || r.code === 8 ? parseChecks(r.stdout) : null;
|
|
603
|
+
// Right after a push no checks are registered yet: that is "required checks pending", not green (ciState then compares against the required set).
|
|
604
|
+
if (!checks && /no checks reported/i.test(`${r.stderr ?? ""}${r.stdout ?? ""}`)) checks = [];
|
|
603
605
|
if (!checks) {
|
|
604
|
-
if (/no checks reported/i.test(`${r.stderr ?? ""}${r.stdout ?? ""}`)) return null;
|
|
605
606
|
return { pending: [], failing: ["checks unreadable"] };
|
|
606
607
|
}
|
|
607
608
|
const read = await requiredChecksRead({ gh: io.gh, repo: c.ghRepo, lane: c.defaultBranch });
|
|
@@ -642,14 +643,16 @@ export function countFailingChecks(checks) {
|
|
|
642
643
|
return classifyChecks(checks).blocking;
|
|
643
644
|
}
|
|
644
645
|
|
|
645
|
-
/** Phase 8 verdict from the deterministic inputs (CI, test gate, CONFIRMED CRITICAL
|
|
646
|
-
export function stagingVerdict({ ciFailing, testGateInvalid, acceptanceBlocked = null, confirmedCritical, confirmedHigh }) {
|
|
646
|
+
/** Phase 8 verdict from the deterministic inputs (CI, test gate, CONFIRMED findings at or above `blockSeverity`, default HIGH; CRITICAL always blocks). */
|
|
647
|
+
export function stagingVerdict({ ciFailing, testGateInvalid, acceptanceBlocked = null, confirmedCritical, confirmedHigh, confirmedMedium = 0, blockSeverity = "HIGH" }) {
|
|
647
648
|
if (acceptanceBlocked) return { verdict: "BLOCK DEPLOY", why: `feature acceptance blocked: ${acceptanceBlocked}` };
|
|
648
649
|
if (ciFailing > 0) return { verdict: "BLOCK DEPLOY", why: `CI failing (${ciFailing} required check(s) red; forgedock/verify, forge/deploy-gate and the gate-marker check excluded)` };
|
|
649
650
|
if (testGateInvalid) return { verdict: "BLOCK DEPLOY", why: "test-gate result missing/invalid (fail closed)" };
|
|
650
651
|
if (confirmedCritical > 0) return { verdict: "BLOCK DEPLOY", why: `${confirmedCritical} CONFIRMED CRITICAL finding(s)` };
|
|
651
|
-
|
|
652
|
-
return { verdict: "
|
|
652
|
+
const sev = String(blockSeverity).toUpperCase();
|
|
653
|
+
if (confirmedHigh > 0 && sev !== "CRITICAL") return { verdict: "NEEDS FIXES FIRST", why: `${confirmedHigh} CONFIRMED HIGH finding(s)` };
|
|
654
|
+
if (confirmedMedium > 0 && sev === "MEDIUM") return { verdict: "NEEDS FIXES FIRST", why: `${confirmedMedium} CONFIRMED MEDIUM finding(s)` };
|
|
655
|
+
return { verdict: "APPROVE FOR DEPLOY", why: `no CI failure, no blocking test gate, no CONFIRMED finding at or above ${sev === "CRITICAL" || sev === "MEDIUM" ? sev : "HIGH"}` };
|
|
653
656
|
}
|
|
654
657
|
|
|
655
658
|
/**
|
|
@@ -696,7 +699,7 @@ async function summary(a, io) {
|
|
|
696
699
|
}
|
|
697
700
|
|
|
698
701
|
const acceptanceBlocked = await acceptanceBlock(io, c, pr, tg);
|
|
699
|
-
const v = stagingVerdict({ ciFailing, testGateInvalid: tg.invalid, acceptanceBlocked, confirmedCritical: st.confirmedCritical, confirmedHigh: st.confirmedHigh });
|
|
702
|
+
const v = stagingVerdict({ ciFailing, testGateInvalid: tg.invalid, acceptanceBlocked, confirmedCritical: st.confirmedCritical, confirmedHigh: st.confirmedHigh, confirmedMedium: st.confirmedMedium, blockSeverity: c.blockSeverity });
|
|
700
703
|
const pass = v.verdict === "APPROVE FOR DEPLOY";
|
|
701
704
|
const marker = pass ? "FORGE:GATE_PASS" : "FORGE:GATE_FAILURE";
|
|
702
705
|
const bundle = (st.bundle ?? []).join(" ");
|
|
@@ -721,7 +724,7 @@ async function summary(a, io) {
|
|
|
721
724
|
"| Domain | Result | Notes |",
|
|
722
725
|
"|--------|--------|-------|",
|
|
723
726
|
`| CI | ${ciFailing > 0 ? "FAIL" : "PASS"} | ${ciFailing} failing required check(s), forgedock/verify, forge/deploy-gate and the gate-marker check excluded${warnings.length ? `; ${warnings.length} non-required check(s) red, non-blocking warning: ${warnings.join(", ")}` : ""} |`,
|
|
724
|
-
`| Findings | ${st.confirmedCritical} CRITICAL / ${st.confirmedHigh} HIGH (CONFIRMED) | per-domain verdicts are in the FORGE:REVIEW-AGENT comments |`,
|
|
727
|
+
`| Findings | ${st.confirmedCritical} CRITICAL / ${st.confirmedHigh} HIGH / ${st.confirmedMedium ?? 0} MEDIUM (CONFIRMED) | blocks at ${c.blockSeverity ?? "HIGH"} and above; per-domain verdicts are in the FORGE:REVIEW-AGENT comments |`,
|
|
725
728
|
`| **Test Gate** | \`${tg.verdict}\` | \`${tg.reason || "Phase 6.5 not run"}\` |`,
|
|
726
729
|
...(acceptanceBlocked ? [`| **Feature acceptance** | \`BLOCK\` | ${acceptanceBlocked.replace(/\|/g, "/")} |`] : []),
|
|
727
730
|
"",
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
|
-
import { stagingVerdict } from "./review-staging.mjs";
|
|
5
|
+
import { stagingVerdict, ciNotGreen } from "./review-staging.mjs";
|
|
6
6
|
|
|
7
7
|
const ok = { ciFailing: 0, testGateInvalid: false, confirmedCritical: 0, confirmedHigh: 0 };
|
|
8
8
|
|
|
@@ -16,3 +16,22 @@ describe("stagingVerdict feature acceptance (#5336)", () => {
|
|
|
16
16
|
assert.match(v.why, /feature acceptance blocked: Test Gate SKIP/);
|
|
17
17
|
});
|
|
18
18
|
});
|
|
19
|
+
|
|
20
|
+
describe("ciNotGreen: no checks reported yet", () => {
|
|
21
|
+
const mk = (required) => ({
|
|
22
|
+
cwd: ".",
|
|
23
|
+
run: async () => ({ code: 1, stdout: "", stderr: "no checks reported on the 'x' branch" }),
|
|
24
|
+
gh: async (args) => {
|
|
25
|
+
if (String(args.join(" ")).includes("required_status_checks") && !args.includes("--paginate")) return JSON.stringify({ contexts: required });
|
|
26
|
+
return "";
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
const c = { ghRepo: "o/r", defaultBranch: "main", extraRequiredChecks: [] };
|
|
30
|
+
it("is pending (not green) when required checks are not registered yet", async () => {
|
|
31
|
+
const st = await ciNotGreen(mk(["build"]), c, 1, {});
|
|
32
|
+
assert.deepEqual(st?.pending, ["build"]);
|
|
33
|
+
});
|
|
34
|
+
it("stays green when no checks are required", async () => {
|
|
35
|
+
assert.equal(await ciNotGreen(mk([]), c, 1, {}), null);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* `forgedock stats escapes [--days 14] [--repo R] [--json]` (#6203): the escape linker. For lane PRs merged in the window, find
|
|
5
|
+
* later fix or revert PRs and bug issues that cite the lane PR number or its issue (within WINDOW_DAYS of the merge), plus
|
|
6
|
+
* reopen events on the lane's issue. Deterministic, gh reads only, no model. A citation count is a lower bound on the true
|
|
7
|
+
* escape rate. Results merge into ~/.forge/stats-cache/escapes-<owner>__<repo>.json, which the weekly scorecard reads.
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { defaultGh, isValidRepo } from "./github-source.mjs";
|
|
12
|
+
import { resolveRepo } from "./index.mjs";
|
|
13
|
+
import { forgeHome } from "./weekly.mjs";
|
|
14
|
+
|
|
15
|
+
export const WINDOW_DAYS = 14;
|
|
16
|
+
const DAY = 86400000;
|
|
17
|
+
const labelsOf = (x) => (x.labels ?? []).map((l) => String(l?.name ?? l).toLowerCase());
|
|
18
|
+
const cites = (text, n) => new RegExp(`(^|[^\\w/])#${n}(?!\\d)`).test(String(text ?? ""));
|
|
19
|
+
|
|
20
|
+
/** The lane's issue number: from the lane branch, else a `Closes #N` in the body. */
|
|
21
|
+
export function laneIssueOf(pr) {
|
|
22
|
+
const b = /^feat\/issue-(\d+)(-|$)/.exec(pr.headRefName ?? "")?.[1];
|
|
23
|
+
if (b) return Number(b);
|
|
24
|
+
const c = /\b(?:closes|fixes|resolves)\s+#(\d+)/i.exec(pr.body ?? "")?.[1];
|
|
25
|
+
return c ? Number(c) : null;
|
|
26
|
+
}
|
|
27
|
+
export const isFixPr = (p) => /^(revert|fix|hotfix)\b/i.test(p.title ?? "") || /^(fix|revert|hotfix)\//i.test(p.headRefName ?? "");
|
|
28
|
+
export const isBugIssue = (i) => labelsOf(i).some((l) => /^(bug|regression|revert|type:bug)$/.test(l) || l.includes("regression"));
|
|
29
|
+
const CAUSAL = /regress|introduc|broke|breaks|caused|revert|follow.?up|fallout|missed|incomplete|hotfix|left behind|undid/i;
|
|
30
|
+
/** A citation of #n that blames it: the number sits within 100 chars of a causal word (a bare mention in a tracker does not count). */
|
|
31
|
+
export const blames = (text, n) => {
|
|
32
|
+
const t = String(text ?? ""), re = new RegExp(`(^|[^\\w/])#${n}(?!\\d)`, "g");
|
|
33
|
+
for (let m; (m = re.exec(t));) if (CAUSAL.test(t.slice(Math.max(0, m.index - 100), m.index + 100))) return true;
|
|
34
|
+
return false;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** Pure link step: lane PRs, candidate PRs and issues, reopen counts -> per-PR escape records. */
|
|
38
|
+
export function linkEscapes({ lanePrs, candPrs, candIssues, reopens = new Map(), windowDays = WINDOW_DAYS }) {
|
|
39
|
+
return lanePrs.map((p) => {
|
|
40
|
+
const issue = laneIssueOf(p), t0 = Date.parse(p.mergedAt), t1 = t0 + windowDays * DAY, links = [];
|
|
41
|
+
const hit = (x, kind) => {
|
|
42
|
+
if (x.number === p.number || x.number === issue) return;
|
|
43
|
+
const created = Date.parse(x.createdAt);
|
|
44
|
+
if (!(created > t0 && created <= t1)) return;
|
|
45
|
+
// fix/revert PRs may cite the lane PR directly; every other citation (the lane's issue, or a bug issue) must blame it
|
|
46
|
+
const direct = kind !== "bug_issue" && (cites(x.title, p.number) || cites(x.body, p.number));
|
|
47
|
+
const blamed = blames(x.title, p.number) || blames(x.body, p.number) || (issue && (blames(x.title, issue) || blames(x.body, issue)));
|
|
48
|
+
if (direct || blamed) links.push({ kind, number: x.number });
|
|
49
|
+
};
|
|
50
|
+
for (const x of candPrs) if (isFixPr(x)) hit(x, /^revert/i.test(x.title ?? "") ? "revert_pr" : "fix_pr");
|
|
51
|
+
for (const x of candIssues) if (isBugIssue(x)) hit(x, "bug_issue");
|
|
52
|
+
const reopened = issue ? (reopens.get(issue) ?? 0) : 0;
|
|
53
|
+
return { pr: p.number, issue, mergedAt: p.mergedAt, links, reopened, escaped: links.length > 0 || reopened > 0 };
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const readdirSyncSafe = (d) => { try { return readdirSync(d); } catch { return []; } };
|
|
58
|
+
const cachePath = (home, repo) => join(home, "stats-cache", `escapes-${String(repo).replace("/", "__")}.json`);
|
|
59
|
+
/** Map "PR number" -> escaped boolean for the weekly scorecard; null without a cache. */
|
|
60
|
+
export function readEscapeCache({ home = forgeHome(), repo = null } = {}) {
|
|
61
|
+
const repos = repo ? [repo] : [];
|
|
62
|
+
const m = new Map();
|
|
63
|
+
for (const r of repos.length ? repos : []) { try { for (const [pr, v] of Object.entries(JSON.parse(readFileSync(cachePath(home, r), "utf8")).prs ?? {})) m.set(Number(pr), Boolean(v.escaped)); } catch { /* none */ } }
|
|
64
|
+
if (!repo) { // no repo given: every cached repo
|
|
65
|
+
try { for (const f of readdirSyncSafe(join(home, "stats-cache"))) if (f.startsWith("escapes-")) for (const [pr, v] of Object.entries(JSON.parse(readFileSync(join(home, "stats-cache", f), "utf8")).prs ?? {})) m.set(Number(pr), Boolean(v.escaped)); } catch { /* none */ }
|
|
66
|
+
}
|
|
67
|
+
return m.size ? m : null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function gatherEscapes({ repo, days = WINDOW_DAYS, gh = defaultGh, now = Date.now(), windowDays = WINDOW_DAYS } = {}) {
|
|
71
|
+
const day = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
72
|
+
const from = day(now - days * DAY), upto = day(now - 0);
|
|
73
|
+
const j = async (args) => JSON.parse(await gh(args) || "[]");
|
|
74
|
+
const merged = await j(["pr", "list", "-R", repo, "--state", "merged", "--search", `merged:>=${from}`, "--limit", "1000", "--json", "number,title,body,headRefName,mergedAt"]);
|
|
75
|
+
const lanePrs = merged.filter((p) => laneIssueOf(p) != null && /^feat\/issue-\d+/.test(p.headRefName ?? ""));
|
|
76
|
+
const candFrom = from;
|
|
77
|
+
const candPrs = await j(["pr", "list", "-R", repo, "--state", "all", "--search", `created:>=${candFrom}`, "--limit", "1000", "--json", "number,title,body,headRefName,createdAt"]);
|
|
78
|
+
const candIssues = await j(["issue", "list", "-R", repo, "--state", "all", "--search", `created:>=${candFrom}`, "--limit", "1000", "--json", "number,title,body,labels,createdAt"]);
|
|
79
|
+
const reopens = new Map(), issues = [...new Set(lanePrs.map(laneIssueOf))];
|
|
80
|
+
let i = 0;
|
|
81
|
+
await Promise.all(Array.from({ length: 6 }, async () => {
|
|
82
|
+
for (;;) {
|
|
83
|
+
const n = issues[i++]; if (n === undefined) return;
|
|
84
|
+
const pr = lanePrs.find((p) => laneIssueOf(p) === n), t0 = Date.parse(pr.mergedAt);
|
|
85
|
+
try {
|
|
86
|
+
const ev = JSON.parse(await gh(["api", `repos/${repo}/issues/${n}/events`, "--paginate", "--jq", "[.[] | select(.event==\"reopened\") | .created_at]"]).then((s) => `[${String(s).replace(/\]\s*\[/g, ",").replace(/^\[|\]$/g, "")}]`) || "[]");
|
|
87
|
+
reopens.set(n, ev.filter((t) => Date.parse(t) > t0 && Date.parse(t) <= t0 + windowDays * DAY).length);
|
|
88
|
+
} catch { /* a missing events read is not a reopen */ }
|
|
89
|
+
}
|
|
90
|
+
}));
|
|
91
|
+
return { upto, records: linkEscapes({ lanePrs, candPrs, candIssues, reopens, windowDays }) };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function summarise(records) {
|
|
95
|
+
const done = records.filter((r) => Date.parse(r.mergedAt) <= Date.now() - WINDOW_DAYS * DAY), esc = (rs) => rs.filter((r) => r.escaped).length;
|
|
96
|
+
return { lane_prs: records.length, escaped: esc(records), escape_pct: records.length ? esc(records) / records.length : null,
|
|
97
|
+
matured_prs: done.length, matured_escaped: esc(done), matured_escape_pct: done.length ? esc(done) / done.length : null,
|
|
98
|
+
by_kind: records.flatMap((r) => r.links.map((l) => l.kind)).reduce((a, k) => ({ ...a, [k]: (a[k] ?? 0) + 1 }), {}), reopened: records.filter((r) => r.reopened > 0).length };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function renderEscapes(records, repo, days) {
|
|
102
|
+
const s = summarise(records), p = (v) => (v == null ? "n/a" : `${(v * 100).toFixed(1)}%`);
|
|
103
|
+
const lines = [`Escapes for ${repo}: lane PRs merged in the last ${days}d, linked to fix/revert PRs and bug issues citing the PR or its issue within ${WINDOW_DAYS}d, plus reopens.`,
|
|
104
|
+
`lane PRs ${s.lane_prs} escaped ${s.escaped} escape ${p(s.escape_pct)} (matured ${WINDOW_DAYS}d+: ${s.matured_escaped}/${s.matured_prs} = ${p(s.matured_escape_pct)}) reopened ${s.reopened}`,
|
|
105
|
+
`links by kind: ${Object.entries(s.by_kind).map(([k, n]) => `${k} ${n}`).join(", ") || "none"}. Citation-based, so a lower bound.`];
|
|
106
|
+
for (const r of records.filter((x) => x.escaped)) lines.push(` PR #${r.pr} (issue ${r.issue ?? "?"}): ${r.links.map((l) => `${l.kind} #${l.number}`).join(", ")}${r.reopened ? ` reopened x${r.reopened}` : ""}`);
|
|
107
|
+
return `${lines.join("\n")}\n`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function runEscapes(argv, deps = {}) {
|
|
111
|
+
const val = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : null; };
|
|
112
|
+
const days = Number(val("--days") ?? WINDOW_DAYS), repo = resolveRepo(val("--repo"));
|
|
113
|
+
if (!isValidRepo(repo) || !(days > 0)) { process.stderr.write("forgedock stats escapes [--days N] [--repo owner/repo] [--json]\n"); return 2; }
|
|
114
|
+
const { records } = await gatherEscapes({ repo, days, gh: deps.gh ?? defaultGh, now: deps.now?.() ?? Date.now() });
|
|
115
|
+
if (!deps.noCache) { // merge into the cache: a re-run replaces the PRs it covers (the linker is deterministic) and keeps older ones
|
|
116
|
+
const home = deps.home ?? forgeHome(), file = cachePath(home, repo);
|
|
117
|
+
let prs = {}; try { prs = JSON.parse(readFileSync(file, "utf8")).prs ?? {}; } catch { /* new cache */ }
|
|
118
|
+
for (const r of records) prs[r.pr] = r;
|
|
119
|
+
if (!existsSync(dirname(file))) mkdirSync(dirname(file), { recursive: true });
|
|
120
|
+
writeFileSync(file, JSON.stringify({ repo, updated: new Date().toISOString(), prs }));
|
|
121
|
+
}
|
|
122
|
+
(deps.out ?? ((s) => process.stdout.write(s)))(argv.includes("--json") ? `${JSON.stringify({ repo, days, ...summarise(records), records }, null, 2)}\n` : renderEscapes(records, repo, days));
|
|
123
|
+
return 0;
|
|
124
|
+
}
|
package/bin/stats/index.mjs
CHANGED
|
@@ -38,7 +38,9 @@ import { gitProbes } from "./compounding.mjs";
|
|
|
38
38
|
|
|
39
39
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
40
40
|
|
|
41
|
-
export const HELP = `Usage: forgedock stats [--
|
|
41
|
+
export const HELP = `Usage: forgedock stats escapes [--days 14] [--repo <owner/repo>] [--json] (lane PRs later fixed/reverted/reopened)
|
|
42
|
+
forgedock stats scorecard --weekly [--repo <owner/repo>] [--json] (by week and engine version)
|
|
43
|
+
forgedock stats [--since <version|date>] [--repo <owner/repo>] [--json] [--refresh]
|
|
42
44
|
[--compact] [--no-local] [--no-cache] [--min-n N] [--release-times FILE]
|
|
43
45
|
forgedock stats --experiment <id> [--require-met] [--min-n N] [--repo <owner/repo>] [--json]
|
|
44
46
|
forgedock stats --by version [--post-metrics <pr>] [--min-n N] [--repo <owner/repo>] [--json]
|
|
@@ -533,6 +535,8 @@ export async function buildReport(opts, deps = {}) {
|
|
|
533
535
|
}
|
|
534
536
|
|
|
535
537
|
export async function runStats(argv, deps = {}) {
|
|
538
|
+
if (argv[0] === "escapes") return (await import("./escapes.mjs")).runEscapes(argv.slice(1), deps); // #6203
|
|
539
|
+
if (argv[0] === "scorecard" && argv.includes("--weekly")) return (await import("./weekly.mjs")).runWeekly(argv.slice(1), deps); // #6203
|
|
536
540
|
let opts;
|
|
537
541
|
try { opts = parseArgs(argv); } catch (err) {
|
|
538
542
|
process.stderr.write(`forgedock stats: ${err.message}\n\n${HELP}`);
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Quality ledger (#6203): the per-merge MERGE_LEDGER telemetry record, plus the pure helpers the weekly scorecard and the
|
|
5
|
+
* escape linker share. No model calls; everything is derived from run-log / batch-row / GitHub facts that already exist.
|
|
6
|
+
*/
|
|
7
|
+
const isNum = (x) => typeof x === "number" && Number.isFinite(x);
|
|
8
|
+
const TEST_PATH_RE = /(^|\/)(tests?|__tests__|spec|e2e)\/|\.(test|spec)\.[cm]?[jt]sx?$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$|Tests?\.(java|kt|cs)$/i;
|
|
9
|
+
export const isTestFile = (p) => TEST_PATH_RE.test(String(p ?? ""));
|
|
10
|
+
|
|
11
|
+
/** Test files added or changed in a diff, from `git diff --name-status` lines or plain names. */
|
|
12
|
+
export function testDelta(files = []) {
|
|
13
|
+
const list = (files ?? []).map((f) => String(f ?? "").trim()).filter(Boolean);
|
|
14
|
+
const tests = list.filter(isTestFile);
|
|
15
|
+
return { files_changed: list.length, test_files: tests.length };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const isBotLogin = (l) => /\[bot\]$|^github-actions$|^dependabot$/i.test(String(l ?? ""));
|
|
19
|
+
/** Operator actions visible on the issue during the run: comments by a non-bot author that are not FORGE machine comments. */
|
|
20
|
+
export function humanTouches(comments = [], sinceMs = 0) {
|
|
21
|
+
return (comments ?? []).filter((c) => {
|
|
22
|
+
if (!c || c.__mine === true) return false;
|
|
23
|
+
const login = c.author?.login ?? c.user?.login ?? null;
|
|
24
|
+
if (!login || isBotLogin(login)) return false;
|
|
25
|
+
if (/^\s*<!--\s*FORGE:/.test(String(c.body ?? ""))) return false;
|
|
26
|
+
const at = Date.parse(c.createdAt ?? c.created_at ?? "");
|
|
27
|
+
return !Number.isFinite(at) || at >= sinceMs;
|
|
28
|
+
}).length;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The MERGE_LEDGER record. first_pass: merged without a recovery run, a relaunch (attempt > 1) or a builder rework round
|
|
33
|
+
* (reviewer, CI, precheck, conformance...) after the first build; null when the builder triggers are not measurable.
|
|
34
|
+
* cost_usd is THIS run's total (one number per run); the scorecard sums distinct runs per lane, never cumulative rows.
|
|
35
|
+
*/
|
|
36
|
+
export function buildMergeLedger({ firstPass = null, recovered = false, attempt = 1, ciVerifies = 0, ciFixRounds = 0, files = [], comments = [], sinceMs = 0, costUsd = 0, phases = {}, wallMs = null, engineVersion = null, tier = null, model = null, pr = null } = {}) {
|
|
37
|
+
const clean = firstPass === true && !recovered && !(attempt > 1) && !ciFixRounds;
|
|
38
|
+
const byPhase = {};
|
|
39
|
+
for (const [id, v] of Object.entries(phases ?? {})) if (isNum(v?.ms)) byPhase[id] = Math.round(v.ms);
|
|
40
|
+
return {
|
|
41
|
+
event: "MERGE_LEDGER", ...(Number.isInteger(pr) ? { pr } : {}),
|
|
42
|
+
first_pass: firstPass == null && !recovered && !(attempt > 1) ? null : clean,
|
|
43
|
+
human_touch: humanTouches(comments, sinceMs),
|
|
44
|
+
test_files: testDelta(files).test_files, files_changed: testDelta(files).files_changed,
|
|
45
|
+
ci_attempts: Math.max(0, Math.round(ciVerifies)), ci_fix_rounds: Math.max(0, Math.round(ciFixRounds)),
|
|
46
|
+
cost_usd: Math.round((costUsd || 0) * 1e6) / 1e6, ...(isNum(wallMs) ? { wall_ms: Math.round(wallMs) } : {}), wall_ms_by_phase: byPhase,
|
|
47
|
+
engine_version: engineVersion ?? null, model_tier: tier ?? null, ...(model && model !== "default" ? { model } : {}), attempt, recovered: Boolean(recovered),
|
|
48
|
+
};
|
|
49
|
+
}
|