forgedock 1.54.1 → 1.55.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 (110) hide show
  1. package/bin/engine/events.mjs +1 -0
  2. package/bin/engine/events.test.mjs +5 -1
  3. package/bin/engine/outcome-codes.mjs +3 -0
  4. package/bin/engine-cli.mjs +126 -34
  5. package/bin/forgedock.mjs +54 -2
  6. package/bin/gc-schedule.mjs +83 -0
  7. package/bin/gc.mjs +56 -8
  8. package/bin/help-text.mjs +1 -1
  9. package/bin/hooks/pre-tool-use.mjs +1 -0
  10. package/bin/init-detect.mjs +73 -2
  11. package/bin/labels.json +5 -0
  12. package/bin/lean/admission.mjs +21 -1
  13. package/bin/lean/baselines.mjs +43 -0
  14. package/bin/lean/baselines.test.mjs +33 -0
  15. package/bin/lean/batch-health.mjs +43 -6
  16. package/bin/lean/batch-health.test.mjs +41 -1
  17. package/bin/lean/batch.mjs +41 -4
  18. package/bin/lean/batch.test.mjs +106 -3
  19. package/bin/lean/conformance.mjs +131 -12
  20. package/bin/lean/conformance.test.mjs +172 -3
  21. package/bin/lean/depcache.mjs +23 -2
  22. package/bin/lean/depcache.test.mjs +22 -0
  23. package/bin/lean/docsgate.mjs +137 -0
  24. package/bin/lean/docsgate.test.mjs +78 -0
  25. package/bin/lean/effects.mjs +31 -2
  26. package/bin/lean/enumerating.mjs +39 -13
  27. package/bin/lean/enumerating.test.mjs +20 -0
  28. package/bin/lean/execution.test.mjs +3 -3
  29. package/bin/lean/fastforward.mjs +93 -0
  30. package/bin/lean/fastforward.test.mjs +73 -0
  31. package/bin/lean/guardgate.mjs +38 -7
  32. package/bin/lean/guardgate.test.mjs +39 -0
  33. package/bin/lean/issuewatch-install.mjs +92 -0
  34. package/bin/lean/issuewatch-install.test.mjs +31 -0
  35. package/bin/lean/issuewatch-parity.mjs +33 -3
  36. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  37. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  38. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  39. package/bin/lean/issuewatch-verify.mjs +51 -9
  40. package/bin/lean/issuewatch.mjs +153 -33
  41. package/bin/lean/issuewatch.test.mjs +243 -22
  42. package/bin/lean/lean.mjs +381 -75
  43. package/bin/lean/lean.test.mjs +437 -20
  44. package/bin/lean/light.mjs +11 -3
  45. package/bin/lean/light.test.mjs +27 -0
  46. package/bin/lean/lightlane.mjs +8 -3
  47. package/bin/lean/lightlane.test.mjs +20 -0
  48. package/bin/lean/mechfix.mjs +21 -2
  49. package/bin/lean/mechfix.test.mjs +28 -1
  50. package/bin/lean/orchestrate-children.test.mjs +10 -0
  51. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  52. package/bin/lean/orchestrate.mjs +28 -4
  53. package/bin/lean/overlap.mjs +20 -0
  54. package/bin/lean/overlap.test.mjs +49 -0
  55. package/bin/lean/pagegate.mjs +152 -0
  56. package/bin/lean/pagegate.test.mjs +77 -0
  57. package/bin/lean/parked-relabel.mjs +32 -0
  58. package/bin/lean/parked-relabel.test.mjs +45 -0
  59. package/bin/lean/phaseledger.mjs +17 -2
  60. package/bin/lean/postdeploy-check.mjs +27 -0
  61. package/bin/lean/postdeploy-check.test.mjs +13 -1
  62. package/bin/lean/postrun.mjs +32 -0
  63. package/bin/lean/postrun.test.mjs +41 -0
  64. package/bin/lean/preflight.mjs +46 -0
  65. package/bin/lean/preflight.test.mjs +30 -1
  66. package/bin/lean/prompts.mjs +36 -6
  67. package/bin/lean/recovery.test.mjs +16 -0
  68. package/bin/lean/release.mjs +23 -2
  69. package/bin/lean/release.test.mjs +28 -1
  70. package/bin/lean/render.mjs +17 -6
  71. package/bin/lean/reproquality.mjs +116 -0
  72. package/bin/lean/reproquality.test.mjs +85 -0
  73. package/bin/lean/review-trigger.mjs +8 -3
  74. package/bin/lean/sandbox-budget.test.mjs +27 -0
  75. package/bin/lean/schedd.mjs +40 -11
  76. package/bin/lean/schedd.test.mjs +12 -1
  77. package/bin/lean/testadequacy.mjs +97 -0
  78. package/bin/lean/testadequacy.test.mjs +92 -0
  79. package/bin/lean/testsandbox.mjs +202 -0
  80. package/bin/lean/testsandbox.test.mjs +157 -0
  81. package/bin/lean/toolplace.mjs +5 -2
  82. package/bin/lean/toolplace.test.mjs +6 -0
  83. package/bin/lean/verify.mjs +6 -1
  84. package/bin/lean/verify.test.mjs +18 -2
  85. package/bin/lean/warmtree.mjs +77 -0
  86. package/bin/lean/warmtree.test.mjs +81 -0
  87. package/bin/stats/conformance-outcomes.mjs +12 -2
  88. package/bin/stats/depth.mjs +24 -1
  89. package/bin/stats/depth.test.mjs +21 -1
  90. package/bin/stats/index.mjs +5 -2
  91. package/bin/stats/query.mjs +2 -1
  92. package/commands/cleanup.md +18 -0
  93. package/commands/fd-introspect.md +19 -0
  94. package/commands/milestone.md +5 -1
  95. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  96. package/commands/recover-orphans.md +31 -1
  97. package/commands/review-pr-staging.md +9 -0
  98. package/commands/review-pr.md +2 -0
  99. package/docs/CONFIG.md +26 -1
  100. package/docs/EVENTS.md +1 -0
  101. package/docs/ISSUE-WATCH.md +12 -3
  102. package/docs/eval/adversarial-bench.md +1 -1
  103. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  104. package/package.json +1 -1
  105. package/scripts/bench-lightlane.mjs +3 -2
  106. package/scripts/hotspots.sh +7 -4
  107. package/scripts/hotspots.test.sh +12 -0
  108. package/scripts/recover-orphans-stateless.test.sh +79 -0
  109. package/scripts/transition-label.sh +2 -0
  110. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
@@ -0,0 +1,152 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5428: the page gate. A diff that adds or changes a public page needs an approved design (FORGE:DESIGN_SPEC), an SEO intent/ICP brief
5
+ * and a GEO brief in the contract (`page_gate`), and passes deterministic checks (sitemap, metadata, canonical, structured data, internal
6
+ * links, forbidden raw-JSON/null-sample patterns). forge.yaml `pages: {enabled, routes, icp_doc, require, sitemap, metadata_patterns,
7
+ * canonical_patterns, structured_data_patterns, forbid_patterns, lint}`. On by default only for repos with Next `app/**\/page.*` files;
8
+ * `enabled: false` or no pages = off. Deterministic, 0 LLM calls; core stays repo-agnostic (#1347), like docsgate.mjs.
9
+ */
10
+ import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
11
+ import { globToRegex } from "../../scripts/ci-local/lib.mjs";
12
+ import { routePathOf } from "./routecheck.mjs";
13
+
14
+ export const PAGE_REQUIRE = Object.freeze(["design", "seo_intent", "geo"]);
15
+ export const PAGE_RE = /(?:^|\/)app\/(?:.*\/)?page\.[cm]?[jt]sx?$/;
16
+ const TEST_RE = /(?:^|\/)(?:__tests__|tests?)\/|\.(?:test|spec)\.[cm]?[jt]sx?$/;
17
+ const DEFAULTS = {
18
+ sitemap: ["**/sitemap.*", "**/sitemap*.xml"],
19
+ metadata: ["export\\s+const\\s+metadata\\b", "generateMetadata", "<title[ >]"],
20
+ canonical: ["canonical"],
21
+ structured: ["application/ld\\+json", "json-?ld"],
22
+ forbid: ["\\[\\[null\\]\\]", "Success rate\\s*0\\.0%", "catalog temporarily unavailable", "JSON\\.stringify\\([^)]*,\\s*null,\\s*2\\)"],
23
+ };
24
+ const norm = (p) => String(p ?? "").trim().replace(/^\.\//, "");
25
+ const blank = (v) => v == null || (typeof v === "string" ? !v.trim() : Array.isArray(v) ? !v.length : false);
26
+ const sq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
27
+ const list = (v) => (Array.isArray(v) ? v : typeof v === "string" ? v.replace(/^\[|\]$/g, "").split(",") : []).map((x) => String(x ?? "").trim().replace(/^(["'])(.*)\1$/, "$2").trim()).filter(Boolean);
28
+ const anyGlob = (globs, f) => globs.some((g) => globToRegex(g).test(f));
29
+ const regexes = (src) => src.flatMap((s) => { try { return [new RegExp(s, "i")]; } catch { return []; } });
30
+
31
+ /** forge.yaml pages: -> config, or null when off. `hasAppPages`: the repo tracks Next app/**\/page.* files (default-on trigger). */
32
+ export function parsePagesConfig(raw, { hasAppPages = false } = {}) {
33
+ const obj = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
34
+ if (obj.enabled === false || String(obj.enabled).toLowerCase() === "false") return null;
35
+ const routes = list(obj.routes).map(norm);
36
+ if (!hasAppPages && !routes.length) return null;
37
+ const req = list(obj.require).map((k) => k.toLowerCase()).filter((k) => PAGE_REQUIRE.includes(k));
38
+ const pick = (v, d) => { const l = list(v); return l.length ? l : d; };
39
+ return {
40
+ routes, icp_doc: typeof obj.icp_doc === "string" && obj.icp_doc.trim() ? obj.icp_doc.trim() : null,
41
+ require: raw && obj.require !== undefined && req.length ? [...new Set(req)] : [...PAGE_REQUIRE],
42
+ sitemap: pick(obj.sitemap, DEFAULTS.sitemap).map(norm), metadata_patterns: pick(obj.metadata_patterns, DEFAULTS.metadata),
43
+ canonical_patterns: pick(obj.canonical_patterns, DEFAULTS.canonical), structured_data_patterns: pick(obj.structured_data_patterns, DEFAULTS.structured),
44
+ forbid_patterns: pick(obj.forbid_patterns, DEFAULTS.forbid), lint: typeof obj.lint === "string" && obj.lint.trim() ? obj.lint.trim() : null,
45
+ };
46
+ }
47
+
48
+ /** The public page files among `files`: built-in Next `app/**\/page.*` plus `pages.routes` globs, tests excluded. */
49
+ export function pageFiles(files, cfg) {
50
+ if (!cfg) return [];
51
+ return [...new Set((files ?? []).map(norm).filter((f) => f && !TEST_RE.test(f) && (PAGE_RE.test(f) || anyGlob(cfg.routes, f))))];
52
+ }
53
+
54
+ const present = (o, ks) => ks.filter((k) => blank(o?.[k]));
55
+
56
+ /** Contract-time problems: a deliverable that is a page needs `page_gate` {design_spec, seo, geo} per `pages.require`. [] when off or no page deliverable. */
57
+ export function contractBriefProblems(contract, cfg) {
58
+ const pages = pageFiles((contract?.deliverables ?? []).map((d) => d?.path), cfg);
59
+ if (!pages.length) return [];
60
+ const g = contract?.page_gate, out = [], at = `deliverable page ${pages.slice(0, 3).join(", ")} needs contract.page_gate`;
61
+ if (!g || typeof g !== "object" || Array.isArray(g)) return [`${at}: {"design_spec":"<FORGE:DESIGN_SPEC ref>","seo":{...},"geo":{...}} (forge.yaml pages.require: ${cfg.require.join(", ")})`];
62
+ if (cfg.require.includes("design") && blank(g.design_spec)) out.push(`${at}.design_spec: the approved FORGE:DESIGN_SPEC (run /design first; issue or comment ref)`);
63
+ if (cfg.require.includes("seo_intent")) {
64
+ const miss = present(g.seo, ["intent", "icp", "title", "h1", "meta", "structured_data", "links_in", "links_out", "gsc_baseline", "measure_by"]);
65
+ if (miss.length) out.push(`${at}.seo is missing ${miss.join(", ")} (target query/intent, named ICP${cfg.icp_doc ? ` from ${cfg.icp_doc}` : ""}, title/H1/meta, structured data type, internal links in/out, GSC baseline, measure-by date)`);
66
+ }
67
+ if (cfg.require.includes("geo")) {
68
+ const miss = present(g.geo, ["surfaces", "agent_question"]);
69
+ if (miss.length) out.push(`${at}.geo is missing ${miss.join(", ")} (llms.txt/llms-full/markdown mirror/ai-catalog/MCP surfaces and a natural-language agent question that resolves to the page)`);
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /** True when the issue comments carry a FORGE:DESIGN_SPEC that is not marked draft/rejected; false when none. */
75
+ export function designSpecApproved(comments) {
76
+ return (comments ?? []).map((c) => String(c?.body ?? c ?? "")).some((b) => b.includes("FORGE:DESIGN_SPEC") && !/"?(?:status|approved)"?\s*[:=]\s*"?(?:draft|rejected|false)/i.test(b));
77
+ }
78
+
79
+ /** #5442: the first `design:*` label before approval (`design:needed`...), or null; `design:approved` lifts the hold. */
80
+ export function designHold(labels) {
81
+ const names = (labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean);
82
+ return names.includes("design:approved") ? null : names.find((n) => n.startsWith("design:")) ?? null;
83
+ }
84
+ /** #5442: true when the `design:approved` label is on the issue. */
85
+ export const designLabelApproved = (labels) => (labels ?? []).some((l) => (typeof l === "string" ? l : l?.name) === "design:approved");
86
+
87
+ /** Added lines per file from a unified diff. */
88
+ export function addedByFile(diff) {
89
+ const out = {}; let cur = null;
90
+ for (const line of String(diff ?? "").split("\n")) {
91
+ if (line.startsWith("+++ ")) { cur = line.replace(/^\+\+\+ (?:b\/)?/, "").trim(); if (cur === "/dev/null") cur = null; continue; }
92
+ if (cur && line.startsWith("+")) (out[cur] ??= []).push(line.slice(1));
93
+ }
94
+ return out;
95
+ }
96
+
97
+ /** URL path served by a Next page file, or null. */
98
+ export function pageRouteOf(file) {
99
+ const m = /(?:^|\/)app\/(?:(.*)\/)?page\.[cm]?[jt]sx?$/.exec(String(file ?? ""));
100
+ return m ? `/${(m[1] ?? "").split("/").filter((s) => s && !/^\(.*\)$/.test(s) && !s.startsWith("@")).join("/")}` : null;
101
+ }
102
+ const routeRe = (r) => new RegExp(`^${r.split("/").map((s) => (/^\[\[?\.\.\.|^\[/.test(s) ? "[^/]*(?:/.*)?" : s.replace(/[.+^${}()|\\]/g, "\\$&"))).join("/")}$`.replace("/[^/]*(?:/.*)?$", "(?:/.*)?$"));
103
+ const LINK_RE = /href\s*=\s*\{?\s*["'`](\/[^"'`#?\s{}$]*)/g;
104
+
105
+ /**
106
+ * Blocking failures (conformance.unimplemented) for the pages a diff adds or changes. `readFile(path)` returns worktree content or "";
107
+ * `tracked` the repo's files; `designApproved` true/false/null (unknown skips); `run({command})` -> {rc, output} for `pages.lint`.
108
+ */
109
+ export async function pageFailures({ cfg, files = [], diff = "", result = null, readFile = () => "", tracked = null, designApproved = null, run = null }) {
110
+ const pages = pageFiles(files, cfg);
111
+ if (!cfg || !pages.length) return [];
112
+ const C = OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, out = [], j = result?.page_gate ?? {};
113
+ const row = (kind, detail) => out.push({ code: C, kind, detail });
114
+ if (cfg.require.includes("design")) {
115
+ if (designApproved === false) row("page_design_missing", `${pages.slice(0, 3).join(", ")} is a public page but the issue has no approved FORGE:DESIGN_SPEC: run /design before building`);
116
+ const shots = list(j.screenshots).join(" ");
117
+ if (!/390/.test(shots) || !/1440/.test(shots)) row("page_visual_missing", `${pages.slice(0, 3).join(", ")}: the result's page_gate.screenshots must name a 390px and a 1440px visual check attached to the PR`);
118
+ }
119
+ const all = [...new Set([...(tracked ?? []), ...files].map(norm))];
120
+ if (cfg.require.includes("seo_intent")) {
121
+ const meta = regexes(cfg.metadata_patterns), canon = regexes(cfg.canonical_patterns), sd = regexes(cfg.structured_data_patterns);
122
+ for (const f of pages) {
123
+ const dir = f.split("/").slice(0, -1);
124
+ const ctx = [f, ...all.filter((p) => /(?:^|\/)layout\.[cm]?[jt]sx?$/.test(p) && (p.split("/").slice(0, -1).join("/") === "" || dir.join("/").startsWith(p.split("/").slice(0, -1).join("/"))))].map((p) => String(readFile(p) ?? "")).join("\n");
125
+ if (!meta.some((r) => r.test(ctx))) row("page_metadata_missing", `${f} has no title/description metadata (forge.yaml pages.metadata_patterns)`);
126
+ if (!canon.some((r) => r.test(ctx))) row("page_canonical_missing", `${f} declares no canonical URL (pages.canonical_patterns)`);
127
+ if (!sd.some((r) => r.test(ctx))) row("page_structured_data_missing", `${f} emits no structured data / JSON-LD (pages.structured_data_patterns)`);
128
+ }
129
+ if (!files.map(norm).some((f) => anyGlob(cfg.sitemap, f)) && blank(j.sitemap_justification)) row("page_sitemap_missing", `${pages.slice(0, 3).join(", ")} needs a sitemap entry (a change under ${cfg.sitemap.join(", ")}) or page_gate.sitemap_justification in the result (a generated sitemap)`);
130
+ }
131
+ const added = addedByFile(diff), forbid = regexes(cfg.forbid_patterns);
132
+ for (const f of pages) {
133
+ const lines = added[f] ?? [];
134
+ const hit = forbid.find((r) => lines.some((l) => r.test(l)));
135
+ if (hit) row("page_forbidden_pattern", `${f} adds content matching /${hit.source}/ (null sample, raw JSON or dead-end state on a public page; forge.yaml pages.forbid_patterns)`);
136
+ }
137
+ if (tracked) {
138
+ const routes = all.map(pageRouteOf).concat(all.map(routePathOf)).filter(Boolean).map(routeRe);
139
+ const bad = new Set();
140
+ for (const f of pages) for (const l of added[f] ?? []) for (const m of l.matchAll(LINK_RE)) {
141
+ const p = m[1].replace(/\/+$/, "") || "/";
142
+ if (!routes.some((r) => r.test(p)) && !all.includes(`public${p}`) && !all.some((a) => a.endsWith(`/public${p}`))) bad.add(p);
143
+ }
144
+ if (bad.size) row("page_link_broken", `a public page links to ${[...bad].slice(0, 5).join(", ")} which no page, route or public file serves: create it or fix the link`);
145
+ }
146
+ if (cfg.lint && run) {
147
+ let r;
148
+ try { r = await run({ command: `${cfg.lint} ${pages.map(sq).join(" ")}` }); r = r?.r ?? r; } catch (e) { r = { rc: 127, output: String(e?.message ?? e) }; }
149
+ if (r?.rc !== 0) row("page_lint_failed", `forge.yaml pages.lint (\`${cfg.lint}\`) exited ${r?.rc ?? "?"}${r?.output ? `:\n${String(r.output).trim().split("\n").slice(-12).join("\n").slice(0, 1500)}` : ""}`);
150
+ }
151
+ return out;
152
+ }
@@ -0,0 +1,77 @@
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 { parsePagesConfig, pageFiles, contractBriefProblems, pageFailures, designSpecApproved, designHold, designLabelApproved } from "./pagegate.mjs";
6
+ import { pagePlanNote, domainChecksBlock } from "./prompts.mjs";
7
+ import { pathDomains } from "./review-trigger.mjs";
8
+ import { validateContract, precheck } from "./conformance.mjs";
9
+
10
+ const cfg = parsePagesConfig(undefined, { hasAppPages: true });
11
+ // The shape of the AlterLab Store PRs (#5428): listing pages with null samples, no structured data, no sitemap, no briefs.
12
+ const storeFiles = ["web/app/store/[slug]/page.tsx"];
13
+ const storeDiff = "+++ b/web/app/store/[slug]/page.tsx\n+<p>Sample output [[null]]</p>\n+<p>Success rate 0.0%</p>\n+<a href=\"/pricing\">x</a>\n";
14
+ const read = (p) => (p === storeFiles[0] ? "export default function P() { return null }" : "");
15
+
16
+ describe("page gate (#5428)", () => {
17
+ it("is on by default only for app repos and off when disabled", () => {
18
+ assert.equal(parsePagesConfig(undefined), null);
19
+ assert.equal(parsePagesConfig({ enabled: false }, { hasAppPages: true }), null);
20
+ assert.deepEqual(cfg.require, ["design", "seo_intent", "geo"]);
21
+ assert.equal(parsePagesConfig({ routes: ["site/**/*.html"] }).routes.length, 1);
22
+ assert.deepEqual(pageFiles(["web/app/a/page.tsx", "web/app/a/page.test.tsx", "web/app/api/x/route.ts"], cfg), ["web/app/a/page.tsx"]);
23
+ assert.equal(pagePlanNote(null), "");
24
+ assert.match(pagePlanNote(cfg), /page_gate/);
25
+ });
26
+ it("replay at contract time: a page deliverable with no design spec, ICP or GEO brief fails validateContract", () => {
27
+ const c = { deliverables: [{ id: "D1", path: storeFiles[0], change: "x", requirements: ["R1"] }] };
28
+ assert.equal(contractBriefProblems(c, cfg).length, 1);
29
+ const partial = { ...c, page_gate: { design_spec: "", seo: { intent: "buy tools" }, geo: {} } };
30
+ const p = contractBriefProblems(partial, cfg).join("\n");
31
+ assert.match(p, /design_spec/); assert.match(p, /seo is missing .*icp/); assert.match(p, /geo is missing/);
32
+ const issue = "Add the store page";
33
+ const v = validateContract({ requirements: [{ id: "R1", quote: "Add the store page", disposition: "deliver" }], deliverables: c.deliverables, validate: [{ id: "V1", command: "true" }] }, issue, { pages: cfg });
34
+ assert.ok(v.problems.some((x) => /page_gate/.test(x)));
35
+ const ok = { ...c, page_gate: { design_spec: "#1 FORGE:DESIGN_SPEC", seo: { intent: "a", icp: "b", title: "c", h1: "d", meta: "e", structured_data: "Product", links_in: ["/"], links_out: ["/x"], gsc_baseline: "none", measure_by: "2027-01-01" }, geo: { surfaces: ["llms.txt"], agent_question: "q?" } } };
36
+ assert.deepEqual(contractBriefProblems(ok, cfg), []);
37
+ assert.deepEqual(contractBriefProblems(c, null), []);
38
+ });
39
+ it("replay at CI: null samples, missing structured data, sitemap, canonical, design and screenshots all fail precheck", async () => {
40
+ const f = await pageFailures({ cfg, files: storeFiles, diff: storeDiff, readFile: read, tracked: storeFiles, designApproved: false });
41
+ assert.deepEqual([...new Set(f.map((x) => x.kind))].sort(), ["page_canonical_missing", "page_design_missing", "page_forbidden_pattern", "page_link_broken", "page_metadata_missing", "page_sitemap_missing", "page_structured_data_missing", "page_visual_missing"]);
42
+ const pc = precheck({ contract: { requirements: [], deliverables: [], validate: [] }, result: {}, changedFiles: storeFiles, pageFailures: f });
43
+ assert.ok(pc.failures.some((x) => x.kind === "page_sitemap_missing"));
44
+ });
45
+ it("passes a complete page, ignores repos without pages, and runs pages.lint", async () => {
46
+ const good = (p) => (p === storeFiles[0] ? "export const metadata = {alternates:{canonical:'/s'}}; <script type=\"application/ld+json\"/>" : "");
47
+ const files = [...storeFiles, "web/app/sitemap.ts"];
48
+ const diff = "+++ b/web/app/store/[slug]/page.tsx\n+<a href=\"/store\">all</a>\n";
49
+ const tracked = [...files, "web/app/store/page.tsx"];
50
+ const shots = { page_gate: { screenshots: ["home-390.png", "home-1440.png"] } };
51
+ assert.deepEqual(await pageFailures({ cfg, files, diff, readFile: good, tracked, designApproved: true, result: shots }), []);
52
+ assert.deepEqual(await pageFailures({ cfg, files: ["src/cli.ts"], diff: "", tracked: [] }), []);
53
+ assert.deepEqual(await pageFailures({ cfg: null, files: storeFiles }), []);
54
+ const lint = { ...cfg, lint: "bash lint.sh" };
55
+ const bad = await pageFailures({ cfg: lint, files, diff, readFile: good, tracked, designApproved: true, result: shots, run: async () => ({ rc: 1, output: "nope" }) });
56
+ assert.deepEqual(bad.map((x) => x.kind), ["page_lint_failed"]);
57
+ });
58
+ it("reads design spec approval and adds design + seo-geo review domains", () => {
59
+ assert.equal(designSpecApproved([{ body: "<!-- FORGE:DESIGN_SPEC -->\n{}" }]), true);
60
+ assert.equal(designSpecApproved([{ body: "FORGE:DESIGN_SPEC status: draft" }]), false);
61
+ assert.equal(designSpecApproved([]), false);
62
+ const d = pathDomains(storeFiles, { pages: cfg });
63
+ assert.ok(d.includes("design") && d.includes("seo-geo"));
64
+ assert.ok(!pathDomains(storeFiles).includes("design"));
65
+ assert.match(domainChecksBlock(["seo-geo"]), /canonical/);
66
+ });
67
+ });
68
+
69
+ describe("design hold (#5442)", () => {
70
+ it("holds design:* before approval and lifts on design:approved", () => {
71
+ assert.equal(designHold([{ name: "design:needed" }]), "design:needed");
72
+ assert.equal(designHold(["design:needed", "design:approved"]), null);
73
+ assert.equal(designHold([{ name: "bug" }]), null);
74
+ assert.equal(designLabelApproved([{ name: "design:approved" }]), true);
75
+ assert.equal(designLabelApproved([]), false);
76
+ });
77
+ });
@@ -0,0 +1,32 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { parkedLabel, REMEDIATION_QUEUE_LABEL } from "../engine/outcome-codes.mjs";
4
+
5
+ /**
6
+ * #5466: the mechanical-park relabel. Both labels are created first (`--force`); `remediation-queue` is skipped when it
7
+ * cannot be created. Labels are added, then read back, and only then is `needs-human` removed, so a failure at any step
8
+ * leaves the issue with `needs-human` (labels this call added are rolled back). Returns `{ ok, queued }`.
9
+ */
10
+ export async function parkedRelabel({ gh, repo, issue, code }) {
11
+ const parked = parkedLabel(code);
12
+ const n = String(issue);
13
+ try { await gh(["label", "create", parked, "-R", repo, "--force", "--color", "C5DEF5", "--description", "Mechanical park on a terminal code. Managed by ForgeDock."]); } catch { /* exists, or no rights: the add says */ }
14
+ let queued = true;
15
+ try { await gh(["label", "create", REMEDIATION_QUEUE_LABEL, "-R", repo, "--force", "--color", "C5DEF5", "--description", "Parked issues awaiting remediation. Managed by ForgeDock."]); } catch { queued = false; }
16
+ const want = queued ? [parked, REMEDIATION_QUEUE_LABEL] : [parked];
17
+ const rollback = async () => { try { await gh(["issue", "edit", n, "-R", repo, "--remove-label", want.join(",")]); } catch { /* needs-human is still on */ } };
18
+ try {
19
+ await gh(["issue", "edit", n, "-R", repo, "--add-label", want.join(",")]);
20
+ } catch {
21
+ // The add may have applied some labels: if the queue label was the problem, retry with the parked label alone.
22
+ if (!queued) { await rollback(); return { ok: false, queued }; }
23
+ try { await gh(["issue", "edit", n, "-R", repo, "--add-label", parked]); queued = false; } catch { await rollback(); return { ok: false, queued }; }
24
+ }
25
+ try {
26
+ const names = (JSON.parse(await gh(["issue", "view", n, "-R", repo, "--json", "labels"]))?.labels ?? []).map((l) => l?.name);
27
+ if (!names.includes(parked)) { await rollback(); return { ok: false, queued }; }
28
+ if (queued && !names.includes(REMEDIATION_QUEUE_LABEL)) queued = false;
29
+ } catch { await rollback(); return { ok: false, queued }; }
30
+ try { await gh(["issue", "edit", n, "-R", repo, "--remove-label", "needs-human"]); } catch { return { ok: false, queued }; }
31
+ return { ok: true, queued };
32
+ }
@@ -0,0 +1,45 @@
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 { parkedRelabel } from "./parked-relabel.mjs";
6
+
7
+ // A fake issue whose label set a stub `gh` edits; `missing` labels cannot be created or added.
8
+ const fake = ({ missing = [], failVerify = false } = {}) => {
9
+ const labels = new Set(["needs-human"]), calls = [];
10
+ const gh = async (a) => {
11
+ calls.push(a.slice(0, 2).join(" "));
12
+ const list = (f) => String(a[a.indexOf(f) + 1] ?? "").split(",").filter(Boolean);
13
+ if (a[0] === "label") { if (missing.includes(a[2])) throw new Error("create failed"); return ""; }
14
+ if (a[1] === "view") { if (failVerify) throw new Error("view failed"); return JSON.stringify({ labels: [...labels].map((name) => ({ name })) }); }
15
+ if (a.includes("--add-label")) { const ls = list("--add-label"); if (ls.some((l) => missing.includes(l))) throw new Error("add failed"); ls.forEach((l) => labels.add(l)); }
16
+ if (a.includes("--remove-label")) list("--remove-label").forEach((l) => labels.delete(l));
17
+ return "";
18
+ };
19
+ return { labels, calls, run: () => parkedRelabel({ gh, repo: "o/r", issue: 7, code: "ci.red" }) };
20
+ };
21
+
22
+ describe("#5466 parkedRelabel", () => {
23
+ it("adds both labels, verifies, then removes needs-human", async () => {
24
+ const f = fake();
25
+ assert.deepEqual(await f.run(), { ok: true, queued: true });
26
+ assert.deepEqual([...f.labels].sort(), ["parked:ci.red", "remediation-queue"]);
27
+ });
28
+ it("missing remediation-queue label never leaves the issue stateless", async () => {
29
+ const f = fake({ missing: ["remediation-queue"] });
30
+ const r = await f.run();
31
+ assert.equal(r.ok, true);
32
+ assert.equal(r.queued, false);
33
+ assert.deepEqual([...f.labels], ["parked:ci.red"]);
34
+ });
35
+ it("a failed parked add keeps needs-human", async () => {
36
+ const f = fake({ missing: ["parked:ci.red", "remediation-queue"] });
37
+ assert.equal((await f.run()).ok, false);
38
+ assert.deepEqual([...f.labels], ["needs-human"]);
39
+ });
40
+ it("a failed verify rolls back and keeps needs-human", async () => {
41
+ const f = fake({ failVerify: true });
42
+ assert.equal((await f.run()).ok, false);
43
+ assert.deepEqual([...f.labels], ["needs-human"]);
44
+ });
45
+ });
@@ -35,7 +35,7 @@ function waitOf(ms, modelMs, typed = {}, id) {
35
35
  /** Sequential ledger starting in `first` at `start`. `now` is the lane clock. */
36
36
  export function createLedger(now, first = "sandbox_start", start = now()) {
37
37
  let cur = LANE_PHASES.includes(first) ? first : null, since = start;
38
- const ms = {}, model = {}, usd = {}, wait = {};
38
+ const ms = {}, model = {}, usd = {}, wait = {}, steps = {};
39
39
  const close = (t) => { if (cur) ms[cur] = (ms[cur] ?? 0) + Math.max(0, t - since); };
40
40
  const enter = (phase) => {
41
41
  if (!LANE_PHASES.includes(phase) || phase === cur) return;
@@ -61,6 +61,12 @@ export function createLedger(now, first = "sandbox_start", start = now()) {
61
61
  if (!id || !WAIT_CAUSES.includes(cause) || !isNum(waitMs) || waitMs <= 0) return;
62
62
  (wait[id] ??= {})[cause] = (wait[id][cause] ?? 0) + waitMs;
63
63
  },
64
+ /** #5435: `stepMs` spent in the named step of `phase` (sub-timing, e.g. sandbox_start's fetch); not added to the phase total. */
65
+ addStep(phase, name, stepMs) {
66
+ const id = LANE_PHASES.includes(phase) ? phase : cur;
67
+ if (!id || typeof name !== "string" || !name || !isNum(stepMs) || stepMs < 0) return;
68
+ (steps[id] ??= {})[name] = (steps[id][name] ?? 0) + stepMs;
69
+ },
64
70
  /** The ledger as of now (the open phase counted up to now); does not end the current phase. */
65
71
  snapshot() {
66
72
  const t = now(), total = { ...ms };
@@ -69,7 +75,7 @@ export function createLedger(now, first = "sandbox_start", start = now()) {
69
75
  for (const id of LANE_PHASES) {
70
76
  if (!(id in total) && !(id in model) && !(id in usd)) continue;
71
77
  const w = waitOf(total[id] ?? 0, model[id] ?? 0, wait[id], id);
72
- out[id] = { ms: Math.round(total[id] ?? 0), ...(model[id] ? { model_ms: Math.round(model[id]) } : {}), ...(usd[id] ? { usd: Math.round(usd[id] * 1e6) / 1e6 } : {}), ...(Object.keys(w).length ? { wait: w } : {}) };
78
+ out[id] = { ms: Math.round(total[id] ?? 0), ...(model[id] ? { model_ms: Math.round(model[id]) } : {}), ...(usd[id] ? { usd: Math.round(usd[id] * 1e6) / 1e6 } : {}), ...(Object.keys(w).length ? { wait: w } : {}), ...(steps[id] ? { steps: Object.fromEntries(Object.entries(steps[id]).map(([k, x]) => [k, Math.round(x)])) } : {}) };
73
79
  }
74
80
  return out;
75
81
  },
@@ -156,3 +162,12 @@ export function formatLedgerSummary(rows) {
156
162
  return `phases (p50/p90 per lane, ${s.n} lane${s.n === 1 ? "" : "s"}): ${parts.join(", ")}; largest: ${s.largest.phase} (${Math.round(s.largest.share * 100)}% of ledger time)`;
157
163
  } catch { return "phases (wall time): n/a"; }
158
164
  }
165
+
166
+ /** #5435: the local `sandbox_start` budget (issue: p50 <= 3 s on the bench corpus). */
167
+ export const SANDBOX_START_P50_BUDGET_MS = 3000;
168
+
169
+ /** p50 of `sandbox_start` over the lanes' `phases` objects against the budget; `ok` is true when no lane carried the phase. */
170
+ export function sandboxStartBudget(list, budgetMs = SANDBOX_START_P50_BUDGET_MS) {
171
+ const v = summarizePhases(list).phases.sandbox_start;
172
+ return { n: v?.n ?? 0, p50: v?.p50 ?? null, budgetMs, ok: !v || v.p50 <= budgetMs };
173
+ }
@@ -265,3 +265,30 @@ export async function measureFollowup({ iss, repo, parent, def, shas = [], cwd,
265
265
  await io.gh(["issue", "close", String(iss.number), "-R", repo, "--reason", "completed"]);
266
266
  return { state: "pass", detail: `checks ${[...new Set(ids)].join(", ")} passed` };
267
267
  }
268
+
269
+ /**
270
+ * #5468: the generated check for a production-only e2e/manual requirement quote: `{id, entry}` or null when the quote names no
271
+ * URL to probe. A concrete URL is fetched; a templated one (`{slug}`, `<id>`) probes its origin, the most the engine can assert
272
+ * without the builder's data. The entry parses under `parseChecks`.
273
+ */
274
+ export function e2eCheckFor(reqId, quote) {
275
+ const m = /https?:\/\/[^\s`'")>\]]+/.exec(String(quote ?? ""));
276
+ if (!m) return null;
277
+ const url = m[0].replace(/[.,;:]+$/, "");
278
+ const templated = /[{}<>$]/.test(url);
279
+ let target = url;
280
+ if (templated) { try { target = new URL(url.replace(/[{}<>$]/g, "x")).origin + "/"; } catch { return null; } }
281
+ if (!/^https?:\/\/[A-Za-z0-9._~:/?#@!&=+%-]+$/.test(target)) return null;
282
+ let h = 0;
283
+ for (const ch of String(quote)) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
284
+ const id = `e2e-${String(reqId).toLowerCase().replace(/[^a-z0-9]/g, "")}-${h.toString(16).slice(0, 8)}`;
285
+ return { id, entry: { run: `curl -fsS -o /dev/null --max-time 30 '${target}'`, pass: "exit 0", timeout: 60, for: "7d" } };
286
+ }
287
+
288
+ /** #5468: merge generated entries into the checks file text; existing entries win. Returns the new JSON text. */
289
+ export function mergeCheckEntries(text, entries) {
290
+ let cur = {};
291
+ try { const j = JSON.parse(String(text ?? "")); if (j && typeof j === "object" && !Array.isArray(j)) cur = j; } catch { /* absent or malformed: start fresh */ }
292
+ for (const [id, e] of Object.entries(entries ?? {})) if (!(id in cur)) cur[id] = e;
293
+ return `${JSON.stringify(cur, null, 2)}\n`;
294
+ }
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { parseChecks, itemCheckIds, measureFollowup, monitorRecord, CHECK_ID_RE, tickItems } from "./postdeploy-check.mjs";
5
+ import { e2eCheckFor, mergeCheckEntries, parseChecks, itemCheckIds, measureFollowup, monitorRecord, CHECK_ID_RE, tickItems } from "./postdeploy-check.mjs";
6
6
  import { postDeployOnly } from "./prefilter.mjs";
7
7
  import { validateContract, applyAmendments, precheck, followupItems } from "./conformance.mjs";
8
8
  import { PROBE_MARKER } from "./probe.mjs";
@@ -323,3 +323,15 @@ console.log(cs.filter((c) => c.body.startsWith(start) && c.body.includes(has)).l
323
323
  assert.equal(runCheck([{ id: 2, body: "Release notes: the `hotspot_config_missing` anomaly is recorded" }, traj("- none")]).code, 0);
324
324
  });
325
325
  });
326
+
327
+ describe("generated e2e checks (#5468)", () => {
328
+ it("a concrete URL is probed, a templated one probes its origin, no URL generates nothing; entries parse and merge", () => {
329
+ const a = e2eCheckFor("R4", "https://x.example.io/health returns 200 [type:e2e]");
330
+ assert.match(a.entry.run, /'https:\/\/x\.example\.io\/health'/);
331
+ assert.match(e2eCheckFor("R4", "https://x.example.io/{slug}/a.md is 200").entry.run, /'https:\/\/x\.example\.io\/'/);
332
+ assert.equal(e2eCheckFor("R4", "after deploy it works"), null);
333
+ assert.ok(CHECK_ID_RE.test(a.id));
334
+ const merged = parseChecks(mergeCheckEntries(JSON.stringify({ smoke: "echo ok" }), { [a.id]: a.entry }));
335
+ assert.ok(merged.smoke && merged[a.id]);
336
+ });
337
+ });
@@ -0,0 +1,32 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5437: post-decision bookkeeping of a lane (branch delete, structure telemetry, guard, trajectory, teardown) as a queue of
5
+ * named jobs run after RUN_TERMINAL. Jobs run in the order added and are idempotent (a job that finished is never re-run,
6
+ * `run()` is safe to call twice). A failing job is retried with backoff; its outcome is recorded (POSTRUN_OK / POSTRUN_FAILED)
7
+ * and never changes the lane's outcome. Deterministic, 0 LLM calls.
8
+ */
9
+ export function makePostRun({ ev = () => {}, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now, attempts = 3, backoffMs = 1000 } = {}) {
10
+ const jobs = [];
11
+ let running = null;
12
+ async function runJob(j) {
13
+ for (let i = 1; i <= attempts; i++) {
14
+ const t = now();
15
+ try { await j.fn(); j.done = true; ev({ event: "POSTRUN_OK", job: j.name, attempt: i, ms: now() - t }); return; }
16
+ catch (e) {
17
+ const error = String(e?.message ?? e).slice(0, 300);
18
+ if (i === attempts) { j.done = true; ev({ event: "POSTRUN_FAILED", job: j.name, attempts: i, error }); return; }
19
+ try { await sleep(backoffMs * 2 ** (i - 1)); } catch { /* keep going */ }
20
+ }
21
+ }
22
+ }
23
+ return {
24
+ add(name, fn) { jobs.push({ name, fn, done: false }); },
25
+ pending: () => jobs.filter((j) => !j.done).map((j) => j.name),
26
+ /** Runs every job not yet done, once at a time; concurrent callers share one run. */
27
+ run() {
28
+ running ??= (async () => { for (const j of jobs) if (!j.done) await runJob(j); })().finally(() => { running = null; });
29
+ return running;
30
+ },
31
+ };
32
+ }
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5437: the post-run job queue.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { makePostRun } from "./postrun.mjs";
7
+
8
+ const mk = (o = {}) => { const events = [], sleeps = []; return { events, sleeps, q: makePostRun({ ev: (e) => events.push(e), sleep: async (ms) => { sleeps.push(ms); }, ...o }) }; };
9
+
10
+ describe("#5437 makePostRun", () => {
11
+ it("runs jobs in order and records POSTRUN_OK for each", async () => {
12
+ const { q, events } = mk(), order = [];
13
+ q.add("a", async () => order.push("a")); q.add("b", async () => order.push("b"));
14
+ await q.run();
15
+ assert.deepEqual(order, ["a", "b"]);
16
+ assert.deepEqual(events.map((e) => `${e.event}:${e.job}`), ["POSTRUN_OK:a", "POSTRUN_OK:b"]);
17
+ assert.deepEqual(q.pending(), []);
18
+ });
19
+ it("is idempotent: a second run does not re-run finished jobs, and concurrent callers share one run", async () => {
20
+ const { q } = mk(); let n = 0;
21
+ q.add("a", async () => { n++; });
22
+ await Promise.all([q.run(), q.run()]); await q.run();
23
+ assert.equal(n, 1);
24
+ });
25
+ it("retries a failing job with backoff and records the success", async () => {
26
+ const { q, events, sleeps } = mk(); let n = 0;
27
+ q.add("flaky", async () => { if (++n < 3) throw new Error("boom"); });
28
+ await q.run();
29
+ assert.equal(n, 3);
30
+ assert.deepEqual(sleeps, [1000, 2000]);
31
+ assert.equal(events.at(-1).event, "POSTRUN_OK"); assert.equal(events.at(-1).attempt, 3);
32
+ });
33
+ it("a job that keeps failing is recorded POSTRUN_FAILED, never thrown, and later jobs still run", async () => {
34
+ const { q, events } = mk(); let later = false;
35
+ q.add("bad", async () => { throw new Error("nope"); }); q.add("later", async () => { later = true; });
36
+ await q.run();
37
+ assert.equal(later, true);
38
+ const f = events.find((e) => e.event === "POSTRUN_FAILED");
39
+ assert.equal(f.job, "bad"); assert.equal(f.attempts, 3); assert.match(f.error, /nope/);
40
+ });
41
+ });
@@ -262,3 +262,49 @@ export async function runPreflight({ contract, run, git, env = {}, repoHas = ()
262
262
  }
263
263
  return { misses, skipped, reverted };
264
264
  }
265
+
266
+ const JS_ECO = new Set(["pnpm", "npm", "yarn"]);
267
+ const SRC_BY_ECO = (eco) => (JS_ECO.has(eco) ? /\.(?:[cm]?[jt]sx?|vue|svelte)$/i : /\.py$/i);
268
+ const underDir = (dir, f) => !dir || dir === "." || f === dir || f.startsWith(`${dir}/`);
269
+ /**
270
+ * #5447: the failed dependency installs of `results` (depcache prepare rows). One that covers a changed source file of its
271
+ * ecosystem (its dir, "." for the root) is blocking (env.tool_missing, kind dep_install); the rest, and a failure with no
272
+ * ecosystem to place, are logged only. Pure.
273
+ */
274
+ export function depInstallFailures({ results = [], changedFiles = [] } = {}) {
275
+ const block = [], logged = [];
276
+ const dirs = (Array.isArray(results) ? results : []).map((r) => r?.dir).filter((d) => d && d !== ".");
277
+ for (const r of Array.isArray(results) ? results : []) {
278
+ if (r?.status !== "failed") continue;
279
+ const label = `${r.eco ?? "dependencies"}${r.dir && r.dir !== "." ? ` in ${r.dir}` : ""}: ${r.reason ?? "install failed"}`;
280
+ const rx = SRC_BY_ECO(r.eco);
281
+ const hit = r.eco ? changedFiles.find((f) => rx.test(f) && underDir(r.dir, f) && (r.dir && r.dir !== "." ? true : !dirs.some((d) => underDir(d, f)))) : null;
282
+ if (hit) block.push({ code: "env.tool_missing", kind: "dep_install", tool: r.eco, detail: `dependency install failed (${label}) for a package the changed file ${hit} imports (environment, not the change)` });
283
+ else logged.push(`Dependency install failed, unrelated to the changed files: ${label}`);
284
+ }
285
+ return { block, logged };
286
+ }
287
+
288
+ /**
289
+ * #5447: declared vs ran for the FORGE:TRAJECTORY Tests row. Declared: each validate plus the repro_test. Skipped: a
290
+ * declared id named by an env/missing/timeout failure of `failures` (reason = its kind). redGreen: repro BASE=FAILED HEAD=RAN.
291
+ */
292
+ export function testRunSummary({ contract, failures = [], repro = null } = {}) {
293
+ const ids = contractCommands(contract).map((c) => c.id);
294
+ const skipped = [];
295
+ for (const f of failures) {
296
+ if (!["validate_env", "validate_missing", "validate_timeout", "repro_env", "dep_install"].includes(f?.kind)) continue;
297
+ const id = f.kind === "repro_env" ? "repro_test" : /validate (\S+)/.exec(String(f.detail))?.[1];
298
+ if (id && ids.includes(id) && !skipped.some((s) => s.id === id)) skipped.push({ id, reason: f.kind });
299
+ }
300
+ const redGreen = repro && repro.base === "FAILED" && repro.head === "RAN" ? 1 : 0;
301
+ return { declared: ids.length, ran: ids.length - skipped.length, redGreen, skipped };
302
+ }
303
+
304
+ /** #5447: tool names the contract's test plan declares in `env` (per row of the #5445 `test_plan` array, or `test_plan.env`); strings, comma lists or {tool}; [] when absent. Pure. */
305
+ export function declaredEnv(contract) {
306
+ const plan = contract?.test_plan;
307
+ const raw = Array.isArray(plan) ? plan.map((r) => r?.env) : [plan?.env];
308
+ const names = raw.flatMap((e) => (Array.isArray(e) ? e : typeof e === "string" ? e.split(",") : [])).map((e) => String(typeof e === "string" ? e : e?.tool ?? "").trim());
309
+ return [...new Set(names.filter((t) => /^[\w.+-]+$/.test(t)))];
310
+ }
@@ -4,7 +4,7 @@ import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
5
  import { mkdirSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
- import { testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands } from "./preflight.mjs";
7
+ import { testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, testRunSummary } from "./preflight.mjs";
8
8
  import { runCheckCommand } from "./effects.mjs";
9
9
  import { repoTracks } from "./conformance.mjs";
10
10
  import { tmpDir } from "../tests/_tmp.mjs";
@@ -132,3 +132,32 @@ describe("#5020 repro_test is probed like a validate command", () => {
132
132
  assert.ok(probes.some((p) => p.tool === "madeuptool" && p.ids.includes("repro_test")));
133
133
  });
134
134
  });
135
+
136
+ describe("#5447 unrunnable tests: install classification and the Tests summary", () => {
137
+ it("a failed install covering a changed source file blocks; an unrelated one is logged", () => {
138
+ const results = [{ status: "failed", eco: "poetry", dir: "services/cortex", reason: "install failed" }, { status: "failed", eco: "npm", dir: "web", reason: "ERESOLVE" }, { status: "miss-installed", eco: "uv", dir: "." }];
139
+ const r = depInstallFailures({ results, changedFiles: ["services/cortex/app/x.py", "README.md"] });
140
+ assert.deepEqual(r.block.map((f) => [f.code, f.kind, f.tool]), [["env.tool_missing", "dep_install", "poetry"]]);
141
+ assert.equal(r.logged.length, 1); assert.match(r.logged[0], /npm in web/);
142
+ assert.deepEqual(depInstallFailures({ results: [{ status: "failed", eco: null, reason: "x" }], changedFiles: ["a.py"] }).block, []);
143
+ });
144
+ it("a root install failure does not block for a file owned by a nested project", () => {
145
+ const results = [{ status: "failed", eco: "uv", dir: ".", reason: "r" }, { status: "hit", eco: "uv", dir: "svc" }];
146
+ assert.deepEqual(depInstallFailures({ results, changedFiles: ["svc/a.py"] }).block, []);
147
+ assert.equal(depInstallFailures({ results, changedFiles: ["top.py"] }).block.length, 1);
148
+ });
149
+ it("testRunSummary counts declared, ran, red->green and skipped(reason)", () => {
150
+ const c = { validate: [{ id: "V1", command: "a" }, { id: "V2", command: "b" }], repro_test: { command: "c" } };
151
+ const t = testRunSummary({ contract: c, failures: [{ kind: "validate_env", detail: "validate V2 (`b`) could not run" }], repro: { base: "FAILED", head: "RAN" } });
152
+ assert.deepEqual(t, { declared: 3, ran: 2, redGreen: 1, skipped: [{ id: "V2", reason: "validate_env" }] });
153
+ });
154
+ });
155
+
156
+ describe("#5447 declaredEnv", () => {
157
+ it("reads test_plan.env tool names", async () => {
158
+ const { declaredEnv } = await import("./preflight.mjs");
159
+ assert.deepEqual(declaredEnv({ test_plan: { env: ["pytest", { tool: "uv" }, "bad name"] } }), ["pytest", "uv"]);
160
+ assert.deepEqual(declaredEnv({ test_plan: [{ requirement: "R1", env: "pytest, uv" }, { requirement: "R2" }] }), ["pytest", "uv"]);
161
+ assert.deepEqual(declaredEnv({}), []);
162
+ });
163
+ });