forgedock 1.56.0 → 1.57.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 +1 -0
- package/bin/engine/phases.mjs +4 -3
- package/bin/engine-cli.mjs +46 -10
- package/bin/forgedock.mjs +52 -3
- package/bin/gc.mjs +43 -6
- package/bin/help-text.mjs +3 -1
- 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 +88 -17
- package/bin/lean/conformance.test.mjs +98 -3
- package/bin/lean/decisions.mjs +86 -1
- package/bin/lean/decisions.test.mjs +21 -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 +12 -2
- package/bin/lean/issuewatch-parity.test.mjs +26 -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 +72 -21
- package/bin/lean/lean.test.mjs +149 -3
- 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 +25 -0
- package/bin/lean/release-config.mjs +158 -0
- package/bin/lean/release-config.test.mjs +109 -0
- package/bin/lean/release-control.mjs +148 -0
- package/bin/lean/release-control.test.mjs +143 -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-ledger.mjs +160 -0
- package/bin/lean/release-ledger.test.mjs +226 -0
- package/bin/lean/release-minutes.mjs +92 -0
- package/bin/lean/release-minutes.test.mjs +99 -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-unitmap.mjs +35 -0
- package/bin/lean/release-unitmap.test.mjs +41 -0
- package/bin/lean/release.mjs +177 -19
- package/bin/lean/release.test.mjs +40 -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 +75 -1
- 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.test.sh +3 -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,133 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { STATUS_SEP, parseStatus, renderStatus, putSection, writeStatus, findStatus, findLeading, hasSection, sectionText, commentId, isStatusPost, isUpsertPost,
|
|
6
|
+
postStatusSection, postUpsert, clearPipelineLabels, pipelineLabels, isPipelineLabel } from "./statuscomment.mjs";
|
|
7
|
+
|
|
8
|
+
const BOT = { author: { login: "rapiercraft-forgedock" }, authorAssociation: "CONTRIBUTOR" };
|
|
9
|
+
const trusted = (c) => c.author?.login === "rapiercraft-forgedock";
|
|
10
|
+
const url = (id) => `https://github.com/o/r/issues/7#issuecomment-${id}`;
|
|
11
|
+
|
|
12
|
+
describe("#5592 status comment format", () => {
|
|
13
|
+
it("renders sections that keep their own marker lines and parses them back", () => {
|
|
14
|
+
let s = putSection(new Map(), ["FORGE:STARTED"], "Started work on #7.");
|
|
15
|
+
s = putSection(s, ["FORGE:TRAJECTORY", "FORGE:WORK-ON"], "## Trajectory\nmerged at abc1234");
|
|
16
|
+
const body = renderStatus(s);
|
|
17
|
+
assert.ok(body.startsWith("<!-- FORGE:STATUS -->\n"));
|
|
18
|
+
const back = parseStatus(body);
|
|
19
|
+
assert.deepEqual([...back.keys()], ["FORGE:STARTED", "FORGE:TRAJECTORY"]);
|
|
20
|
+
assert.deepEqual(back.get("FORGE:TRAJECTORY").markers, ["FORGE:TRAJECTORY", "FORGE:WORK-ON"]);
|
|
21
|
+
assert.equal(sectionText(body, "FORGE:TRAJECTORY"), "## Trajectory\nmerged at abc1234");
|
|
22
|
+
assert.equal(renderStatus(back), body, "round trip");
|
|
23
|
+
});
|
|
24
|
+
it("a section is replaced by the newest write; DECISION keeps its last 5 entries and skips an identical repeat", () => {
|
|
25
|
+
let s = putSection(new Map(), ["FORGE:STARTED"], "run 1");
|
|
26
|
+
s = putSection(s, ["FORGE:STARTED"], "run 2");
|
|
27
|
+
assert.equal(s.get("FORGE:STARTED").text, "run 2");
|
|
28
|
+
for (let i = 1; i <= 7; i++) s = putSection(s, ["FORGE:DECISION"], `decision ${i}`);
|
|
29
|
+
s = putSection(s, ["FORGE:DECISION"], "decision 7");
|
|
30
|
+
const entries = s.get("FORGE:DECISION").text.split("\n\n---\n\n");
|
|
31
|
+
assert.deepEqual(entries, ["decision 3", "decision 4", "decision 5", "decision 6", "decision 7"]);
|
|
32
|
+
});
|
|
33
|
+
it("readers that search a body for a marker still match; anchored readers go through hasSection", () => {
|
|
34
|
+
const body = renderStatus(putSection(new Map(), ["FORGE:TRAJECTORY", "FORGE:WORK-ON"], "merged at abc1234"));
|
|
35
|
+
assert.ok(body.includes("FORGE:TRAJECTORY") && /merged at ([0-9a-f]{7,40})\b/.test(body), "probe / prefilter read the sha");
|
|
36
|
+
assert.ok(/FORGE:DECISION/.test(renderStatus(putSection(new Map(), ["FORGE:DECISION"], "x"))), "batch-health resolved read");
|
|
37
|
+
assert.ok(hasSection(body, "FORGE:TRAJECTORY") && hasSection(body, "FORGE:WORK-ON"));
|
|
38
|
+
assert.ok(!hasSection(body, "FORGE:STARTED"));
|
|
39
|
+
assert.ok(hasSection("<!-- FORGE:TRAJECTORY -->\nlegacy", "FORGE:TRAJECTORY"), "a legacy standalone comment still matches");
|
|
40
|
+
assert.ok(!hasSection("prose quoting <!-- FORGE:TRAJECTORY -->", "FORGE:TRAJECTORY"));
|
|
41
|
+
assert.ok(!hasSection("<!-- FORGE:TRAJECTORY_X -->", "FORGE:TRAJECTORY"));
|
|
42
|
+
});
|
|
43
|
+
it("classifies posts", () => {
|
|
44
|
+
assert.ok(isStatusPost("FORGE:STARTED") && isStatusPost(["FORGE:TRAJECTORY", "FORGE:WORK-ON"]) && isStatusPost("FORGE:DECISION"));
|
|
45
|
+
for (const m of ["FORGE:NEEDS_HUMAN", "FORGE:CONTRACT", "FORGE:REVIEW", "FORGE:ASK", "FORGE:DECISION {\"id\":1}", "FORGE:DECISION (escalated)", "FORGE:FACTS", "FORGE:TRACKED"]) assert.ok(!isStatusPost(m) && !isUpsertPost(m), m);
|
|
46
|
+
assert.ok(isUpsertPost(["FORGE:INVESTIGATION", "FORGE:VALIDATE"]) && isUpsertPost("FORGE:IMPLEMENTATION") && isUpsertPost("FORGE:PARKED"));
|
|
47
|
+
});
|
|
48
|
+
it("commentId reads gh-view urls and REST ids", () => {
|
|
49
|
+
assert.equal(commentId({ url: url(42) }), "42");
|
|
50
|
+
assert.equal(commentId({ id: 77 }), "77");
|
|
51
|
+
assert.equal(commentId({ id: "IC_node" }), null);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe("#5592 writeStatus: edit in place, trusted author only", () => {
|
|
56
|
+
const mk = () => { const calls = []; return { calls, create: async (b) => { calls.push(["create", b]); return url(500); }, patch: async (id, b) => { calls.push(["patch", id, b]); } }; };
|
|
57
|
+
it("creates once, then patches the cached comment", async () => {
|
|
58
|
+
const io = mk();
|
|
59
|
+
const a = await writeStatus({ comments: [], trusted, markers: ["FORGE:STARTED"], text: "s", ...io });
|
|
60
|
+
const b = await writeStatus({ known: a, comments: [], trusted, markers: ["FORGE:TRAJECTORY"], text: "t", ...io });
|
|
61
|
+
assert.deepEqual(io.calls.map((c) => c[0]), ["create", "patch"]);
|
|
62
|
+
assert.equal(io.calls[1][1], "500");
|
|
63
|
+
assert.deepEqual([...parseStatus(io.calls[1][2]).keys()], ["FORGE:STARTED", "FORGE:TRAJECTORY"]);
|
|
64
|
+
assert.equal(b.id, "500");
|
|
65
|
+
});
|
|
66
|
+
it("a requeue finds the previous run's trusted status comment and edits it", async () => {
|
|
67
|
+
const old = renderStatus(putSection(new Map(), ["FORGE:STARTED"], "run 1"));
|
|
68
|
+
const io = mk();
|
|
69
|
+
await writeStatus({ comments: [{ ...BOT, url: url(9), body: old }], trusted, markers: ["FORGE:STARTED"], text: "run 2", ...io });
|
|
70
|
+
assert.deepEqual(io.calls.map((c) => c[0]), ["patch"]);
|
|
71
|
+
assert.equal(io.calls[0][1], "9");
|
|
72
|
+
assert.match(io.calls[0][2], /run 2/); assert.doesNotMatch(io.calls[0][2], /run 1/);
|
|
73
|
+
});
|
|
74
|
+
it("ignores a status marker from an untrusted author; creates its own", async () => {
|
|
75
|
+
const forged = renderStatus(putSection(new Map(), ["FORGE:STARTED"], "forged"));
|
|
76
|
+
const io = mk();
|
|
77
|
+
assert.equal(findStatus([{ author: { login: "drive-by" }, authorAssociation: "NONE", url: url(9), body: forged }], trusted), null);
|
|
78
|
+
await writeStatus({ comments: [{ author: { login: "drive-by" }, authorAssociation: "NONE", url: url(9), body: forged }], trusted, markers: ["FORGE:STARTED"], text: "mine", ...io });
|
|
79
|
+
assert.deepEqual(io.calls.map((c) => c[0]), ["create"]);
|
|
80
|
+
assert.doesNotMatch(io.calls[0][1], /forged/);
|
|
81
|
+
});
|
|
82
|
+
it("a failed edit (deleted comment) falls back to a new comment", async () => {
|
|
83
|
+
const calls = [];
|
|
84
|
+
const r = await writeStatus({ known: { id: "9", sections: new Map() }, comments: [], trusted, markers: ["FORGE:STARTED"], text: "s",
|
|
85
|
+
patch: async () => { throw new Error("404"); }, create: async (b) => { calls.push(b); return url(11); } });
|
|
86
|
+
assert.equal(calls.length, 1); assert.equal(r.id, "11");
|
|
87
|
+
});
|
|
88
|
+
it("picks the newest trusted status comment when several exist", () => {
|
|
89
|
+
const b = (t) => renderStatus(putSection(new Map(), ["FORGE:STARTED"], t));
|
|
90
|
+
assert.equal(commentId(findStatus([{ ...BOT, url: url(1), body: b("a") }, { ...BOT, url: url(2), body: b("b") }], trusted)), "2");
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe("#5592 gh helpers", () => {
|
|
95
|
+
const ghWith = (comments, log) => async (a) => {
|
|
96
|
+
log.push(a);
|
|
97
|
+
if (a[0] === "issue" && a[1] === "view") return JSON.stringify({ comments, labels: [{ name: "bug" }, { name: "parked:ci.red" }, { name: "needs-human" }] });
|
|
98
|
+
if (a[0] === "issue" && a[1] === "comment") return "https://github.com/o/r/issues/7#issuecomment-600\n";
|
|
99
|
+
return "";
|
|
100
|
+
};
|
|
101
|
+
it("postStatusSection patches the bot's status comment (the batch runner's decide path)", async () => {
|
|
102
|
+
const log = [];
|
|
103
|
+
const old = renderStatus(putSection(new Map(), ["FORGE:DECISION"], "## Decision 1"));
|
|
104
|
+
await postStatusSection({ gh: ghWith([{ ...BOT, url: url(9), body: old }], log), repo: "o/r", issue: 7, markers: ["FORGE:DECISION"], text: "## Decision 2", trusted });
|
|
105
|
+
const patch = log.find((a) => a[0] === "api");
|
|
106
|
+
assert.ok(patch && patch.includes("repos/o/r/issues/comments/9"));
|
|
107
|
+
assert.ok(!log.some((a) => a[1] === "comment"));
|
|
108
|
+
assert.match(patch.at(-1), /Decision 1[\s\S]*Decision 2/);
|
|
109
|
+
});
|
|
110
|
+
it("postUpsert edits the newest trusted comment that leads with the marker, keeps the marker first, else posts", async () => {
|
|
111
|
+
const log = [];
|
|
112
|
+
await postUpsert({ gh: ghWith([{ ...BOT, url: url(5), body: "<!-- FORGE:PARKED code=ci.red -->\nold" }, { ...BOT, url: url(6), body: "hello" }], log), repo: "o/r", issue: 7, markers: ["FORGE:PARKED"], attrs: "code=base.conflict pr=3", body: "## Parked", trusted });
|
|
113
|
+
const patch = log.find((a) => a[0] === "api");
|
|
114
|
+
assert.ok(patch.includes("repos/o/r/issues/comments/5"));
|
|
115
|
+
assert.ok(patch.at(-1).startsWith("body=<!-- FORGE:PARKED code=base.conflict pr=3 -->\n## Parked"));
|
|
116
|
+
const log2 = [];
|
|
117
|
+
await postUpsert({ gh: ghWith([], log2), repo: "o/r", issue: 7, markers: ["FORGE:PARKED"], body: "## Parked", trusted });
|
|
118
|
+
assert.ok(log2.some((a) => a[1] === "comment") && !log2.some((a) => a[0] === "api"));
|
|
119
|
+
assert.equal(findLeading([{ author: { login: "x" }, url: url(1), body: "<!-- FORGE:PARKED -->" }], "FORGE:PARKED", trusted), null);
|
|
120
|
+
});
|
|
121
|
+
it("clearPipelineLabels removes exactly the pipeline labels", async () => {
|
|
122
|
+
assert.ok(["needs-human", "needs-human:external", "parked:ci.red", "remediation-queue"].every(isPipelineLabel));
|
|
123
|
+
assert.ok(!["bug", "workflow:building", "needs-validation", "parked", "needs-humans"].some(isPipelineLabel));
|
|
124
|
+
assert.deepEqual(pipelineLabels([{ name: "bug" }, "needs-human", { name: "parked:x" }]), ["needs-human", "parked:x"]);
|
|
125
|
+
const log = [];
|
|
126
|
+
assert.deepEqual(await clearPipelineLabels({ gh: ghWith([], log), repo: "o/r", issue: 7 }), ["parked:ci.red", "needs-human"]);
|
|
127
|
+
assert.deepEqual(log.at(-1), ["issue", "edit", "7", "-R", "o/r", "--remove-label", "parked:ci.red,needs-human"]);
|
|
128
|
+
const log2 = [];
|
|
129
|
+
assert.deepEqual(await clearPipelineLabels({ gh: ghWith([], log2), repo: "o/r", issue: 7, labels: [{ name: "bug" }] }), []);
|
|
130
|
+
assert.equal(log2.length, 0, "nothing to remove: no gh call");
|
|
131
|
+
assert.deepEqual(await clearPipelineLabels({ gh: async () => { throw new Error("boom"); }, repo: "o/r", issue: 7, labels: ["needs-human"] }), [], "best effort");
|
|
132
|
+
});
|
|
133
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* UI quality rules (#5330): every user-visible frontend change fits the platform's design system, and a new surface is
|
|
5
|
+
* intuitive and polished. Deterministic: detection is by path and issue text, the rules are prompt text appended only to
|
|
6
|
+
* UI lanes (base prompts stay inside their token caps), and the visual reviewer is the frontend domain check, not a new
|
|
7
|
+
* agent call. A browser is never installed: the rendered self-check records why it could not run.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const UI_FILE_RE = /\.(?:tsx|jsx|vue|svelte|css|scss|sass|less)$|(?:^|\/)(?:web|app|components|pages|styles)\//i;
|
|
11
|
+
const TEST_FILE_RE = /\.(?:test|spec|stories)\.|(?:^|\/)(?:__tests__|e2e)\//i;
|
|
12
|
+
const UI_TEXT_RE = /\b(?:frontend|front-end|ui|ux|page|component|modal|dialog|button|layout|screen|dashboard|landing|css|tailwind|responsive|mobile view)\b|\.(?:tsx|jsx|vue|svelte)\b/i;
|
|
13
|
+
export const VISUAL_HEADING = "### Visual Check";
|
|
14
|
+
|
|
15
|
+
/** Changed or contracted non-test files that are user-visible UI (components, pages, styles). */
|
|
16
|
+
export const uiChanged = (files = []) => (Array.isArray(files) ? files : []).map(String).filter((f) => UI_FILE_RE.test(f) && !TEST_FILE_RE.test(f));
|
|
17
|
+
|
|
18
|
+
/** Whether the issue text or labels describe a user-visible frontend change (plan-time, before any file is known). */
|
|
19
|
+
export const uiIssue = ({ title = "", body = "", labels = [] } = {}) =>
|
|
20
|
+
(labels ?? []).some((l) => /^(?:frontend|design|ui)$/i.test(String(l?.name ?? l))) || UI_TEXT_RE.test(`${title}\n${String(body).slice(0, 4000)}`);
|
|
21
|
+
|
|
22
|
+
/** design.system (forge.yaml): a path or list of paths naming the design system docs/tokens; [] when unset. */
|
|
23
|
+
export const designPaths = (cfg) => {
|
|
24
|
+
const v = cfg?.system ?? cfg;
|
|
25
|
+
return (Array.isArray(v) ? v : typeof v === "string" ? v.replace(/^\s*\[|\]\s*$/g, "").split(",") : []).map((x) => String(x).trim().replace(/^(["'])(.*)\1$/, "$2")).filter(Boolean);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** The build rule: read the design system first, reuse it, and give every new surface its states. */
|
|
29
|
+
export function designSystemRule(cfg) {
|
|
30
|
+
const paths = designPaths(cfg);
|
|
31
|
+
const where = paths.length ? `Read the design system first: ${paths.join(", ")}.` : "Read the design system first: the paths in forge.yaml design.system, else the repo's design or token docs and the neighbouring components.";
|
|
32
|
+
return `${where} Reuse existing components, tokens, spacing and type so the change fits the surrounding product; no off-system colours, fonts or spacing. A new surface must be intuitive: clear hierarchy, an obvious primary action, useful empty, loading and error states, and no placeholder boxes.`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The self-check and gate rule; text for the builder only. */
|
|
36
|
+
export function uiSelfCheckRule() {
|
|
37
|
+
return `Self-check before you commit: render the changed routes at desktop and mobile widths, compare them with neighbouring pages and fix alignment, spacing, truncation, contrast and state handling. Only use a browser that already exists; never install one. A new or rewritten page or route needs a design spec (route to /design) referenced in the contract. Record the result in implementation.md under "${VISUAL_HEADING}": the screenshot paths (before and after for an existing page), a verdict (consistent|inconsistent) and the fixes made, or "not rendered: <reason>" when no browser is available.`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The conditional block appended to the plan and implement prompts of a UI lane; "" otherwise. */
|
|
41
|
+
export function uiBuildRule(on, cfg = null) {
|
|
42
|
+
return on ? `\n\nUI change (user-visible frontend): ${designSystemRule(cfg)}\n${uiSelfCheckRule()}` : "";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The visual reviewer check, appended to DOMAIN_CHECKS.frontend (blocks as a regressions row). */
|
|
46
|
+
export const visualReviewCheck = () => "Visual/UX: open the screenshots listed in the PR's Visual check section (or render the route) and judge the change for intuitiveness, consistency with neighbouring pages and the design system, and polish; off-system colours, fonts or spacing, missing empty/loading/error states, placeholder boxes, and a UI change with no recorded visual check or screenshots (a new page also needs a /design spec) are findings.";
|
|
47
|
+
|
|
48
|
+
/** The PR body's "Visual check" section from implementation.md's "### Visual Check"; "" when absent or empty. */
|
|
49
|
+
export function visualSection(implementation) {
|
|
50
|
+
const md = String(implementation ?? "");
|
|
51
|
+
const i = md.indexOf(VISUAL_HEADING);
|
|
52
|
+
if (i < 0) return "";
|
|
53
|
+
const rest = md.slice(i + VISUAL_HEADING.length);
|
|
54
|
+
const m = /\n#{1,3} /.exec(rest);
|
|
55
|
+
const body = (m ? rest.slice(0, m.index) : rest).trim();
|
|
56
|
+
return body ? `\n\n## Visual check\n${body}` : "";
|
|
57
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { uiChanged, uiIssue, designPaths, designSystemRule, uiSelfCheckRule, uiBuildRule, visualReviewCheck, visualSection } from "./ui-quality.mjs";
|
|
6
|
+
import { DOMAIN_CHECKS, domainChecksBlock } from "./prompts.mjs";
|
|
7
|
+
import { renderPrBody } from "./render.mjs";
|
|
8
|
+
|
|
9
|
+
describe("UI lane quality (#5330)", () => {
|
|
10
|
+
it("detects user-visible UI files, not tests", () => {
|
|
11
|
+
assert.deepEqual(uiChanged(["web/app/page.tsx", "web/app/page.test.tsx", "src/a.mjs", "styles/x.css"]), ["web/app/page.tsx", "styles/x.css"]);
|
|
12
|
+
assert.deepEqual(uiChanged(undefined), []);
|
|
13
|
+
});
|
|
14
|
+
it("detects a UI issue from text or labels", () => {
|
|
15
|
+
assert.ok(uiIssue({ title: "Fix the settings page layout" }));
|
|
16
|
+
assert.ok(uiIssue({ title: "x", labels: [{ name: "frontend" }] }));
|
|
17
|
+
assert.ok(!uiIssue({ title: "Fix retry backoff", body: "scheduler bug" }));
|
|
18
|
+
});
|
|
19
|
+
it("names design.system paths, or falls back to forge.yaml", () => {
|
|
20
|
+
assert.deepEqual(designPaths({ system: "a.md, b.css" }), ["a.md", "b.css"]);
|
|
21
|
+
assert.match(designSystemRule({ system: ["docs/ds.md"] }), /docs\/ds\.md[\s\S]*empty, loading and error states[\s\S]*no placeholder boxes/);
|
|
22
|
+
assert.match(designSystemRule(null), /forge\.yaml design\.system/);
|
|
23
|
+
});
|
|
24
|
+
it("the self-check never installs a browser and records the visual check", () => {
|
|
25
|
+
const r = uiSelfCheckRule();
|
|
26
|
+
assert.match(r, /desktop and mobile/); assert.match(r, /never install one/); assert.match(r, /### Visual Check/); assert.match(r, /\/design/);
|
|
27
|
+
});
|
|
28
|
+
it("adds the build rule only to UI lanes", () => {
|
|
29
|
+
assert.equal(uiBuildRule(false), "");
|
|
30
|
+
assert.match(uiBuildRule(true), /UI change[\s\S]*Self-check/);
|
|
31
|
+
});
|
|
32
|
+
it("the frontend domain check carries the visual check and the ISR check", () => {
|
|
33
|
+
assert.ok(DOMAIN_CHECKS.frontend.startsWith(visualReviewCheck()));
|
|
34
|
+
assert.match(DOMAIN_CHECKS.frontend, /headers\(\), cookies\(\)/);
|
|
35
|
+
assert.match(domainChecksBlock(["frontend"]), /off-system colours, fonts or spacing/);
|
|
36
|
+
});
|
|
37
|
+
it("the PR body shows the Visual check section only when recorded", () => {
|
|
38
|
+
const impl = "### Approach\nx\n### Visual Check\n- shots: $TMPDIR/a.png\n- verdict: consistent\n### Notes\nn";
|
|
39
|
+
assert.equal(visualSection("### Approach\nx"), "");
|
|
40
|
+
assert.equal(visualSection("### Visual Check\n\n### Notes\n"), "");
|
|
41
|
+
const body = renderPrBody({ issue: 1, investigation: "", contract: { deliverables: [] }, implementation: impl, result: {}, gitFiles: [] });
|
|
42
|
+
assert.match(body, /## Visual check\n- shots: \$TMPDIR\/a\.png\n- verdict: consistent\n\nCloses #1/);
|
|
43
|
+
assert.ok(!renderPrBody({ issue: 1, investigation: "", contract: { deliverables: [] }, implementation: "### Approach\nx", result: {}, gitFiles: [] }).includes("Visual check"));
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe("design.system wiring (#5330)", () => {
|
|
48
|
+
it("forge.yaml design.system feeds the build rule", async () => {
|
|
49
|
+
const { parseForgeYaml } = await import("../forge-utils.mjs");
|
|
50
|
+
const cfg = parseForgeYaml("design:\n system: [docs/ds.md, web/tokens.css]\n").design;
|
|
51
|
+
assert.deepEqual(designPaths(cfg), ["docs/ds.md", "web/tokens.css"]);
|
|
52
|
+
assert.match(uiBuildRule(true, cfg), /docs\/ds\.md, web\/tokens\.css/);
|
|
53
|
+
assert.equal(uiBuildRule(false, cfg), "");
|
|
54
|
+
});
|
|
55
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// scripts/visual-gate.mjs (#5369): the review-pr-staging visual gate, run as the command spec runs it.
|
|
4
|
+
import { describe, it, before } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { spawnSync } from "node:child_process";
|
|
7
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
|
+
import { join, dirname } from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
|
|
12
|
+
const SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "../../scripts/visual-gate.mjs");
|
|
13
|
+
const CONF = "design:\n gate: blocking\n routes: [\"web/app/**/page.tsx\"]\n viewports: [390, 1440]\n require_visual_check: true\n";
|
|
14
|
+
const BAD = '<main><h1>Hands</h1><p>Delegate.</p><div className="rounded border p-4"></div><div className="rounded border p-4"></div><a href="/s">Get access</a></main>';
|
|
15
|
+
const GOOD = '<main><Hero title="Hands"/><Card title="Needs" body="A task."/><Button>Get access</Button></main>';
|
|
16
|
+
const run = (args, input) => { const r = spawnSync(process.execPath, [SCRIPT, ...args], { encoding: "utf8", input }); return { rc: r.status, out: r.stdout, err: r.stderr }; };
|
|
17
|
+
let root;
|
|
18
|
+
const put = (rel, text) => { const p = join(root, rel); mkdirSync(dirname(p), { recursive: true }); writeFileSync(p, text); return p; };
|
|
19
|
+
|
|
20
|
+
before(() => {
|
|
21
|
+
root = tmpDir("vgate-");
|
|
22
|
+
put("forge.yaml", CONF); put("web/app/hands/page.tsx", BAD); put("web/app/pricing/page.tsx", GOOD);
|
|
23
|
+
put("ev-ok.json", JSON.stringify({ "/pricing": { screenshots: ["p-390.png", "p-1440.png"], verdict: "PASS" } }));
|
|
24
|
+
put("ev-bad.json", JSON.stringify({ "/hands": { screenshots: ["h-390.png", "h-1440.png"], verdict: "PASS" } }));
|
|
25
|
+
put("off.yaml", "design:\n system: [docs/ds.md]\n");
|
|
26
|
+
});
|
|
27
|
+
const base = () => ["--root", root, "--files-file", "-"];
|
|
28
|
+
|
|
29
|
+
describe("scripts/visual-gate.mjs (#5369)", () => {
|
|
30
|
+
it("--list names every changed user-visible route with the viewports to render", () => {
|
|
31
|
+
const r = run([...base(), "--list"], "web/app/hands/page.tsx\nweb/app/pricing/page.tsx\nservices/api/x.py\n");
|
|
32
|
+
const j = JSON.parse(r.out);
|
|
33
|
+
assert.equal(r.rc, 0); assert.deepEqual(j.routes.map((x) => x.route), ["/hands", "/pricing"]); assert.deepEqual(j.viewports, [390, 1440]);
|
|
34
|
+
});
|
|
35
|
+
it("regression fixture: the bundle adding the plain-text hero page with empty boxes fails (exit 1, GATE_FAILURE)", () => {
|
|
36
|
+
const r = run([...base(), "--spec", "yes", "--evidence", join(root, "ev-bad.json")], "web/app/hands/page.tsx\n");
|
|
37
|
+
const j = JSON.parse(r.out);
|
|
38
|
+
assert.equal(r.rc, 1); assert.equal(j.verdict, "FAIL");
|
|
39
|
+
assert.ok(j.rows.some((x) => /empty_box/.test(x.detail)) && j.rows.some((x) => /plain_text_hero/.test(x.detail)));
|
|
40
|
+
});
|
|
41
|
+
it("a missing spec fails with design.gate: blocking", () => {
|
|
42
|
+
const r = run([...base(), "--evidence", join(root, "ev-ok.json")], "web/app/pricing/page.tsx\n");
|
|
43
|
+
assert.equal(r.rc, 1); assert.equal(JSON.parse(r.out).rows[0].kind, "design_spec_missing");
|
|
44
|
+
});
|
|
45
|
+
it("a good page with spec, both screenshots and a PASS verdict passes; --comment prints the FORGE:VISUAL_GATE marker", () => {
|
|
46
|
+
const a = [...base(), "--spec", "yes", "--evidence", join(root, "ev-ok.json")];
|
|
47
|
+
assert.equal(run(a, "web/app/pricing/page.tsx\n").rc, 0);
|
|
48
|
+
const c = run([...a, "--comment"], "web/app/pricing/page.tsx\n");
|
|
49
|
+
assert.match(c.out, /<!-- FORGE:VISUAL_GATE -->/); assert.match(c.out, /Visual gate: PASS/); assert.match(c.out, /p-390\.png/);
|
|
50
|
+
});
|
|
51
|
+
it("no evidence for a route fails when require_visual_check is on", () => {
|
|
52
|
+
const r = run([...base(), "--spec", "yes"], "web/app/pricing/page.tsx\n");
|
|
53
|
+
assert.equal(r.rc, 1); assert.deepEqual(JSON.parse(r.out).rows.map((x) => x.kind), ["visual_screenshots_missing", "visual_critique_missing"]);
|
|
54
|
+
});
|
|
55
|
+
it("opt-in: without design.routes the gate is SKIP and exits 0", () => {
|
|
56
|
+
const r = run(["--root", root, "--config", join(root, "off.yaml"), "--files-file", "-"], "web/app/hands/page.tsx\n");
|
|
57
|
+
assert.equal(r.rc, 0); assert.equal(JSON.parse(r.out).verdict, "SKIP");
|
|
58
|
+
});
|
|
59
|
+
it("usage errors exit 2 (unknown flag, no file source)", () => {
|
|
60
|
+
assert.equal(run(["--root", root, "--bogus"]).rc, 2);
|
|
61
|
+
assert.equal(run(["--root", root]).rc, 2);
|
|
62
|
+
});
|
|
63
|
+
});
|
package/bin/pool/agent.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { createServer } from "node:http";
|
|
|
4
4
|
import { randomBytes } from "node:crypto";
|
|
5
5
|
import { execFile, spawn } from "node:child_process";
|
|
6
6
|
import { promisify } from "node:util";
|
|
7
|
-
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, statfsSync, lstatSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { basename, join } from "node:path";
|
|
9
9
|
import { cpus, hostname } from "node:os";
|
|
10
10
|
import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
|
|
@@ -91,9 +91,23 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
91
91
|
} finally { rmSync(file, { force: true }); }
|
|
92
92
|
}
|
|
93
93
|
const used = () => Object.values(sb()).filter((s) => s.state !== "exited").reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
|
|
94
|
+
// #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
|
|
95
|
+
let diskCache = { at: 0, mb: {} };
|
|
96
|
+
const dirMb = (d) => { let n = 0, seen = 0; const walk = (x) => { if (seen++ > 200000) return; let st; try { st = lstatSync(x); } catch { return; } n += st.size; if (st.isDirectory()) { try { for (const e of readdirSync(x)) walk(join(x, e)); } catch { /* unreadable */ } } }; walk(d); return Math.round(n / 1048576); };
|
|
97
|
+
function diskView() {
|
|
98
|
+
const out = {};
|
|
99
|
+
try { const f = statfsSync(stateDir); out.disk_free_gb = Math.round((Number(f.bavail) * Number(f.bsize)) / 107374182.4) / 10; } catch { /* unknown */ }
|
|
100
|
+
if (Date.now() - diskCache.at > 60000) {
|
|
101
|
+
const mb = {};
|
|
102
|
+
for (const r of Object.values(sb())) if (r.state !== "exited") mb[r.id] = dirMb(join(stateDir, "sandboxes", safeName(r.id)));
|
|
103
|
+
diskCache = { at: Date.now(), mb };
|
|
104
|
+
}
|
|
105
|
+
out.sandbox_disk_mb = diskCache.mb;
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
94
108
|
function capacity() {
|
|
95
109
|
const u = used();
|
|
96
|
-
return { host: cfg.name ?? hostname(), ...running, vm: vmSize(), ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), cpus_total: cfg.allow_cpus, mem_total_gb: cfg.allow_mem_gb, cpus_free: cfg.allow_cpus - u.cpus, mem_free_gb: cfg.allow_mem_gb - u.mem, active: Object.values(sb()).filter((s) => s.state !== "exited").length, paused: Boolean(cfg.paused), live: live(cfg), usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
110
|
+
return { host: cfg.name ?? hostname(), ...running, vm: vmSize(), ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), cpus_total: cfg.allow_cpus, mem_total_gb: cfg.allow_mem_gb, cpus_free: cfg.allow_cpus - u.cpus, mem_free_gb: cfg.allow_mem_gb - u.mem, active: Object.values(sb()).filter((s) => s.state !== "exited").length, ...diskView(), paused: Boolean(cfg.paused), live: live(cfg), usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
97
111
|
}
|
|
98
112
|
|
|
99
113
|
async function launch({ spec, cpus, mem_gb, limit = null }) {
|
package/bin/pool/router.mjs
CHANGED
|
@@ -314,7 +314,11 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
314
314
|
[route("POST", "/sandboxes/:id/stop"), fd(async ({ id }) => forward(id, "POST", `/sandboxes/${encodeURIComponent(id)}/stop`))], // #5274
|
|
315
315
|
[route("DELETE", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "DELETE", `/sandboxes/${encodeURIComponent(id)}`, DESTROY_TIMEOUT_MS))],
|
|
316
316
|
[route("GET", "/status"), fd(async () => ({ status: 200, body: await status() }))],
|
|
317
|
-
[route("GET", "/agents"), fd(async () =>
|
|
317
|
+
[route("GET", "/agents"), fd(async () => { // #5535: each sandbox carries disk_used_mb from its agent's sandbox_disk_mb when the agent reports it
|
|
318
|
+
const caps = await capacities(), byName = new Map(caps.map((c) => [c.name, c])), out = {};
|
|
319
|
+
for (const [id, s] of Object.entries(sbx())) { const mb = byName.get(s?.agent)?.sandbox_disk_mb?.[id]; out[id] = Number.isFinite(mb) ? { ...s, disk_used_mb: mb } : s; }
|
|
320
|
+
return { status: 200, body: { agents: caps, sandboxes: out } };
|
|
321
|
+
})],
|
|
318
322
|
[route("POST", "/codes"), fd(async () => ({ status: 200, body: issueCode() }))],
|
|
319
323
|
[route("GET", "/agent/creds/github"), { fn: async () => ({ status: 200, body: { token: await githubToken() } }), auth: "agent" }],
|
|
320
324
|
[route("GET", "/agent/creds/claude"), { fn: async (_p, _b, _u, req) => claudeToken(req), auth: "agent" }],
|
package/bin/review-staging.mjs
CHANGED
|
@@ -633,14 +633,16 @@ async function summary(a, io) {
|
|
|
633
633
|
let ciFailing = 1;
|
|
634
634
|
const ci = await io.run("gh", ["pr", "checks", String(pr), "-R", c.ghRepo, "--json", "name,bucket,link"], { env, cwd: io.cwd });
|
|
635
635
|
let checks = ci.code === 0 ? parseChecks(ci.stdout) : null;
|
|
636
|
-
let warnings = [], ciCancelOnly = false;
|
|
636
|
+
let warnings = [], ciCancelOnly = false, ciPendingOnly = false;
|
|
637
637
|
if (checks) {
|
|
638
638
|
const read = await requiredChecksRead({ gh: io.gh, repo: c.ghRepo, lane: c.defaultBranch });
|
|
639
639
|
const required = requiredSet(read, c.extraRequiredChecks);
|
|
640
640
|
const only = cancelOnlyChecks(checks, required);
|
|
641
641
|
if (only.length) checks = await rerunCancelled(io, c, pr, env, checks, only);
|
|
642
642
|
({ blocking: ciFailing, warnings } = classifyChecks(checks, required));
|
|
643
|
-
|
|
643
|
+
const rows = redChecks(checks, required).blockRows;
|
|
644
|
+
ciCancelOnly = ciFailing > 0 && rows.every((k) => k.bucket === "cancel");
|
|
645
|
+
ciPendingOnly = ciFailing > 0 && rows.every((k) => k.bucket === "pending");
|
|
644
646
|
}
|
|
645
647
|
|
|
646
648
|
const acceptanceBlocked = await acceptanceBlock(io, c, pr, tg);
|
|
@@ -697,7 +699,7 @@ async function summary(a, io) {
|
|
|
697
699
|
} catch (e) {
|
|
698
700
|
throw new Stop(1, [`REVIEW_RESULT: status: BLOCKED, blocker: could not post the Phase 8 summary and gate marker (${e.message})`, BLOCK_DEPLOY]);
|
|
699
701
|
}
|
|
700
|
-
if (a.json) io.out(JSON.stringify({ pr, headSha: head, verdict: v.verdict, why: v.why, marker, ciFailing, ciCancelOnly, warnings, testGate: tg.verdict, filed: a.filed }));
|
|
702
|
+
if (a.json) io.out(JSON.stringify({ pr, headSha: head, verdict: v.verdict, why: v.why, marker, ciFailing, ciCancelOnly, ciPendingOnly, warnings, testGate: tg.verdict, filed: a.filed }));
|
|
701
703
|
else io.out([`VERDICT: ${v.verdict} (${v.why})`, ...(warnings.length ? [`WARNING: ${warnings.length} non-required check(s) red, non-blocking: ${warnings.join(", ")}`] : []), `GATE: ${marker} posted on PR #${pr}`, ...(pass ? [] : [BLOCK_DEPLOY])].join("\n"));
|
|
702
704
|
return pass ? 0 : 1;
|
|
703
705
|
}
|
|
@@ -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
|
+
});
|