forgedock 1.56.0 → 1.58.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 +2 -1
- package/bin/engine/phases.mjs +4 -3
- package/bin/engine-cli.mjs +48 -12
- package/bin/forgedock.mjs +52 -3
- package/bin/gc.mjs +43 -6
- package/bin/help-text.mjs +4 -2
- package/bin/lean/batch-health.mjs +5 -1
- package/bin/lean/batch-health.test.mjs +7 -1
- package/bin/lean/batch.mjs +7 -2
- package/bin/lean/batch.test.mjs +45 -0
- package/bin/lean/conformance.e2e.test.mjs +3 -2
- package/bin/lean/conformance.mjs +118 -20
- package/bin/lean/conformance.test.mjs +172 -3
- package/bin/lean/decisions.mjs +98 -1
- package/bin/lean/decisions.test.mjs +30 -1
- package/bin/lean/depcache.mjs +124 -13
- package/bin/lean/depcache.test.mjs +121 -3
- package/bin/lean/design-gate.mjs +144 -0
- package/bin/lean/design-gate.test.mjs +169 -0
- package/bin/lean/effects-cap.test.mjs +17 -0
- package/bin/lean/effects.mjs +58 -13
- package/bin/lean/heavy.mjs +25 -8
- package/bin/lean/hostload.test.mjs +28 -0
- package/bin/lean/intake.mjs +97 -0
- package/bin/lean/intake.test.mjs +105 -0
- package/bin/lean/interfaces.mjs +181 -0
- package/bin/lean/interfaces.test.mjs +192 -0
- package/bin/lean/issuewatch-install.mjs +52 -12
- package/bin/lean/issuewatch-install.test.mjs +50 -0
- package/bin/lean/issuewatch-parity.mjs +16 -3
- package/bin/lean/issuewatch-parity.test.mjs +32 -0
- package/bin/lean/issuewatch-reconcile.mjs +29 -1
- package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
- package/bin/lean/issuewatch.mjs +34 -3
- package/bin/lean/issuewatch.test.mjs +49 -1
- package/bin/lean/lanecheck.test.mjs +15 -4
- package/bin/lean/lean.mjs +110 -24
- package/bin/lean/lean.test.mjs +183 -4
- package/bin/lean/orchestrate-blocked.test.mjs +18 -2
- package/bin/lean/orchestrate-owned.test.mjs +14 -5
- package/bin/lean/orchestrate.mjs +26 -4
- package/bin/lean/orphan-pr.mjs +3 -2
- package/bin/lean/orphan-pr.test.mjs +8 -1
- package/bin/lean/pagegate.mjs +35 -12
- package/bin/lean/pagegate.test.mjs +39 -1
- package/bin/lean/preflight.mjs +35 -1
- package/bin/lean/preflight.test.mjs +27 -1
- package/bin/lean/prompts.mjs +2 -1
- package/bin/lean/reap.test.mjs +39 -0
- package/bin/lean/recovery.test.mjs +28 -3
- package/bin/lean/release-config.mjs +169 -0
- package/bin/lean/release-config.test.mjs +132 -0
- package/bin/lean/release-control.mjs +171 -0
- package/bin/lean/release-control.test.mjs +167 -0
- package/bin/lean/release-deploy.mjs +209 -0
- package/bin/lean/release-deploy.test.mjs +217 -0
- package/bin/lean/release-fence.mjs +50 -0
- package/bin/lean/release-fence.test.mjs +105 -0
- package/bin/lean/release-flakes.mjs +139 -0
- package/bin/lean/release-flakes.test.mjs +116 -0
- package/bin/lean/release-gates.mjs +230 -0
- package/bin/lean/release-gates.test.mjs +146 -0
- package/bin/lean/release-ledger.mjs +176 -0
- package/bin/lean/release-ledger.test.mjs +226 -0
- package/bin/lean/release-minutes.mjs +102 -0
- package/bin/lean/release-minutes.test.mjs +107 -0
- package/bin/lean/release-nightly.mjs +75 -0
- package/bin/lean/release-nightly.test.mjs +48 -0
- package/bin/lean/release-postmerge.mjs +8 -2
- package/bin/lean/release-review.e2e.test.mjs +1 -0
- package/bin/lean/release-review.mjs +54 -7
- package/bin/lean/release-review.test.mjs +76 -7
- package/bin/lean/release-status.mjs +300 -0
- package/bin/lean/release-status.test.mjs +220 -0
- package/bin/lean/release-unitmap.mjs +35 -0
- package/bin/lean/release-unitmap.test.mjs +41 -0
- package/bin/lean/release-verify.mjs +221 -0
- package/bin/lean/release-verify.test.mjs +176 -0
- package/bin/lean/release.mjs +244 -22
- package/bin/lean/release.test.mjs +44 -0
- package/bin/lean/render.mjs +3 -1
- package/bin/lean/run-issue-placement.test.mjs +82 -0
- package/bin/lean/sandbox-remote.mjs +16 -0
- package/bin/lean/schedd.mjs +1 -1
- package/bin/lean/seam.mjs +115 -0
- package/bin/lean/seam.test.mjs +118 -0
- package/bin/lean/selftest-journey.mjs +40 -2
- package/bin/lean/selftest-journey.test.mjs +43 -3
- package/bin/lean/statuscomment.mjs +168 -0
- package/bin/lean/statuscomment.test.mjs +133 -0
- package/bin/lean/ui-quality.mjs +57 -0
- package/bin/lean/ui-quality.test.mjs +55 -0
- package/bin/lean/visual-gate.test.mjs +63 -0
- package/bin/pool/agent.mjs +16 -2
- package/bin/pool/router.mjs +5 -1
- package/bin/review-staging.mjs +5 -3
- package/bin/stats/card.mjs +117 -0
- package/bin/stats/card.test.mjs +109 -0
- package/bin/stats/conformance-outcomes.test.mjs +2 -1
- package/bin/stats/depth.mjs +1 -1
- package/bin/stats/gh-retry.test.mjs +152 -0
- package/bin/stats/github-source.mjs +147 -14
- package/bin/stats/index.mjs +35 -2
- package/bin/stats/stats.test.mjs +31 -3
- package/bin/vendor/js-yaml/LICENSE +21 -0
- package/bin/vendor/js-yaml/PIN.md +7 -0
- package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
- package/commands/design-render-critique-loop.md +2 -0
- package/commands/design.md +2 -0
- package/commands/issue.md +1 -1
- package/commands/milestone.md +1 -1
- package/commands/review-pr-agents/frontend.md +1 -0
- package/commands/review-pr-staging.md +5 -0
- package/docs/CONFIG.md +95 -2
- package/docs/ISSUE-WATCH.md +7 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/docs/STATS.md +10 -0
- package/docs/design/visual-gate.md +25 -0
- package/docs/eval/adversarial-bench.md +2 -2
- package/docs/eval/corpus/adversarial-v1.json +3 -3
- package/docs/site/start-a-new-project.md +7 -0
- package/docs/spec/forge-protocol-v1.md +31 -0
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/scripts/acceptance-red-green.sh +15 -1
- package/scripts/acceptance-red-green.test.sh +12 -0
- package/scripts/bench-adversarial.mjs +4 -0
- package/scripts/bench-lightlane.mjs +4 -1
- package/scripts/bootstrap-create.mjs +8 -2
- package/scripts/ci-local/scoping.mjs +19 -0
- package/scripts/ci-local.test.sh +16 -3
- package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
- package/scripts/plan-validate-live.mjs +9 -6
- package/scripts/review-prepare.sh +7 -1
- package/scripts/review-roster.sh +5 -2
- package/scripts/review-roster.test.sh +9 -0
- package/scripts/visual-gate.mjs +64 -0
- package/templates/bootstrap/technical-spike.md +17 -0
- package/templates/contracts/seam-check.mjs +236 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* `forgedock stats --card` (forge#5291): a shareable summary card (SVG + Markdown) built from the aggregate report.
|
|
5
|
+
* Aggregate numbers only: no issue titles, and no repo name unless `includeRepoNames`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Documented estimate: human-hours of work saved per merged PR. Always shown as an estimate. */
|
|
9
|
+
export const HOURS_SAVED_PER_MERGE = 1.5;
|
|
10
|
+
export const CARD_URL = "https://github.com/RapierCraftStudios/forgedock";
|
|
11
|
+
|
|
12
|
+
import { deflateSync } from "node:zlib";
|
|
13
|
+
|
|
14
|
+
const isNum = (x) => typeof x === "number" && Number.isFinite(x);
|
|
15
|
+
const n0 = (x) => (isNum(x) ? x : 0);
|
|
16
|
+
|
|
17
|
+
/** Sum the report groups (all versions; one repo or all repos) into aggregate card numbers. */
|
|
18
|
+
export function buildCard(report, { includeRepoNames = false, publicRepo = false, attribution = true, windowLabel = "all time", repo = null } = {}) {
|
|
19
|
+
const groups = report?.groups ?? [];
|
|
20
|
+
let merged = 0, completed = 0, closedBeforeCode = 0, gateCatches = 0, usd = 0;
|
|
21
|
+
const repos = new Set();
|
|
22
|
+
for (const g of groups) {
|
|
23
|
+
repos.add(g.repo);
|
|
24
|
+
merged += Math.round(n0(g.flow?.mergedPct) * n0(g.flow?.n));
|
|
25
|
+
completed += n0(g.issueFlow?.closed?.merged);
|
|
26
|
+
closedBeforeCode += n0(g.issueFlow?.closed?.invalid) + n0(g.issueFlow?.closed?.duplicate);
|
|
27
|
+
const q = g.gates ?? {};
|
|
28
|
+
gateCatches += n0(q.acceptance?.blocked) + n0(q.diffSize?.blocked) + n0(q.ci?.blocked) + n0(q.liveness?.blocked);
|
|
29
|
+
usd += n0(g.cost?.usdTotal);
|
|
30
|
+
}
|
|
31
|
+
// `publicRepo` is the user's assertion that the repo is public: it names the repo and links its merged-PR run history.
|
|
32
|
+
const named = (includeRepoNames || publicRepo) && repos.size === 1;
|
|
33
|
+
const runHistory = publicRepo && repo && repos.size === 1 && /^[\w.-]+\/[\w.-]+$/.test(repo) ? `https://github.com/${repo}/pulls?q=is%3Apr+is%3Amerged` : null;
|
|
34
|
+
return {
|
|
35
|
+
window: windowLabel, runHistory,
|
|
36
|
+
scope: named ? [...repos][0] : repos.size === 1 ? "1 repo" : `${repos.size} repos`,
|
|
37
|
+
prsMerged: merged, issuesCompleted: completed, costPerMerge: merged ? usd / merged : null,
|
|
38
|
+
closedBeforeCode, gateCatches, hoursSavedEstimate: merged * HOURS_SAVED_PER_MERGE,
|
|
39
|
+
footer: attribution ? CARD_URL : null,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const usd = (x) => (isNum(x) ? `$${x.toFixed(2)}` : "n/a");
|
|
44
|
+
const rows = (c) => [
|
|
45
|
+
["PRs merged", String(c.prsMerged)], ["Issues completed", String(c.issuesCompleted)], ["Cost per merge", usd(c.costPerMerge)],
|
|
46
|
+
["Issues closed before code (invalid/duplicate)", String(c.closedBeforeCode)], ["Release-gate catches", String(c.gateCatches)],
|
|
47
|
+
["Time saved (estimate)", `~${Math.round(c.hoursSavedEstimate * 10) / 10}h`],
|
|
48
|
+
];
|
|
49
|
+
const esc = (s) => String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
50
|
+
|
|
51
|
+
export function renderCardMarkdown(c) {
|
|
52
|
+
const out = [`# ForgeDock stats card: ${c.scope}, ${c.window}`, "", "| metric | value |", "|---|---|", ...rows(c).map(([a, b]) => `| ${a} | ${b} |`), "",
|
|
53
|
+
`Time saved is an estimate (${HOURS_SAVED_PER_MERGE}h per merged PR), not a measurement.`];
|
|
54
|
+
if (c.runHistory) out.push("", `[Run history](${c.runHistory})`);
|
|
55
|
+
if (c.footer) out.push("", `Made with [ForgeDock](${c.footer})`);
|
|
56
|
+
return out.join("\n");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function renderCardSvg(c) {
|
|
60
|
+
const r = rows(c), h = 120 + r.length * 36 + (c.footer ? 30 : 0) + (c.runHistory ? 20 : 0);
|
|
61
|
+
const lines = r.map(([a, b], i) => `<text x="24" y="${96 + i * 36}" font-size="16">${esc(a)}</text><text x="576" y="${96 + i * 36}" font-size="18" font-weight="bold" text-anchor="end">${esc(b)}</text>`);
|
|
62
|
+
return [`<svg xmlns="http://www.w3.org/2000/svg" width="600" height="${h}" viewBox="0 0 600 ${h}" font-family="sans-serif">`,
|
|
63
|
+
`<rect width="600" height="${h}" rx="12" fill="#0d1117"/><g fill="#e6edf3">`,
|
|
64
|
+
`<text x="24" y="40" font-size="22" font-weight="bold">ForgeDock stats</text><text x="24" y="64" font-size="14" fill="#8b949e">${esc(c.scope)}, ${esc(c.window)}</text>`,
|
|
65
|
+
...lines, `<text x="24" y="${h - (c.footer ? 36 : 12)}" font-size="11" fill="#8b949e">Time saved is an estimate (${HOURS_SAVED_PER_MERGE}h per merged PR).</text>`,
|
|
66
|
+
...(c.runHistory ? [`<text x="24" y="${h - (c.footer ? 52 : 28)}" font-size="11" fill="#58a6ff">Run history: ${esc(c.runHistory)}</text>`] : []),
|
|
67
|
+
...(c.footer ? [`<text x="24" y="${h - 12}" font-size="12" fill="#58a6ff">Made with ForgeDock: ${esc(c.footer)}</text>`] : []), "</g></svg>"].join("\n");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// PNG (forge#5291): dependency-free raster of the same rows (node:zlib + a built-in 5x7 bitmap font, upper-case only).
|
|
71
|
+
const GLYPHS = {
|
|
72
|
+
A: "0E 11 11 1F 11 11 11", B: "1E 11 11 1E 11 11 1E", C: "0E 11 10 10 10 11 0E", D: "1E 11 11 11 11 11 1E", E: "1F 10 10 1E 10 10 1F",
|
|
73
|
+
F: "1F 10 10 1E 10 10 10", G: "0E 11 10 17 11 11 0F", H: "11 11 11 1F 11 11 11", I: "0E 04 04 04 04 04 0E", J: "07 02 02 02 02 12 0C",
|
|
74
|
+
K: "11 12 14 18 14 12 11", L: "10 10 10 10 10 10 1F", M: "11 1B 15 15 11 11 11", N: "11 11 19 15 13 11 11", O: "0E 11 11 11 11 11 0E",
|
|
75
|
+
P: "1E 11 11 1E 10 10 10", Q: "0E 11 11 11 15 12 0D", R: "1E 11 11 1E 14 12 11", S: "0F 10 10 0E 01 01 1E", T: "1F 04 04 04 04 04 04",
|
|
76
|
+
U: "11 11 11 11 11 11 0E", V: "11 11 11 11 11 0A 04", W: "11 11 11 15 15 15 0A", X: "11 11 0A 04 0A 11 11", Y: "11 11 0A 04 04 04 04",
|
|
77
|
+
Z: "1F 01 02 04 08 10 1F", 0: "0E 11 13 15 19 11 0E", 1: "04 0C 04 04 04 04 0E", 2: "0E 11 01 02 04 08 1F", 3: "1F 02 04 02 01 11 0E",
|
|
78
|
+
4: "02 06 0A 12 1F 02 02", 5: "1F 10 1E 01 01 11 0E", 6: "06 08 10 1E 11 11 0E", 7: "1F 01 02 04 08 08 08", 8: "0E 11 11 0E 11 11 0E",
|
|
79
|
+
9: "0E 11 11 0F 01 02 0C", ".": "00 00 00 00 00 0C 0C", ",": "00 00 00 00 0C 04 08", ":": "00 0C 0C 00 0C 0C 00", "-": "00 00 00 1F 00 00 00",
|
|
80
|
+
_: "00 00 00 00 00 00 1F", "/": "01 01 02 04 08 10 10", "~": "00 00 08 15 02 00 00", "(": "02 04 08 08 08 04 02", ")": "08 04 02 02 02 04 08",
|
|
81
|
+
$: "04 0F 14 0E 05 1E 04", "?": "0E 11 01 02 04 00 04", "+": "00 04 04 1F 04 04 00", "=": "00 00 1F 00 1F 00 00", "%": "18 19 02 04 08 13 03",
|
|
82
|
+
};
|
|
83
|
+
const CRC = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
|
|
84
|
+
const crc32 = (b) => { let c = 0xffffffff; for (const x of b) c = CRC[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
|
|
85
|
+
const chunk = (type, data) => {
|
|
86
|
+
const t = Buffer.from(type), len = Buffer.alloc(4), crc = Buffer.alloc(4);
|
|
87
|
+
len.writeUInt32BE(data.length); crc.writeUInt32BE(crc32(Buffer.concat([t, data])));
|
|
88
|
+
return Buffer.concat([len, t, data, crc]);
|
|
89
|
+
};
|
|
90
|
+
const hex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
|
|
91
|
+
|
|
92
|
+
export function renderCardPng(c) {
|
|
93
|
+
const S = 2, ADV = 6 * S, W = 900, r = rows(c), H = 120 + r.length * 36 + 70;
|
|
94
|
+
const px = Buffer.alloc(W * H * 3);
|
|
95
|
+
const rect = (x, y, w, h, col) => { for (let j = y; j < y + h && j < H; j++) for (let i = x; i < x + w && i < W; i++) px.set(col, (j * W + i) * 3); };
|
|
96
|
+
const text = (s, x, y, col, right = false) => {
|
|
97
|
+
const t = String(s).toUpperCase();
|
|
98
|
+
let cx = right ? x - t.length * ADV : x;
|
|
99
|
+
for (const ch of t) {
|
|
100
|
+
const g = ch === " " ? null : (GLYPHS[ch] ?? GLYPHS["?"]).split(" ").map((h) => parseInt(h, 16));
|
|
101
|
+
g?.forEach((bits, ry) => { for (let rx = 0; rx < 5; rx++) if (bits & (16 >> rx)) rect(cx + rx * S, y + ry * S, S, S, col); });
|
|
102
|
+
cx += ADV;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const fg = hex("#e6edf3"), dim = hex("#8b949e"), link = hex("#58a6ff");
|
|
106
|
+
rect(0, 0, W, H, hex("#0d1117"));
|
|
107
|
+
text("FORGEDOCK STATS", 24, 24, fg); text(`${c.scope}, ${c.window}`, 24, 48, dim);
|
|
108
|
+
r.forEach(([a, b], i) => { text(a, 24, 84 + i * 36, fg); text(b, W - 24, 84 + i * 36, fg, true); });
|
|
109
|
+
let y = 84 + r.length * 36 + 8;
|
|
110
|
+
text(`TIME SAVED IS AN ESTIMATE (${HOURS_SAVED_PER_MERGE}H PER MERGED PR).`, 24, y, dim);
|
|
111
|
+
if (c.runHistory) text(`RUN HISTORY: ${c.runHistory}`, 24, (y += 20), link);
|
|
112
|
+
if (c.footer) text(`MADE WITH FORGEDOCK: ${c.footer}`, 24, (y += 20), link);
|
|
113
|
+
const raw = Buffer.alloc((W * 3 + 1) * H);
|
|
114
|
+
for (let j = 0; j < H; j++) px.copy(raw, j * (W * 3 + 1) + 1, j * W * 3, (j + 1) * W * 3);
|
|
115
|
+
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(W); ihdr.writeUInt32BE(H, 4); ihdr[8] = 8; ihdr[9] = 2;
|
|
116
|
+
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
|
|
117
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
4
|
+
import { describe, it, afterEach } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { buildCard, renderCardMarkdown, renderCardPng, renderCardSvg } from "./card.mjs";
|
|
10
|
+
import { parseArgs, readAttribution, runStats } from "./index.mjs";
|
|
11
|
+
import { writeFileSync } from "node:fs";
|
|
12
|
+
|
|
13
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
const TITLE = "SECRET-TITLE-do-not-leak", REPO = "secret-org/private-repo";
|
|
15
|
+
const group = (over = {}) => ({
|
|
16
|
+
version: "1.0.0", repo: REPO, n: 4, flow: { n: 4, mergedPct: 0.5 }, cost: { usdTotal: 10 },
|
|
17
|
+
issueFlow: { closed: { merged: 2, invalid: 1, duplicate: 2, other: 3 } },
|
|
18
|
+
gates: { acceptance: { blocked: 1 }, diffSize: { blocked: 2 }, ci: { blocked: 3 }, liveness: { blocked: 0 } }, ...over,
|
|
19
|
+
});
|
|
20
|
+
// A report whose input carries canary strings: groups never hold titles, but extra fields must not reach the card.
|
|
21
|
+
const report = { groups: [group(), group({ version: "1.1.0", flow: { n: 2, mergedPct: 1 }, cost: { usdTotal: 2 }, title: TITLE })] };
|
|
22
|
+
|
|
23
|
+
let td;
|
|
24
|
+
afterEach(() => { if (td) rmSync(td, { recursive: true, force: true }); td = null; });
|
|
25
|
+
|
|
26
|
+
describe("stats card (forge#5291)", () => {
|
|
27
|
+
it("sums the groups into aggregate numbers", () => {
|
|
28
|
+
const c = buildCard(report);
|
|
29
|
+
assert.equal(c.prsMerged, 4);
|
|
30
|
+
assert.equal(c.issuesCompleted, 4);
|
|
31
|
+
assert.equal(c.closedBeforeCode, 6);
|
|
32
|
+
assert.equal(c.gateCatches, 12);
|
|
33
|
+
assert.equal(c.costPerMerge, 3);
|
|
34
|
+
assert.match(renderCardMarkdown(c), /Time saved \(estimate\)/);
|
|
35
|
+
});
|
|
36
|
+
it("defaults expose no issue titles or repo names, in either format", () => {
|
|
37
|
+
const c = buildCard(report);
|
|
38
|
+
for (const text of [renderCardMarkdown(c), renderCardSvg(c), JSON.stringify(c)]) {
|
|
39
|
+
assert.ok(!text.includes(TITLE), "no title");
|
|
40
|
+
assert.ok(!text.includes(REPO) && !text.includes("private-repo"), "no repo name");
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
it("--include-repo-names opts the repo name in", () => {
|
|
44
|
+
assert.match(renderCardMarkdown(buildCard({ groups: [group()] }, { includeRepoNames: true })), /secret-org\/private-repo/);
|
|
45
|
+
});
|
|
46
|
+
it("footer follows show_attribution and SVG text is escaped", () => {
|
|
47
|
+
assert.match(renderCardMarkdown(buildCard(report)), /ForgeDock\]\(/);
|
|
48
|
+
assert.ok(!renderCardMarkdown(buildCard(report, { attribution: false })).includes("Made with"));
|
|
49
|
+
assert.ok(!renderCardSvg(buildCard(report, { attribution: false })).includes("Made with"));
|
|
50
|
+
assert.ok(!renderCardSvg(buildCard({ groups: [group({ repo: "a<b>&c" })] }, { includeRepoNames: true })).includes("a<b>"));
|
|
51
|
+
});
|
|
52
|
+
it("--public-repo links the run history; default never does", () => {
|
|
53
|
+
const one = { groups: [group()] };
|
|
54
|
+
assert.ok(!renderCardMarkdown(buildCard(one, { repo: REPO })).includes("github.com/secret-org"));
|
|
55
|
+
const c = buildCard(one, { repo: REPO, publicRepo: true });
|
|
56
|
+
assert.match(renderCardMarkdown(c), /\[Run history\]\(https:\/\/github.com\/secret-org\/private-repo\/pulls/);
|
|
57
|
+
assert.match(renderCardSvg(c), /Run history: https:\/\/github.com\/secret-org/);
|
|
58
|
+
assert.throws(() => parseArgs(["--public-repo"]), /need --card/);
|
|
59
|
+
});
|
|
60
|
+
it("renders a valid PNG with deterministic size and an inflatable pixel stream", async () => {
|
|
61
|
+
const { inflateSync } = await import("node:zlib");
|
|
62
|
+
const png = renderCardPng(buildCard({ groups: [] }));
|
|
63
|
+
const h = png.readUInt32BE(20), idatLen = png.readUInt32BE(33);
|
|
64
|
+
assert.equal(inflateSync(png.subarray(41, 41 + idatLen)).length, (900 * 3 + 1) * h);
|
|
65
|
+
assert.deepEqual([...png.subarray(png.length - 8, png.length - 4)], [73, 69, 78, 68]);
|
|
66
|
+
});
|
|
67
|
+
it("validates flags", () => {
|
|
68
|
+
assert.equal(parseArgs(["--card", "--week", "--include-repo-names", "--out", "x"]).card, true);
|
|
69
|
+
assert.throws(() => parseArgs(["--week"]), /need --card/);
|
|
70
|
+
assert.throws(() => parseArgs(["--card", "--week", "--month"]), /mutually exclusive/);
|
|
71
|
+
assert.throws(() => parseArgs(["--card", "--depth"]), /cannot be combined/);
|
|
72
|
+
});
|
|
73
|
+
it("runStats --card renders from the crawl only, writes files, and leaks nothing by default", async () => {
|
|
74
|
+
td = tmpDir("card-");
|
|
75
|
+
const issues = JSON.parse(readFileSync(join(here, "fixtures", "issues.json"), "utf8")).map((i) => ({ ...i, title: TITLE }));
|
|
76
|
+
const calls = [];
|
|
77
|
+
const gh = (args) => { calls.push(args.join(" ")); return JSON.stringify(args.some((a) => /issues\?|issues$/.test(String(a))) && !args.some((a) => /comments/.test(String(a))) ? issues : []); };
|
|
78
|
+
const realOut = process.stdout.write;
|
|
79
|
+
let stdout = "";
|
|
80
|
+
process.stdout.write = (c) => { stdout += c; return true; };
|
|
81
|
+
try { assert.equal(await runStats(["--card", "--month", "--repo", REPO, "--no-cache", "--no-local", "--out", td], { gh, env: {}, releaseTimes: [], onProgress: () => {} }), 0); } finally { process.stdout.write = realOut; }
|
|
82
|
+
assert.ok(calls.length > 0 && calls.every((c) => c.startsWith("api ") || c.includes("repos/")), "only crawl calls");
|
|
83
|
+
for (const text of [stdout, readFileSync(join(td, "stats-card.svg"), "utf8"), readFileSync(join(td, "stats-card.md"), "utf8")]) {
|
|
84
|
+
assert.ok(!text.includes(TITLE) && !text.includes("private-repo"));
|
|
85
|
+
}
|
|
86
|
+
assert.ok(existsSync(join(td, "stats-card.svg")));
|
|
87
|
+
const png = readFileSync(join(td, "stats-card.png"));
|
|
88
|
+
assert.deepEqual([...png.subarray(0, 8)], [137, 80, 78, 71, 13, 10, 26, 10]);
|
|
89
|
+
assert.equal(png.readUInt32BE(16), 900);
|
|
90
|
+
assert.ok(!png.includes(Buffer.from(TITLE)));
|
|
91
|
+
assert.match(stdout, /last 30 days/);
|
|
92
|
+
});
|
|
93
|
+
it("--json card output is aggregate-only by default and names the repo only when opted in", async () => {
|
|
94
|
+
const run = async (extra) => {
|
|
95
|
+
const realOut = process.stdout.write; let out = "";
|
|
96
|
+
process.stdout.write = (c) => { out += c; return true; };
|
|
97
|
+
try { assert.equal(await runStats(["--card", "--json", "--repo", REPO, "--no-cache", "--no-local", ...extra], { gh: () => "[]", env: {}, releaseTimes: [], onProgress: () => {} }), 0); } finally { process.stdout.write = realOut; }
|
|
98
|
+
return out;
|
|
99
|
+
};
|
|
100
|
+
assert.ok(!(await run([])).includes("private-repo"));
|
|
101
|
+
assert.ok(!(await run(["--week"])).includes(TITLE));
|
|
102
|
+
});
|
|
103
|
+
it("readAttribution honours branding.show_attribution in forge.yaml", () => {
|
|
104
|
+
td = tmpDir("card-attr-");
|
|
105
|
+
assert.equal(readAttribution(td), true);
|
|
106
|
+
writeFileSync(join(td, "forge.yaml"), "branding:\n show_attribution: false\n");
|
|
107
|
+
assert.equal(readAttribution(td), false);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
@@ -132,6 +132,7 @@ describe("conformance outcomes: 2x2 and conclusion (#5210 R2)", () => {
|
|
|
132
132
|
function graphqlGh(total, calls = []) {
|
|
133
133
|
return async (args) => {
|
|
134
134
|
calls.push(args);
|
|
135
|
+
if (args[0] === "api" && args[1] === "graphql" && args.some((a) => /issueOrPullRequest/.test(a))) return JSON.stringify({ data: { repository: {} } }); // #5530 numbers batch
|
|
135
136
|
if (args[0] === "api" && args[1] === "graphql") {
|
|
136
137
|
const after = args.find((a) => a.startsWith("after="));
|
|
137
138
|
const start = after ? Number(after.slice(6)) : 0;
|
|
@@ -171,7 +172,7 @@ describe("conformance outcomes: read only (#5210 R3)", () => {
|
|
|
171
172
|
assert.equal(rep.sources.merged_prs, 120);
|
|
172
173
|
assert.equal(rep.sources.graphql_calls, 2);
|
|
173
174
|
assert.equal(rep.conclusion, OUTCOME_INSUFFICIENT);
|
|
174
|
-
assert.equal(calls.filter((a) => a[1] === "graphql").length, 2);
|
|
175
|
+
assert.equal(calls.filter((a) => a[1] === "graphql" && a.some((x) => x.startsWith("q="))).length, 2);
|
|
175
176
|
assert.ok(calls.every((a) => !isWrite(a)), "no GitHub write");
|
|
176
177
|
});
|
|
177
178
|
it("buildReport bounds the crawl and uses min n 20 unless --min-n is passed", async () => {
|
package/bin/stats/depth.mjs
CHANGED
|
@@ -89,7 +89,7 @@ export function depthRows(events, { repo = null, sinceMs = null, issue = null }
|
|
|
89
89
|
const lines = (raw) => String(raw ?? "").split("\n").filter((l) => l.trim()).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
90
90
|
|
|
91
91
|
const DEFECT_CACHE_V = 2;
|
|
92
|
-
const CONCURRENCY = 4
|
|
92
|
+
const CONCURRENCY = 8; // #5530: was 4
|
|
93
93
|
const defectCachePath = (repo, env) => join(cacheDir(repo, env), "depth-defects.json");
|
|
94
94
|
function loadDefectCache(repo, env) {
|
|
95
95
|
try { const c = JSON.parse(readFileSync(defectCachePath(repo, env), "utf8")); if (c?.v === DEFECT_CACHE_V) return { v: DEFECT_CACHE_V, defects: c.defects ?? {}, shas: c.shas ?? {} }; } catch { /* refetch */ }
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5530: the real defaultGh and the real crawls run against a scripted `gh` binary on PATH that stands in for the GitHub
|
|
4
|
+
// service (its replies, its HTTP 5xx stderr and exit codes). No JS function of the code under test is substituted.
|
|
5
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
6
|
+
import { test, before, after, beforeEach } from "node:test";
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { delimiter, join } from "node:path";
|
|
10
|
+
import * as source from "./github-source.mjs";
|
|
11
|
+
|
|
12
|
+
const { defaultGh, fetchGithubRecords } = source;
|
|
13
|
+
import { gatherDefects } from "./depth.mjs";
|
|
14
|
+
import { gatherCompounding } from "./compounding.mjs";
|
|
15
|
+
|
|
16
|
+
const BIN = String.raw`#!/usr/bin/env node
|
|
17
|
+
const fs = require("fs"), path = require("path");
|
|
18
|
+
const dir = __dirname, args = process.argv.slice(2), line = args.join(" ");
|
|
19
|
+
fs.appendFileSync(path.join(dir, "calls.log"), JSON.stringify(args) + "\n");
|
|
20
|
+
const plan = JSON.parse(process.env.FAKE_GH_PLAN || "{}");
|
|
21
|
+
const calls = fs.readFileSync(path.join(dir, "calls.log"), "utf8").trim().split("\n").map((l) => JSON.parse(l).join(" "));
|
|
22
|
+
for (const f of plan.failures ?? []) {
|
|
23
|
+
if (!new RegExp(f.match).test(line)) continue;
|
|
24
|
+
if (calls.filter((c) => new RegExp(f.match).test(c)).length <= f.times) { process.stderr.write(f.stderr + "\n"); process.exit(1); }
|
|
25
|
+
}
|
|
26
|
+
if (args[0] === "api" && args[1] === "graphql") {
|
|
27
|
+
const q = args.find((a) => a.startsWith("query=")), full = /comments\(first/.test(q), repo = {};
|
|
28
|
+
for (const m of q.matchAll(/i(\d+): issueOrPullRequest/g)) {
|
|
29
|
+
const node = plan.store[m[1]] ?? null;
|
|
30
|
+
repo["i" + m[1]] = node && (full ? node : { __typename: node.__typename, updatedAt: node.updatedAt });
|
|
31
|
+
}
|
|
32
|
+
process.stdout.write(JSON.stringify({ data: { repository: repo } }));
|
|
33
|
+
process.exit(0);
|
|
34
|
+
}
|
|
35
|
+
const c = /repos\/[^/]+\/[^/]+\/issues\/(\d+)\/comments$/.exec(line);
|
|
36
|
+
if (c) { process.stdout.write(JSON.stringify(plan.restComments?.[c[1]] ?? [])); process.exit(0); }
|
|
37
|
+
for (const r of plan.replies ?? []) if (new RegExp(r.match).test(line)) { process.stdout.write(r.out); process.exit(0); }
|
|
38
|
+
process.stdout.write("[]");
|
|
39
|
+
`;
|
|
40
|
+
|
|
41
|
+
const ENV = { FORGE_TRAIL_TRUSTED_ASSOCIATIONS: "OWNER,MEMBER,COLLABORATOR" };
|
|
42
|
+
const DAY = 86400000;
|
|
43
|
+
const iso = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
44
|
+
const T0 = Date.UTC(2026, 9, 1);
|
|
45
|
+
let dir, saved;
|
|
46
|
+
const plan = (p) => { process.env.FAKE_GH_PLAN = JSON.stringify(p); writeFileSync(join(dir, "calls.log"), ""); }; // per-test behaviour via env
|
|
47
|
+
const calls = () => readFileSync(join(dir, "calls.log"), "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l));
|
|
48
|
+
|
|
49
|
+
before(() => {
|
|
50
|
+
dir = tmpDir("gh-retry-");
|
|
51
|
+
writeFileSync(join(dir, "gh"), BIN);
|
|
52
|
+
chmodSync(join(dir, "gh"), 0o755);
|
|
53
|
+
saved = { PATH: process.env.PATH, RETRY: process.env.FORGE_STATS_GH_RETRY_MS, PLAN: process.env.FAKE_GH_PLAN };
|
|
54
|
+
process.env.PATH = `${dir}${delimiter}${process.env.PATH}`;
|
|
55
|
+
process.env.FORGE_STATS_GH_RETRY_MS = "1";
|
|
56
|
+
});
|
|
57
|
+
after(() => {
|
|
58
|
+
process.env.PATH = saved.PATH;
|
|
59
|
+
if (saved.PLAN === undefined) delete process.env.FAKE_GH_PLAN; else process.env.FAKE_GH_PLAN = saved.PLAN;
|
|
60
|
+
if (saved.RETRY === undefined) delete process.env.FORGE_STATS_GH_RETRY_MS; else process.env.FORGE_STATS_GH_RETRY_MS = saved.RETRY;
|
|
61
|
+
});
|
|
62
|
+
beforeEach(() => plan({}));
|
|
63
|
+
|
|
64
|
+
const telemetry = (issue, eid) => `<!-- FORGE:TELEMETRY v1 -->\n\`\`\`jsonl\n${JSON.stringify({ v: 1, ts: iso(T0), repo: "o/r", issue, run: `r_${issue}`, eid, event: "phase_attempt", phase: "build" })}\n\`\`\``;
|
|
65
|
+
const node = (n, { pr = false, comments = [], updatedAt = iso(T0 + n * 60000), more = false } = {}) => ({
|
|
66
|
+
__typename: pr ? "PullRequest" : "Issue", number: n, createdAt: iso(T0), closedAt: iso(T0 + DAY), updatedAt, milestone: n === 1 ? { title: "v1" } : null,
|
|
67
|
+
labels: { nodes: n === 1 ? [{ name: "bug" }] : [] }, author: { __typename: n === 2 ? "Bot" : "User", login: "u" },
|
|
68
|
+
comments: { pageInfo: { hasNextPage: more }, nodes: comments } });
|
|
69
|
+
const trusted = (issue, eid) => ({ body: telemetry(issue, eid), authorAssociation: "MEMBER", author: { __typename: "User", login: "m" } });
|
|
70
|
+
const untrusted = (issue, eid) => ({ body: telemetry(issue, eid), authorAssociation: "NONE", author: { __typename: "User", login: "mallory" } });
|
|
71
|
+
const store = (n, extra = {}) => Object.fromEntries(Array.from({ length: n }, (_, i) => [i + 1, node(i + 1, {
|
|
72
|
+
pr: (i + 1) % 10 === 0, comments: (i + 1) % 5 === 0 ? [trusted(i + 1, `e${i + 1}`), untrusted(i + 1, `x${i + 1}`)] : [], ...(extra[i + 1] ?? {}) })]));
|
|
73
|
+
const range = (n) => Array.from({ length: n }, (_, i) => i + 1);
|
|
74
|
+
|
|
75
|
+
test("defaultGh retries a 504 on the FORGE:GUARD search so --compounding gathers instead of aborting (#5530 compounding)", async () => {
|
|
76
|
+
plan({ failures: [{ match: "^issue list", times: 1, stderr: "HTTP 504: Gateway Timeout (https://api.github.com/graphql)" }] });
|
|
77
|
+
const r = await gatherCompounding({ repo: "o/r", gh: defaultGh, cwd: dir });
|
|
78
|
+
assert.deepEqual(r.guards, []);
|
|
79
|
+
assert.equal(calls().filter((a) => a[0] === "issue" && a[1] === "list").length, 2);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("a non-transient error is not retried (#5530 non-transient)", async () => {
|
|
83
|
+
plan({ failures: [{ match: "issues/1$", times: 9, stderr: "gh: Not Found (HTTP 404)" }] });
|
|
84
|
+
await assert.rejects(defaultGh(["api", "repos/o/r/issues/1"]), /404/);
|
|
85
|
+
assert.equal(calls().length, 1);
|
|
86
|
+
plan({ failures: [{ match: "issues/1$", times: 9, stderr: "HTTP 503: Service Unavailable" }] });
|
|
87
|
+
await assert.rejects(defaultGh(["api", "repos/o/r/issues/1"]), /503/);
|
|
88
|
+
assert.equal(calls().length, 4, "4 attempts, then the 5xx is thrown");
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("defaultGh retry keeps the --depth defect column on a transient 504 (#5530 depth)", async () => {
|
|
92
|
+
plan({ failures: [{ match: "search/issues", times: 1, stderr: "gh: HTTP 504: We couldn't respond to your request in time." }], replies: [{ match: ".", out: "" }] });
|
|
93
|
+
const rows = [{ issue: 1, pr: 2, merged: true, endTs: iso(T0) }];
|
|
94
|
+
const d = await gatherDefects({ repo: "o/r", gh: defaultGh, rows });
|
|
95
|
+
assert.equal(d.get(1).defect, false);
|
|
96
|
+
assert.equal(calls().filter((a) => a.some((x) => x.startsWith("search/issues"))).length, 2);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("writes are never retried, even on a 5xx (#5530 write)", async () => {
|
|
100
|
+
plan({ failures: [{ match: "^pr comment", times: 9, stderr: "HTTP 504: Gateway Timeout" }] });
|
|
101
|
+
await assert.rejects(defaultGh(["pr", "comment", "5", "-R", "o/r", "--body", "x"]), /504/);
|
|
102
|
+
assert.equal(calls().length, 1);
|
|
103
|
+
const { isReadOnlyGh } = source;
|
|
104
|
+
assert.equal(isReadOnlyGh(["api", "-X", "POST", "repos/o/r/issues"]), false);
|
|
105
|
+
assert.equal(isReadOnlyGh(["api", "repos/o/r/issues/1/comments", "-f", "body=x"]), false);
|
|
106
|
+
assert.equal(isReadOnlyGh(["api", "graphql", "-f", "query=mutation { x }"]), false);
|
|
107
|
+
assert.equal(isReadOnlyGh(["api", "graphql", "-f", "query=query { x }", "-F", "first=10"]), true);
|
|
108
|
+
assert.equal(isReadOnlyGh(["issue", "list", "-R", "o/r"]), true);
|
|
109
|
+
assert.equal(isReadOnlyGh(["api", "--paginate", "repos/o/r/issues/1/events"]), true);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("fetchGithubRecords numbers mode batches through GraphQL (#5530 batch)", async () => {
|
|
113
|
+
plan({ store: store(50) });
|
|
114
|
+
const r = await fetchGithubRecords({ repo: "o/r", gh: defaultGh, env: ENV, numbers: range(50), useCache: false });
|
|
115
|
+
assert.ok(calls().length <= 3, `gh spawned ${calls().length} times`);
|
|
116
|
+
assert.equal(r.items.length, 50);
|
|
117
|
+
assert.deepEqual(r.records.map((x) => x.eid).sort(), range(10).map((i) => `e${i * 5}`).sort(), "only trusted telemetry");
|
|
118
|
+
const one = r.items.find((i) => i.number === 1), ten = r.items.find((i) => i.number === 10), two = r.items.find((i) => i.number === 2);
|
|
119
|
+
assert.deepEqual({ isPr: one.isPr, milestone: one.milestone, labels: one.labels, closedAt: one.closedAt }, { isPr: false, milestone: "v1", labels: ["bug"], closedAt: iso(T0 + DAY) });
|
|
120
|
+
assert.equal(ten.isPr, true);
|
|
121
|
+
assert.equal(two.authorType, "Bot");
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("an issue with over 100 comments falls back to the REST comments pages; a 5xx-failing batch is halved (#5530 batch)", async () => {
|
|
125
|
+
plan({ store: store(20, { 7: { more: true } }), restComments: { 7: [{ body: telemetry(7, "late"), author_association: "OWNER", user: { type: "User", login: "o" } }] },
|
|
126
|
+
failures: [{ match: "i1: issueOrPullRequest.*i20: issueOrPullRequest", times: 99, stderr: "HTTP 502: Bad Gateway" }] });
|
|
127
|
+
const r = await fetchGithubRecords({ repo: "o/r", gh: defaultGh, env: ENV, numbers: range(20), useCache: false });
|
|
128
|
+
assert.equal(r.items.length, 20);
|
|
129
|
+
assert.ok(r.records.some((x) => x.eid === "late"));
|
|
130
|
+
assert.ok(calls().some((a) => a.includes("repos/o/r/issues/7/comments")));
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test("per-number cache keyed by updatedAt skips unchanged issues (#5530 cache)", async () => {
|
|
134
|
+
const env = { ...ENV, FORGE_STATS_CACHE_DIR: join(dir, "cache") };
|
|
135
|
+
plan({ store: store(50) });
|
|
136
|
+
const first = await fetchGithubRecords({ repo: "o/r", gh: defaultGh, env, numbers: range(50) });
|
|
137
|
+
plan({ store: store(50) });
|
|
138
|
+
const second = await fetchGithubRecords({ repo: "o/r", gh: defaultGh, env, numbers: range(50) });
|
|
139
|
+
assert.equal(calls().length, 1, "only the light updatedAt query");
|
|
140
|
+
assert.deepEqual(second.records, first.records);
|
|
141
|
+
assert.deepEqual(second.items, first.items);
|
|
142
|
+
plan({ store: store(50, { 3: { updatedAt: iso(T0 + 9 * DAY), comments: [trusted(3, "new")] } }) });
|
|
143
|
+
const third = await fetchGithubRecords({ repo: "o/r", gh: defaultGh, env, numbers: range(50) });
|
|
144
|
+
assert.equal(calls().length, 2);
|
|
145
|
+
assert.match(calls()[1].find((a) => a.startsWith("query=")), /i3: issueOrPullRequest/);
|
|
146
|
+
assert.doesNotMatch(calls()[1].find((a) => a.startsWith("query=")), /i4: issueOrPullRequest/);
|
|
147
|
+
assert.ok(third.records.some((x) => x.eid === "new"));
|
|
148
|
+
const off = { ...ENV, FORGE_STATS_CACHE_DIR: join(dir, "cache-off") };
|
|
149
|
+
plan({ store: store(5) });
|
|
150
|
+
await fetchGithubRecords({ repo: "o/r", gh: defaultGh, env: off, numbers: range(5), useCache: false });
|
|
151
|
+
assert.equal(existsSync(join(dir, "cache-off")), false);
|
|
152
|
+
});
|
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { execFile } from "node:child_process";
|
|
13
13
|
import { promisify } from "node:util";
|
|
14
|
-
import {
|
|
14
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { cacheDir, emptyCache, loadCache, saveCache } from "./cache.mjs";
|
|
15
17
|
import { unflattenPhases } from "../lean/phaseledger.mjs";
|
|
16
18
|
|
|
17
19
|
export const MARKER_RE = /^<!-- FORGE:TELEMETRY v1( part=(\d+))? -->/;
|
|
@@ -20,10 +22,38 @@ export const isValidRepo = (r) => typeof r === "string" && OWNER_REPO_RE.test(r)
|
|
|
20
22
|
|
|
21
23
|
const execFileAsync = promisify(execFile);
|
|
22
24
|
|
|
23
|
-
|
|
25
|
+
const GH_TRIES = 4;
|
|
26
|
+
const WRITE_FLAGS = new Set(["-X", "--method", "-f", "-F", "--field", "--raw-field", "--input"]);
|
|
27
|
+
/** True for a gh invocation that only reads (#5530): safe to repeat. Writes (comments, edits, -X/-f calls) never are. */
|
|
28
|
+
export function isReadOnlyGh(args = []) {
|
|
29
|
+
const [a, b] = args;
|
|
30
|
+
if (a === "api") {
|
|
31
|
+
if (b === "graphql") { const q = args.find((x) => typeof x === "string" && x.startsWith("query=")); return Boolean(q) && !/^query=\s*mutation\b/.test(q); }
|
|
32
|
+
return !args.some((x) => WRITE_FLAGS.has(x) || /^(--method=|-X.)/.test(String(x)));
|
|
33
|
+
}
|
|
34
|
+
return a === "search" || b === "list" || b === "view";
|
|
35
|
+
}
|
|
36
|
+
const TRANSIENT_RE = /HTTP 5\d\d|\b50[234]\b|bad gateway|gateway time|timed? ?out|ETIMEDOUT|ECONNRESET|EAI_AGAIN|secondary rate limit|abuse/i;
|
|
37
|
+
/** A 5xx, timeout, connection reset or secondary rate limit (#5530). Reads stderr when present: the message embeds the argv. */
|
|
38
|
+
export const isTransientGhError = (err) => Boolean(err?.killed) || TRANSIENT_RE.test(err?.stderr ? String(err.stderr) : String(err?.message ?? err));
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Async `gh` runner (concurrency needs it). A test stub may stay synchronous: every call site awaits the result.
|
|
42
|
+
* #5530: a read-only call that fails transiently is retried up to GH_TRIES times with exponential backoff (base
|
|
43
|
+
* FORGE_STATS_GH_RETRY_MS, default 1000 ms, doubling); any other failure, and every write, is thrown at once.
|
|
44
|
+
*/
|
|
24
45
|
export async function defaultGh(args) {
|
|
25
|
-
const
|
|
26
|
-
|
|
46
|
+
const tries = isReadOnlyGh(args) ? GH_TRIES : 1;
|
|
47
|
+
for (let i = 1; ; i++) {
|
|
48
|
+
try {
|
|
49
|
+
const { stdout } = await execFileAsync("gh", args, { encoding: "utf8", timeout: 120000, maxBuffer: 256 * 1024 * 1024 });
|
|
50
|
+
return stdout;
|
|
51
|
+
} catch (err) {
|
|
52
|
+
if (i >= tries || !isTransientGhError(err)) throw err;
|
|
53
|
+
const base = Number(process.env.FORGE_STATS_GH_RETRY_MS ?? 1000);
|
|
54
|
+
await new Promise((r) => setTimeout(r, (Number.isFinite(base) && base >= 0 ? base : 1000) * 2 ** (i - 1)));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
27
57
|
}
|
|
28
58
|
|
|
29
59
|
/** `gh api --paginate` prints one JSON array per page; join them into one flat array. */
|
|
@@ -238,25 +268,128 @@ async function scanWindowComments(call, repo, from, env, onPage) {
|
|
|
238
268
|
|
|
239
269
|
/**
|
|
240
270
|
* Targeted crawl (#5363): only the given issue/PR numbers are read (metadata plus all comments), with no repo-wide comments
|
|
241
|
-
* scan and no issue listing. Coverage is partial, so
|
|
271
|
+
* scan and no issue listing. Coverage is partial, so cache.json is neither read nor written (its watermark would lie);
|
|
272
|
+
* #5530: numbers are read in GraphQL batches and kept in a per-number cache (numbers.json) keyed by updatedAt instead.
|
|
242
273
|
*/
|
|
243
|
-
async function fetchNumbers({ repo, numbers, gh, env, onProgress,
|
|
274
|
+
async function fetchNumbers({ repo, numbers, gh, env, onProgress, now, useCache = false, refresh = false }) {
|
|
244
275
|
const list = [...new Set(numbers.filter((n) => Number.isSafeInteger(n) && n > 0))].sort((a, b) => a - b);
|
|
245
|
-
const
|
|
276
|
+
const byNumber = new Map(), t0 = now();
|
|
246
277
|
let apiCalls = 0, done = 0;
|
|
278
|
+
const call = async (args) => { apiCalls++; return gh(args); };
|
|
247
279
|
const eta = () => (done > 0 && done < list.length ? Math.round(((now() - t0) / done) * (list.length - done)) : 0);
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
280
|
+
const tick = () => onProgress({ phase: "telemetry", done: ++done, total: list.length, etaMs: eta() });
|
|
281
|
+
// #5530: per-number cache keyed by updatedAt (no watermark, so a partial crawl cannot under-report). Only closed items are
|
|
282
|
+
// reused: a telemetry comment edited in place does not bump updatedAt, and edits happen while the lane is still open.
|
|
283
|
+
const cache = useCache && !refresh ? loadNumbersCache(repo, env) : { v: NUMBERS_CACHE_V, items: {} };
|
|
284
|
+
let todo = list;
|
|
285
|
+
if (useCache && !refresh && list.some((n) => cache.items[n])) {
|
|
286
|
+
const fresh = await updatedAtOf(call, repo, list);
|
|
287
|
+
todo = list.filter((n) => {
|
|
288
|
+
const c = cache.items[n];
|
|
289
|
+
if (!c || !c.item?.closedAt || fresh.get(n) == null || c.updatedAt !== fresh.get(n)) return true;
|
|
290
|
+
byNumber.set(n, { ...c.item, records: c.records });
|
|
291
|
+
tick();
|
|
292
|
+
return false;
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
const fetched = new Map();
|
|
296
|
+
const batches = [];
|
|
297
|
+
for (let i = 0; i < todo.length; i += GQL_BATCH) batches.push(todo.slice(i, i + GQL_BATCH));
|
|
298
|
+
await pool(batches, GQL_CONCURRENCY, async (batch) => {
|
|
299
|
+
for (const { n, item, records } of await fetchBatch(call, repo, batch, env)) {
|
|
300
|
+
if (item) { byNumber.set(n, { ...item, records }); fetched.set(n, { updatedAt: item.updatedAt, item, records }); }
|
|
301
|
+
tick();
|
|
302
|
+
}
|
|
254
303
|
});
|
|
304
|
+
if (useCache) {
|
|
305
|
+
for (const [n, e] of fetched) cache.items[n] = e;
|
|
306
|
+
saveNumbersCache(repo, env, cache);
|
|
307
|
+
}
|
|
308
|
+
const items = list.filter((n) => byNumber.has(n)).map((n) => byNumber.get(n));
|
|
255
309
|
const seen = new Set(), records = [];
|
|
256
310
|
for (const it of items) for (const r of it.records) if (!seen.has(r.eid)) { seen.add(r.eid); records.push(r); }
|
|
257
311
|
return { items, records, fetched: list.length, fromCache: false, apiCalls, coveredFrom: null };
|
|
258
312
|
}
|
|
259
313
|
|
|
314
|
+
const GQL_BATCH = 20;
|
|
315
|
+
const GQL_MIN_BATCH = 5;
|
|
316
|
+
const GQL_CONCURRENCY = 4;
|
|
317
|
+
const GQL_LIGHT_BATCH = 100;
|
|
318
|
+
const NUMBERS_CACHE_V = 1;
|
|
319
|
+
const ITEM_FIELDS = "number createdAt closedAt updatedAt milestone { title } labels(first: 50) { nodes { name } } author { __typename login } "
|
|
320
|
+
+ "comments(first: 100) { pageInfo { hasNextPage } nodes { body authorAssociation author { __typename login } } }";
|
|
321
|
+
const ownerName = (repo) => { const [owner, name] = repo.split("/"); return ["-f", `owner=${owner}`, "-f", `name=${name}`]; };
|
|
322
|
+
const gqlQuery = (nums, fields) => `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${
|
|
323
|
+
nums.map((n) => `i${n}: issueOrPullRequest(number: ${n}) { __typename ... on Issue { ${fields} } ... on PullRequest { ${fields} } }`).join(" ")} } }`;
|
|
324
|
+
|
|
325
|
+
/** gh exits non-zero when any alias is NOT_FOUND but still prints the data for the rest: keep it, as the REST path skipped a missing item's peers. */
|
|
326
|
+
async function gql(call, repo, nums, fields) {
|
|
327
|
+
let raw;
|
|
328
|
+
try { raw = await call(["api", "graphql", "-f", `query=${gqlQuery(nums, fields)}`, ...ownerName(repo)]); } catch (err) {
|
|
329
|
+
let partial = null;
|
|
330
|
+
try { partial = JSON.parse(String(err?.stdout ?? "")); } catch { /* none */ }
|
|
331
|
+
if (!partial?.data?.repository) throw err;
|
|
332
|
+
raw = err.stdout;
|
|
333
|
+
}
|
|
334
|
+
const data = typeof raw === "string" ? JSON.parse(raw.trim() || "{}") : raw;
|
|
335
|
+
if (!data?.data?.repository) throw new Error(`GraphQL: ${(data?.errors ?? []).map((e) => e?.message).join("; ") || "no repository in response"}`);
|
|
336
|
+
return data.data.repository;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** A GraphQL issue/PR node in the REST shapes meta(), parseTelemetryComments() and isTrusted() read. */
|
|
340
|
+
export function restOfNode(node) {
|
|
341
|
+
const user = (a) => ({ type: a?.__typename ?? null, login: a?.login ?? null });
|
|
342
|
+
return {
|
|
343
|
+
item: { number: node.number, ...(node.__typename === "PullRequest" ? { pull_request: {} } : {}), created_at: node.createdAt ?? null, closed_at: node.closedAt ?? null,
|
|
344
|
+
updated_at: node.updatedAt ?? null, milestone: node.milestone ?? null, labels: (node.labels?.nodes ?? []).map((l) => ({ name: l?.name })), user: user(node.author) },
|
|
345
|
+
comments: (node.comments?.nodes ?? []).map((c) => ({ body: c?.body ?? "", author_association: c?.authorAssociation ?? null, user: user(c?.author) })),
|
|
346
|
+
moreComments: Boolean(node.comments?.pageInfo?.hasNextPage),
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** One batch of numbers -> [{n, item, records}]; a transient failure that survives gh's retries halves the batch (down to GQL_MIN_BATCH). */
|
|
351
|
+
async function fetchBatch(call, repo, nums, env) {
|
|
352
|
+
let repoData;
|
|
353
|
+
try { repoData = await gql(call, repo, nums, ITEM_FIELDS); } catch (err) {
|
|
354
|
+
if (nums.length <= GQL_MIN_BATCH || !isTransientGhError(err)) throw err;
|
|
355
|
+
const half = Math.ceil(nums.length / 2);
|
|
356
|
+
return [...await fetchBatch(call, repo, nums.slice(0, half), env), ...await fetchBatch(call, repo, nums.slice(half), env)];
|
|
357
|
+
}
|
|
358
|
+
const out = [];
|
|
359
|
+
for (const n of nums) {
|
|
360
|
+
const node = repoData[`i${n}`];
|
|
361
|
+
if (!node || !Number.isInteger(node.number)) { out.push({ n, item: null, records: [] }); continue; }
|
|
362
|
+
const { item, comments, moreComments } = restOfNode(node);
|
|
363
|
+
const all = moreComments ? parsePages(await call(["api", "--paginate", `repos/${repo}/issues/${n}/comments`])) : comments;
|
|
364
|
+
out.push({ n, item: meta(item), records: parseTelemetryComments(all, env) });
|
|
365
|
+
}
|
|
366
|
+
return out;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Map number -> updatedAt in one light GraphQL call per GQL_LIGHT_BATCH numbers. */
|
|
370
|
+
async function updatedAtOf(call, repo, list) {
|
|
371
|
+
const out = new Map();
|
|
372
|
+
for (let i = 0; i < list.length; i += GQL_LIGHT_BATCH) {
|
|
373
|
+
const nums = list.slice(i, i + GQL_LIGHT_BATCH), data = await gql(call, repo, nums, "updatedAt");
|
|
374
|
+
for (const n of nums) if (data[`i${n}`]?.updatedAt) out.set(n, data[`i${n}`].updatedAt);
|
|
375
|
+
}
|
|
376
|
+
return out;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const numbersCachePath = (repo, env) => join(cacheDir(repo, env), "numbers.json");
|
|
380
|
+
function loadNumbersCache(repo, env) {
|
|
381
|
+
try { const c = JSON.parse(readFileSync(numbersCachePath(repo, env), "utf8")); if (c?.v === NUMBERS_CACHE_V && c.items && typeof c.items === "object") return c; } catch { /* refetch */ }
|
|
382
|
+
return { v: NUMBERS_CACHE_V, items: {} };
|
|
383
|
+
}
|
|
384
|
+
function saveNumbersCache(repo, env, c) {
|
|
385
|
+
try {
|
|
386
|
+
mkdirSync(cacheDir(repo, env), { recursive: true });
|
|
387
|
+
const tmp = `${numbersCachePath(repo, env)}.${process.pid}.tmp`;
|
|
388
|
+
writeFileSync(tmp, JSON.stringify(c));
|
|
389
|
+
renameSync(tmp, numbersCachePath(repo, env));
|
|
390
|
+
} catch { /* a cache never fails the report */ }
|
|
391
|
+
}
|
|
392
|
+
|
|
260
393
|
/**
|
|
261
394
|
* Fetch (or incrementally refresh) the repo's issues, PRs and trusted telemetry records. Async; `gh` may be sync or async.
|
|
262
395
|
* `since` (ISO) bounds the crawl: only items and comments updated on/after it are read, plus whatever the cache already
|
|
@@ -269,7 +402,7 @@ export async function fetchGithubRecords({ repo, since = null, refresh = false,
|
|
|
269
402
|
onProgress = () => {}, concurrency = DEFAULT_CONCURRENCY, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now,
|
|
270
403
|
rateCheck = gh === defaultGh, numbers = null } = {}) {
|
|
271
404
|
if (!isValidRepo(repo)) throw new Error(`invalid repo: ${repo}`);
|
|
272
|
-
if (Array.isArray(numbers)) return fetchNumbers({ repo, numbers, gh, env, onProgress,
|
|
405
|
+
if (Array.isArray(numbers)) return fetchNumbers({ repo, numbers, gh, env, onProgress, now, useCache, refresh });
|
|
273
406
|
const cache = useCache && !refresh ? loadCache(repo, env) : emptyCache();
|
|
274
407
|
const start = since ?? null;
|
|
275
408
|
const hasCover = cache.watermark != null;
|