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.
Files changed (140) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +2 -1
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +48 -12
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +4 -2
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +118 -20
  14. package/bin/lean/conformance.test.mjs +172 -3
  15. package/bin/lean/decisions.mjs +98 -1
  16. package/bin/lean/decisions.test.mjs +30 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +16 -3
  32. package/bin/lean/issuewatch-parity.test.mjs +32 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +110 -24
  39. package/bin/lean/lean.test.mjs +183 -4
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +3 -2
  44. package/bin/lean/orphan-pr.test.mjs +8 -1
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +28 -3
  52. package/bin/lean/release-config.mjs +169 -0
  53. package/bin/lean/release-config.test.mjs +132 -0
  54. package/bin/lean/release-control.mjs +171 -0
  55. package/bin/lean/release-control.test.mjs +167 -0
  56. package/bin/lean/release-deploy.mjs +209 -0
  57. package/bin/lean/release-deploy.test.mjs +217 -0
  58. package/bin/lean/release-fence.mjs +50 -0
  59. package/bin/lean/release-fence.test.mjs +105 -0
  60. package/bin/lean/release-flakes.mjs +139 -0
  61. package/bin/lean/release-flakes.test.mjs +116 -0
  62. package/bin/lean/release-gates.mjs +230 -0
  63. package/bin/lean/release-gates.test.mjs +146 -0
  64. package/bin/lean/release-ledger.mjs +176 -0
  65. package/bin/lean/release-ledger.test.mjs +226 -0
  66. package/bin/lean/release-minutes.mjs +102 -0
  67. package/bin/lean/release-minutes.test.mjs +107 -0
  68. package/bin/lean/release-nightly.mjs +75 -0
  69. package/bin/lean/release-nightly.test.mjs +48 -0
  70. package/bin/lean/release-postmerge.mjs +8 -2
  71. package/bin/lean/release-review.e2e.test.mjs +1 -0
  72. package/bin/lean/release-review.mjs +54 -7
  73. package/bin/lean/release-review.test.mjs +76 -7
  74. package/bin/lean/release-status.mjs +300 -0
  75. package/bin/lean/release-status.test.mjs +220 -0
  76. package/bin/lean/release-unitmap.mjs +35 -0
  77. package/bin/lean/release-unitmap.test.mjs +41 -0
  78. package/bin/lean/release-verify.mjs +221 -0
  79. package/bin/lean/release-verify.test.mjs +176 -0
  80. package/bin/lean/release.mjs +244 -22
  81. package/bin/lean/release.test.mjs +44 -0
  82. package/bin/lean/render.mjs +3 -1
  83. package/bin/lean/run-issue-placement.test.mjs +82 -0
  84. package/bin/lean/sandbox-remote.mjs +16 -0
  85. package/bin/lean/schedd.mjs +1 -1
  86. package/bin/lean/seam.mjs +115 -0
  87. package/bin/lean/seam.test.mjs +118 -0
  88. package/bin/lean/selftest-journey.mjs +40 -2
  89. package/bin/lean/selftest-journey.test.mjs +43 -3
  90. package/bin/lean/statuscomment.mjs +168 -0
  91. package/bin/lean/statuscomment.test.mjs +133 -0
  92. package/bin/lean/ui-quality.mjs +57 -0
  93. package/bin/lean/ui-quality.test.mjs +55 -0
  94. package/bin/lean/visual-gate.test.mjs +63 -0
  95. package/bin/pool/agent.mjs +16 -2
  96. package/bin/pool/router.mjs +5 -1
  97. package/bin/review-staging.mjs +5 -3
  98. package/bin/stats/card.mjs +117 -0
  99. package/bin/stats/card.test.mjs +109 -0
  100. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  101. package/bin/stats/depth.mjs +1 -1
  102. package/bin/stats/gh-retry.test.mjs +152 -0
  103. package/bin/stats/github-source.mjs +147 -14
  104. package/bin/stats/index.mjs +35 -2
  105. package/bin/stats/stats.test.mjs +31 -3
  106. package/bin/vendor/js-yaml/LICENSE +21 -0
  107. package/bin/vendor/js-yaml/PIN.md +7 -0
  108. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  109. package/commands/design-render-critique-loop.md +2 -0
  110. package/commands/design.md +2 -0
  111. package/commands/issue.md +1 -1
  112. package/commands/milestone.md +1 -1
  113. package/commands/review-pr-agents/frontend.md +1 -0
  114. package/commands/review-pr-staging.md +5 -0
  115. package/docs/CONFIG.md +95 -2
  116. package/docs/ISSUE-WATCH.md +7 -0
  117. package/docs/OUTCOME-CODES.md +1 -0
  118. package/docs/STATS.md +10 -0
  119. package/docs/design/visual-gate.md +25 -0
  120. package/docs/eval/adversarial-bench.md +2 -2
  121. package/docs/eval/corpus/adversarial-v1.json +3 -3
  122. package/docs/site/start-a-new-project.md +7 -0
  123. package/docs/spec/forge-protocol-v1.md +31 -0
  124. package/package.json +1 -1
  125. package/pool/README.md +2 -0
  126. package/scripts/acceptance-red-green.sh +15 -1
  127. package/scripts/acceptance-red-green.test.sh +12 -0
  128. package/scripts/bench-adversarial.mjs +4 -0
  129. package/scripts/bench-lightlane.mjs +4 -1
  130. package/scripts/bootstrap-create.mjs +8 -2
  131. package/scripts/ci-local/scoping.mjs +19 -0
  132. package/scripts/ci-local.test.sh +16 -3
  133. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  134. package/scripts/plan-validate-live.mjs +9 -6
  135. package/scripts/review-prepare.sh +7 -1
  136. package/scripts/review-roster.sh +5 -2
  137. package/scripts/review-roster.test.sh +9 -0
  138. package/scripts/visual-gate.mjs +64 -0
  139. package/templates/bootstrap/technical-spike.md +17 -0
  140. package/templates/contracts/seam-check.mjs +236 -0
@@ -0,0 +1,168 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5592 (8): one machine-state comment per issue, edited in place.
5
+ *
6
+ * Every run used to post STARTED, CONTEXT, LANE_BRANCH, TRAJECTORY and a recovery DECISION as separate comments, and every
7
+ * requeue posted them again (30-42 comments on one issue). They now live as sections of ONE trusted `<!-- FORGE:STATUS -->`
8
+ * comment the engine PATCHes: a section holds the newest run's text (DECISION keeps the last few entries). A section starts with
9
+ * its own `<!-- FORGE:NAME -->` marker line(s), so every reader that searches a body for a marker (includes / unanchored regex)
10
+ * keeps working; readers that anchor a marker at the comment start use `hasSection` (here) instead.
11
+ *
12
+ * Stays a separate comment, because a person must see it (a new comment notifies, an edit does not) or other code reads the
13
+ * comment order: NEEDS_HUMAN, HOST_TASK, DEPENDENCY, DECOMPOSED, owner asks, CONTRACT/PLAN, REVIEW, FACTS, TRACKED, JSON
14
+ * DECISION records. INVESTIGATION, IMPLEMENTATION and PARKED are single comments edited in place (`upsert`), their marker still
15
+ * leading the body.
16
+ */
17
+
18
+ export const STATUS_MARKER = "FORGE:STATUS";
19
+ export const STATUS_SEP = "<!-- FORGE:STATUS:SEP -->";
20
+ /** Markers folded into the status comment, keyed by the FIRST marker of a post. */
21
+ export const STATUS_SECTIONS = Object.freeze(["FORGE:STARTED", "FORGE:CONTEXT", "FORGE:LANE_BRANCH", "FORGE:LITE", "FORGE:TRAJECTORY", "FORGE:DECISION"]);
22
+ /** Sections that keep their last N entries instead of only the newest. */
23
+ export const APPEND_SECTIONS = Object.freeze({ "FORGE:DECISION": 5 });
24
+ export const ENTRY_SEP = "\n\n---\n\n";
25
+ /** Markers posted once and edited in place (the marker leads the comment body, so anchored readers still match). */
26
+ export const UPSERT_MARKERS = Object.freeze(["FORGE:INVESTIGATION", "FORGE:IMPLEMENTATION", "FORGE:PARKED"]);
27
+
28
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
29
+ const markLine = (m) => `<!-- ${m} -->`;
30
+
31
+ /** The REST comment id of a `gh issue view` comment (`url` ends in `#issuecomment-<id>`) or a REST comment (`id`). */
32
+ export function commentId(c) {
33
+ const m = /#issuecomment-(\d+)/.exec(String(c?.url ?? ""));
34
+ if (m) return m[1];
35
+ return /^\d+$/.test(String(c?.id ?? "")) ? String(c.id) : null;
36
+ }
37
+
38
+ /** True when `marker` is one of the comment's section markers or (legacy / upsert) leads the body. */
39
+ export function hasSection(body, marker) {
40
+ const b = String(body ?? "");
41
+ if (new RegExp(`^\\s*<!--\\s*${esc(marker)}(?![A-Za-z0-9_])`).test(b)) return true;
42
+ return isStatusBody(b) && new RegExp(`^<!--\\s*${esc(marker)}(?![A-Za-z0-9_])`, "m").test(b);
43
+ }
44
+ export const isStatusBody = (body) => new RegExp(`^\\s*<!--\\s*${esc(STATUS_MARKER)}\\s*-->`).test(String(body ?? ""));
45
+
46
+ /** The text of one section (without its marker lines), or null. */
47
+ export function sectionText(body, marker) {
48
+ return parseStatus(body).get(marker)?.text ?? null;
49
+ }
50
+
51
+ /** Status body -> Map(primary marker -> {markers: [..], text}). A non-status body parses to an empty map. */
52
+ export function parseStatus(body) {
53
+ const out = new Map();
54
+ if (!isStatusBody(body)) return out;
55
+ const chunks = String(body).split(STATUS_SEP).slice(1);
56
+ for (const chunk of chunks) {
57
+ const lines = chunk.replace(/^\s*\n/, "").split("\n");
58
+ const markers = [];
59
+ while (lines.length && /^<!--\s*FORGE:[A-Z_:-]+\s*-->\s*$/.test(lines[0])) markers.push(/FORGE:[A-Z_:-]+/.exec(lines.shift())[0]);
60
+ if (markers.length) out.set(markers[0], { markers, text: lines.join("\n").replace(/\s+$/, "") });
61
+ }
62
+ return out;
63
+ }
64
+
65
+ export function renderStatus(sections) {
66
+ const parts = [markLine(STATUS_MARKER)];
67
+ for (const { markers, text } of sections.values()) parts.push(`${STATUS_SEP}\n${markers.map(markLine).join("\n")}\n${text}`);
68
+ return parts.join("\n");
69
+ }
70
+
71
+ /** `sections` with `markers` (array, first = key) set to `text`: replaced, or appended to the last N entries for APPEND_SECTIONS. */
72
+ export function putSection(sections, markers, text) {
73
+ const next = new Map(sections);
74
+ const key = markers[0], cap = APPEND_SECTIONS[key];
75
+ let value = String(text ?? "").replace(/\s+$/, "");
76
+ if (cap) {
77
+ const old = sections.get(key)?.text;
78
+ const entries = old ? old.split(ENTRY_SEP) : [];
79
+ if (entries[entries.length - 1] !== value) entries.push(value);
80
+ value = entries.slice(-cap).join(ENTRY_SEP);
81
+ }
82
+ next.delete(key); // keeps a stable insertion order: the newest write goes last
83
+ next.set(key, { markers, text: value });
84
+ return next;
85
+ }
86
+
87
+ /** The newest trusted status comment in `comments` (gh view shape), or null. */
88
+ export function findStatus(comments, trusted) {
89
+ const list = (comments ?? []).filter((c) => isStatusBody(c?.body) && trusted(c) && commentId(c));
90
+ return list.length ? list[list.length - 1] : null;
91
+ }
92
+ /** The newest trusted comment whose body starts with `<!-- marker` (a boundary follows: `FORGE:PARKED code=..` matches `FORGE:PARKED`). */
93
+ export function findLeading(comments, marker, trusted) {
94
+ const re = new RegExp(`^\\s*<!--\\s*${esc(marker)}(?![A-Za-z0-9_:])`);
95
+ const list = (comments ?? []).filter((c) => re.test(String(c?.body ?? "")) && trusted(c) && commentId(c));
96
+ return list.length ? list[list.length - 1] : null;
97
+ }
98
+
99
+ /**
100
+ * Write one status section for `issue`. `known` is the lane's cached `{id, sections}` (or null: look `comments` up). `create` posts a
101
+ * new comment and returns its url; `patch(id, body)` edits one (throws on failure, then a new comment is created). Returns the cache.
102
+ */
103
+ export async function writeStatus({ known, comments, trusted, markers, text, cap = (s) => s, create, patch }) {
104
+ let id = known?.id ?? null, sections = known?.sections ?? null;
105
+ if (!id) {
106
+ const c = findStatus(comments, trusted);
107
+ if (c) { id = commentId(c); sections = parseStatus(c.body); }
108
+ }
109
+ sections = putSection(sections ?? new Map(), markers, text);
110
+ const body = cap(renderStatus(sections));
111
+ if (id) {
112
+ try { await patch(id, body); return { id, sections, url: null }; } catch { /* deleted or not ours: a new comment */ }
113
+ }
114
+ const url = await create(body);
115
+ return { id: commentId({ url }), sections, url };
116
+ }
117
+
118
+ const asArr = (m) => (Array.isArray(m) ? m : [m]);
119
+ const newUrl = async (gh, repo, issue, body) => /https?:\/\/\S+/.exec(String(await gh(["issue", "comment", String(issue), "-R", repo, "--body", body])))?.[0] ?? null;
120
+ const patchWith = (gh, repo) => (id, body) => gh(["api", "-X", "PATCH", `repos/${repo}/issues/comments/${id}`, "-f", `body=${body}`]);
121
+ const viewComments = async (gh, repo, issue) => { try { return JSON.parse(String(await gh(["issue", "view", String(issue), "-R", repo, "--json", "comments"])))?.comments ?? []; } catch { return []; } };
122
+
123
+ /** True when a post with these markers belongs in the status comment. */
124
+ export const isStatusPost = (marker) => STATUS_SECTIONS.includes(asArr(marker)[0]);
125
+ /** True when a post with these markers is edited in place. */
126
+ export const isUpsertPost = (marker) => UPSERT_MARKERS.includes(asArr(marker)[0]);
127
+
128
+ /**
129
+ * gh-only variant for callers outside the lane (the batch runner): reads the issue's comments, then writes the section.
130
+ * `trusted` defaults to the engine's own trust predicate (trusted association, Bot, or the ForgeDock App).
131
+ */
132
+ export async function postStatusSection({ gh, repo, issue, markers, text, cap = (s) => s, trusted }) {
133
+ const t = trusted ?? (await import("./prefilter.mjs")).isTrustedIssueComment;
134
+ const r = await writeStatus({ comments: await viewComments(gh, repo, issue), trusted: t, markers: asArr(markers), text, cap,
135
+ create: (b) => newUrl(gh, repo, issue, b), patch: patchWith(gh, repo) });
136
+ return r.url;
137
+ }
138
+
139
+ /** Post `body` under `markers`, editing the newest trusted comment that already leads with the first marker. Returns the comment url. */
140
+ export async function postUpsert({ gh, repo, issue, markers, body, comments = null, cap = (s) => s, trusted, attrs = "" }) {
141
+ const t = trusted ?? (await import("./prefilter.mjs")).isTrustedIssueComment;
142
+ const ms = asArr(markers);
143
+ const head = ms.map((m, i) => (i === 0 && attrs ? `<!-- ${m} ${attrs} -->` : markLine(m))).join("\n");
144
+ const full = cap(`${head}\n${body}`);
145
+ const prior = findLeading(comments ?? await viewComments(gh, repo, issue), ms[0], t);
146
+ if (prior) {
147
+ try { await patchWith(gh, repo)(commentId(prior), full); return prior.url ?? null; } catch { /* deleted or not ours: a new comment */ }
148
+ }
149
+ return newUrl(gh, repo, issue, full);
150
+ }
151
+
152
+ /** #5592: labels that mean "parked / waiting for a person or the remediation queue"; a live or finished issue must not keep them. */
153
+ export const isPipelineLabel = (name) => { const n = String(name ?? ""); return n === "needs-human" || n.startsWith("needs-human:") || n.startsWith("parked:") || n === "remediation-queue"; };
154
+ /** The pipeline labels among `labels` (names, or `{name}` objects). */
155
+ export const pipelineLabels = (labels) => (labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(isPipelineLabel);
156
+
157
+ /**
158
+ * Remove the pipeline labels from an issue. `labels` is what the caller already read (names or `{name}`); null re-reads them.
159
+ * Best effort, returns the removed names ([] when none or on failure).
160
+ */
161
+ export async function clearPipelineLabels({ gh, repo, issue, labels = null }) {
162
+ try {
163
+ const names = pipelineLabels(labels ?? JSON.parse(String(await gh(["issue", "view", String(issue), "-R", repo, "--json", "labels"])))?.labels);
164
+ if (!names.length) return [];
165
+ await gh(["issue", "edit", String(issue), "-R", repo, "--remove-label", names.join(",")]);
166
+ return names;
167
+ } catch { return []; }
168
+ }
@@ -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
+ });
@@ -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 }) {
@@ -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 () => ({ status: 200, body: { agents: await capacities(), sandboxes: sbx() } }))],
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" }],
@@ -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
- ciCancelOnly = ciFailing > 0 && redChecks(checks, required).blockRows.every((k) => k.bucket === "cancel");
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
  }