forgedock 1.56.0 → 1.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +1 -1
- package/bin/engine/outcome-codes.mjs +1 -0
- package/bin/engine/phases.mjs +4 -3
- package/bin/engine-cli.mjs +46 -10
- package/bin/forgedock.mjs +52 -3
- package/bin/gc.mjs +43 -6
- package/bin/help-text.mjs +3 -1
- package/bin/lean/batch-health.mjs +5 -1
- package/bin/lean/batch-health.test.mjs +7 -1
- package/bin/lean/batch.mjs +7 -2
- package/bin/lean/batch.test.mjs +45 -0
- package/bin/lean/conformance.e2e.test.mjs +3 -2
- package/bin/lean/conformance.mjs +88 -17
- package/bin/lean/conformance.test.mjs +98 -3
- package/bin/lean/decisions.mjs +86 -1
- package/bin/lean/decisions.test.mjs +21 -1
- package/bin/lean/depcache.mjs +124 -13
- package/bin/lean/depcache.test.mjs +121 -3
- package/bin/lean/design-gate.mjs +144 -0
- package/bin/lean/design-gate.test.mjs +169 -0
- package/bin/lean/effects-cap.test.mjs +17 -0
- package/bin/lean/effects.mjs +58 -13
- package/bin/lean/heavy.mjs +25 -8
- package/bin/lean/hostload.test.mjs +28 -0
- package/bin/lean/intake.mjs +97 -0
- package/bin/lean/intake.test.mjs +105 -0
- package/bin/lean/interfaces.mjs +181 -0
- package/bin/lean/interfaces.test.mjs +192 -0
- package/bin/lean/issuewatch-install.mjs +52 -12
- package/bin/lean/issuewatch-install.test.mjs +50 -0
- package/bin/lean/issuewatch-parity.mjs +12 -2
- package/bin/lean/issuewatch-parity.test.mjs +26 -0
- package/bin/lean/issuewatch-reconcile.mjs +29 -1
- package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
- package/bin/lean/issuewatch.mjs +34 -3
- package/bin/lean/issuewatch.test.mjs +49 -1
- package/bin/lean/lanecheck.test.mjs +15 -4
- package/bin/lean/lean.mjs +72 -21
- package/bin/lean/lean.test.mjs +149 -3
- package/bin/lean/orchestrate-blocked.test.mjs +18 -2
- package/bin/lean/orchestrate-owned.test.mjs +14 -5
- package/bin/lean/orchestrate.mjs +26 -4
- package/bin/lean/orphan-pr.mjs +3 -2
- package/bin/lean/orphan-pr.test.mjs +8 -1
- package/bin/lean/pagegate.mjs +35 -12
- package/bin/lean/pagegate.test.mjs +39 -1
- package/bin/lean/preflight.mjs +35 -1
- package/bin/lean/preflight.test.mjs +27 -1
- package/bin/lean/prompts.mjs +2 -1
- package/bin/lean/reap.test.mjs +39 -0
- package/bin/lean/recovery.test.mjs +25 -0
- package/bin/lean/release-config.mjs +158 -0
- package/bin/lean/release-config.test.mjs +109 -0
- package/bin/lean/release-control.mjs +148 -0
- package/bin/lean/release-control.test.mjs +143 -0
- package/bin/lean/release-fence.mjs +50 -0
- package/bin/lean/release-fence.test.mjs +105 -0
- package/bin/lean/release-flakes.mjs +139 -0
- package/bin/lean/release-flakes.test.mjs +116 -0
- package/bin/lean/release-ledger.mjs +160 -0
- package/bin/lean/release-ledger.test.mjs +226 -0
- package/bin/lean/release-minutes.mjs +92 -0
- package/bin/lean/release-minutes.test.mjs +99 -0
- package/bin/lean/release-nightly.mjs +75 -0
- package/bin/lean/release-nightly.test.mjs +48 -0
- package/bin/lean/release-postmerge.mjs +8 -2
- package/bin/lean/release-review.e2e.test.mjs +1 -0
- package/bin/lean/release-review.mjs +54 -7
- package/bin/lean/release-review.test.mjs +76 -7
- package/bin/lean/release-unitmap.mjs +35 -0
- package/bin/lean/release-unitmap.test.mjs +41 -0
- package/bin/lean/release.mjs +177 -19
- package/bin/lean/release.test.mjs +40 -0
- package/bin/lean/render.mjs +3 -1
- package/bin/lean/run-issue-placement.test.mjs +82 -0
- package/bin/lean/sandbox-remote.mjs +16 -0
- package/bin/lean/schedd.mjs +1 -1
- package/bin/lean/seam.mjs +115 -0
- package/bin/lean/seam.test.mjs +118 -0
- package/bin/lean/selftest-journey.mjs +40 -2
- package/bin/lean/selftest-journey.test.mjs +43 -3
- package/bin/lean/statuscomment.mjs +168 -0
- package/bin/lean/statuscomment.test.mjs +133 -0
- package/bin/lean/ui-quality.mjs +57 -0
- package/bin/lean/ui-quality.test.mjs +55 -0
- package/bin/lean/visual-gate.test.mjs +63 -0
- package/bin/pool/agent.mjs +16 -2
- package/bin/pool/router.mjs +5 -1
- package/bin/review-staging.mjs +5 -3
- package/bin/stats/card.mjs +117 -0
- package/bin/stats/card.test.mjs +109 -0
- package/bin/stats/conformance-outcomes.test.mjs +2 -1
- package/bin/stats/depth.mjs +1 -1
- package/bin/stats/gh-retry.test.mjs +152 -0
- package/bin/stats/github-source.mjs +147 -14
- package/bin/stats/index.mjs +35 -2
- package/bin/stats/stats.test.mjs +31 -3
- package/bin/vendor/js-yaml/LICENSE +21 -0
- package/bin/vendor/js-yaml/PIN.md +7 -0
- package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
- package/commands/design-render-critique-loop.md +2 -0
- package/commands/design.md +2 -0
- package/commands/issue.md +1 -1
- package/commands/milestone.md +1 -1
- package/commands/review-pr-agents/frontend.md +1 -0
- package/commands/review-pr-staging.md +5 -0
- package/docs/CONFIG.md +75 -1
- package/docs/ISSUE-WATCH.md +7 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/docs/STATS.md +10 -0
- package/docs/design/visual-gate.md +25 -0
- package/docs/eval/adversarial-bench.md +2 -2
- package/docs/eval/corpus/adversarial-v1.json +3 -3
- package/docs/site/start-a-new-project.md +7 -0
- package/docs/spec/forge-protocol-v1.md +31 -0
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/scripts/acceptance-red-green.sh +15 -1
- package/scripts/acceptance-red-green.test.sh +12 -0
- package/scripts/bench-adversarial.mjs +4 -0
- package/scripts/bench-lightlane.mjs +4 -1
- package/scripts/bootstrap-create.mjs +8 -2
- package/scripts/ci-local.test.sh +3 -3
- package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
- package/scripts/plan-validate-live.mjs +9 -6
- package/scripts/review-prepare.sh +7 -1
- package/scripts/review-roster.sh +5 -2
- package/scripts/review-roster.test.sh +9 -0
- package/scripts/visual-gate.mjs +64 -0
- package/templates/bootstrap/technical-spike.md +17 -0
- package/templates/contracts/seam-check.mjs +236 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5338: the machine form of an interface. A spike/epic `Interfaces` row whose signature cell is an HTTP route
|
|
5
|
+
* (`POST /v1/search`), a function signature (`refund(job_id, amount_micro)`) or a typed payload / queue message
|
|
6
|
+
* (`queue research.jobs {query, device, city, uule}`) is parsed into a `seam` and becomes (1) a generated contract test
|
|
7
|
+
* that provider and consumer CI both run against the real source, nothing mocked, and (2) a deterministic precheck at
|
|
8
|
+
* lane review (`seamFailures`), so a mismatch is flagged when the lane that causes it is reviewed, not at release review.
|
|
9
|
+
* The checker itself is templates/contracts/seam-check.mjs (self-contained, copied next to the generated tests).
|
|
10
|
+
* Pure except where an injected read/list is given; no LLM, gh or git here.
|
|
11
|
+
*/
|
|
12
|
+
import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
|
|
13
|
+
import { checkSeam, authMode, anchorMatches } from "../../templates/contracts/seam-check.mjs";
|
|
14
|
+
|
|
15
|
+
export { checkSeam, authMode };
|
|
16
|
+
export const SEAM_KINDS = ["symbol", "route", "payload"];
|
|
17
|
+
const IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
18
|
+
const METHODS = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\/[^\s`]*)/i;
|
|
19
|
+
|
|
20
|
+
const unTick = (s) => String(s ?? "").trim().replace(/^`+|`+$/g, "").trim();
|
|
21
|
+
|
|
22
|
+
function topSplit(s) {
|
|
23
|
+
const out = []; let depth = 0, cur = "";
|
|
24
|
+
for (const c of s) {
|
|
25
|
+
if ("([{<".includes(c)) depth++; else if (")]}>".includes(c)) depth = Math.max(0, depth - 1);
|
|
26
|
+
if (c === "," && depth === 0) { out.push(cur); cur = ""; } else cur += c;
|
|
27
|
+
}
|
|
28
|
+
if (cur.trim()) out.push(cur);
|
|
29
|
+
return out.map((x) => x.trim()).filter(Boolean);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** {kind, symbol|route|payload} for a signature cell with a machine form, else null. */
|
|
33
|
+
export function parseSeamForm(signature) {
|
|
34
|
+
const t = unTick(signature);
|
|
35
|
+
const r = METHODS.exec(t);
|
|
36
|
+
if (r) return { kind: "route", route: { method: r[1].toUpperCase(), path: r[2].replace(/[.,;]+$/, "") } };
|
|
37
|
+
const f = /^(?:(?:async|def|function|fn)\s+)?([A-Za-z_$][\w$.]*)\s*\(([^)]*)\)/.exec(t);
|
|
38
|
+
if (f) {
|
|
39
|
+
const name = f[1].split(".").at(-1);
|
|
40
|
+
const params = [];
|
|
41
|
+
for (const raw of topSplit(f[2])) {
|
|
42
|
+
if (raw === "*" || raw === "/") continue;
|
|
43
|
+
const variadic = /^(\*\*?|\.\.\.)/.test(raw);
|
|
44
|
+
const m = /^([A-Za-z_$][\w$]*)(\?)?/.exec(raw.replace(/^(\*\*?|\.\.\.)/, ""));
|
|
45
|
+
if (!m) return null;
|
|
46
|
+
params.push({ name: m[1], optional: Boolean(m[2]) || /(^|[^=!<>])=(?!=)/.test(raw) || variadic, variadic });
|
|
47
|
+
}
|
|
48
|
+
if (IDENT.test(name)) return { kind: "symbol", symbol: { name, params } };
|
|
49
|
+
}
|
|
50
|
+
const p = /^(?:(?:queue|topic|message|payload|event)\s+)?(?:[\w.:\-/]+\s+)?\{([^}]*)\}/i.exec(t);
|
|
51
|
+
if (p) {
|
|
52
|
+
const fields = [...new Set(topSplit(p[1]).map((x) => /^["']?([A-Za-z_$][\w$]*)/.exec(x)?.[1]).filter(Boolean))];
|
|
53
|
+
if (fields.length) return { kind: "payload", payload: { fields } };
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Anchor cell tokens: `provider:path` / `consumer:path` set the side; a bare path is governed but on neither side. {all, provider, consumer}. */
|
|
59
|
+
export function roleAnchors(tokens) {
|
|
60
|
+
const all = [], provider = [], consumer = [];
|
|
61
|
+
for (const raw of tokens ?? []) {
|
|
62
|
+
const m = /^(provider|consumer)\s*:\s*(.+)$/i.exec(String(raw).trim());
|
|
63
|
+
const path = (m ? m[2] : String(raw)).trim();
|
|
64
|
+
if (!path) continue;
|
|
65
|
+
all.push(path);
|
|
66
|
+
if (m?.[1].toLowerCase() === "provider") provider.push(path);
|
|
67
|
+
if (m?.[1].toLowerCase() === "consumer") consumer.push(path);
|
|
68
|
+
}
|
|
69
|
+
return { all: [...new Set(all)], provider: [...new Set(provider)], consumer: [...new Set(consumer)] };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The stored seam of a decision from its parsed form and role anchors; null when no form or a side is undeclared. */
|
|
73
|
+
export function buildSeam(form, roles, auth) {
|
|
74
|
+
if (!form || !roles?.provider?.length || !roles?.consumer?.length) return null;
|
|
75
|
+
return { ...form, auth: String(auth ?? "").slice(0, 160), provider: roles.provider, consumer: roles.consumer };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The contract the checker and the generated test take, from a decision record with a `seam`. */
|
|
79
|
+
export const seamContract = (rec) => ({ v: 1, id: rec.id, kind: rec.seam.kind, boundary: String(rec.choice ?? "").slice(0, 160), auth: rec.seam.auth ?? "", [rec.seam.kind]: rec.seam[rec.seam.kind], provider: rec.seam.provider, consumer: rec.seam.consumer });
|
|
80
|
+
|
|
81
|
+
/** Source of `contracts/<id>.contract.test.mjs`: one node:test file that reads both sides' real source. */
|
|
82
|
+
export function renderSeamTest(contract) {
|
|
83
|
+
const lit = JSON.stringify(contract, null, 2).replace(/</g, "\\u003c");
|
|
84
|
+
return `// Generated by \`npx forgedock interfaces contract\` for interface decision ${contract.id} (forgedock #5338).
|
|
85
|
+
// Both sides of the seam run this file (\`node --test contracts/*.contract.test.mjs\`); it reads the real source and mocks nothing.
|
|
86
|
+
// Changing the interface means a \`supersedes\` decision and regenerating this file, not editing it by hand.
|
|
87
|
+
import { test } from "node:test";
|
|
88
|
+
import assert from "node:assert/strict";
|
|
89
|
+
import { fileURLToPath } from "node:url";
|
|
90
|
+
import { checkSeamAt, formatFindings } from "./seam-check.mjs";
|
|
91
|
+
|
|
92
|
+
const contract = ${lit};
|
|
93
|
+
|
|
94
|
+
test(\`interface \${contract.id}: \${contract.boundary}\`, () => {
|
|
95
|
+
const r = checkSeamAt(contract, fileURLToPath(new URL("../", import.meta.url)));
|
|
96
|
+
assert.equal(r.unchecked, undefined, r.unchecked);
|
|
97
|
+
assert.equal(r.findings.length, 0, \`the provider and consumer disagree on \${contract.id}:\\n\${formatFindings(r.findings)}\`);
|
|
98
|
+
});
|
|
99
|
+
`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Lane-review failures: for every active decision with a `seam` whose anchors a changed file touches (and that the lane
|
|
104
|
+
* does not supersede), run the checker on the lane's worktree. `read(path)`/`list()` give the worktree files. Pure.
|
|
105
|
+
*/
|
|
106
|
+
export function seamFailures({ records, changedFiles, read, list, superseded = [] }) {
|
|
107
|
+
const gone = new Set(superseded), out = [];
|
|
108
|
+
for (const rec of records ?? []) {
|
|
109
|
+
if (!rec?.seam || rec.status === "superseded" || gone.has(rec.id)) continue;
|
|
110
|
+
if (!(changedFiles ?? []).some((f) => (rec.anchors ?? []).some((a) => anchorMatches(a, f)))) continue;
|
|
111
|
+
const r = checkSeam(seamContract(rec), { read, list });
|
|
112
|
+
for (const f of r.findings) out.push({ code: OUTCOME_CODES.CONFORMANCE_PRESERVE_VIOLATED, kind: "interface_seam", detail: `decision ${rec.id} (${rec.choice.slice(0, 80)}): ${f.side}${f.file ? ` ${f.file}${f.line ? `:${f.line}` : ""}` : ""}: ${f.detail}; amend {kind:"decision", decision:{choice, anchors, supersedes:"${rec.id}"}, why} when the interface really changes` });
|
|
113
|
+
}
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
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 { spawnSync } from "node:child_process";
|
|
6
|
+
import { mkdirSync, writeFileSync, readFileSync } from "node:fs";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
8
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
|
+
import { parseSeamForm, roleAnchors, buildSeam, seamContract, renderSeamTest, seamFailures, checkSeam, authMode } from "./seam.mjs";
|
|
10
|
+
import { anchorMatches } from "./decisions.mjs";
|
|
11
|
+
import { anchorMatches as checkerAnchorMatches } from "../../templates/contracts/seam-check.mjs";
|
|
12
|
+
import { normaliseDecision } from "./decisions.mjs";
|
|
13
|
+
|
|
14
|
+
const io = (files) => ({ list: () => Object.keys(files), read: (p) => files[p] });
|
|
15
|
+
const contract = (o) => ({ v: 1, id: "i1-1", boundary: "b", auth: "", ...o });
|
|
16
|
+
|
|
17
|
+
describe("seam forms (#5338)", () => {
|
|
18
|
+
it("parses a route, a function signature and a typed payload; prose has no machine form", () => {
|
|
19
|
+
assert.deepEqual(parseSeamForm("`POST /v1/search/{id}`"), { kind: "route", route: { method: "POST", path: "/v1/search/{id}" } });
|
|
20
|
+
assert.deepEqual(parseSeamForm("refund(job_id: str, amount_micro: int, *, reason=None)").symbol, { name: "refund", params: [{ name: "job_id", optional: false, variadic: false }, { name: "amount_micro", optional: false, variadic: false }, { name: "reason", optional: true, variadic: false }] });
|
|
21
|
+
assert.equal(parseSeamForm("billing.refund(a)").symbol.name, "refund");
|
|
22
|
+
assert.deepEqual(parseSeamForm("queue research.jobs {query, device?: string, city}").payload.fields, ["query", "device", "city"]);
|
|
23
|
+
assert.equal(parseSeamForm("a JSON document with the results"), null);
|
|
24
|
+
});
|
|
25
|
+
it("roles: provider:/consumer: prefixes set the side, a bare anchor is governed but on neither; a seam needs both sides", () => {
|
|
26
|
+
const r = roleAnchors(["provider:worker/", "consumer:api/", "shared/"]);
|
|
27
|
+
assert.deepEqual(r.all, ["worker/", "api/", "shared/"]);
|
|
28
|
+
assert.deepEqual(r.provider, ["worker/"]);
|
|
29
|
+
assert.deepEqual(r.consumer, ["api/"]);
|
|
30
|
+
assert.equal(buildSeam(parseSeamForm("POST /x"), roleAnchors(["provider:a/"]), "k"), null);
|
|
31
|
+
assert.equal(buildSeam(null, r, "k"), null);
|
|
32
|
+
assert.equal(buildSeam(parseSeamForm("POST /x"), r, "k").kind, "route");
|
|
33
|
+
});
|
|
34
|
+
it("the checker's anchor rule is the register's (parity)", () => {
|
|
35
|
+
for (const [a, p] of [["src/a.js", "src/a.js"], ["src/a/", "src/a/b.js"], ["src/**", "src/a/b.js"], ["src/*.js", "src/a/b.js"], ["src/a", "src/a/b.js"], ["./x/", "x/y"], ["", "x"]]) assert.equal(checkerAnchorMatches(a, p), anchorMatches(a, p), `${a} ${p}`);
|
|
36
|
+
});
|
|
37
|
+
it("auth mode: an API key with a negated session is api-key; a session is not", () => {
|
|
38
|
+
assert.equal(authMode("API key only, no session cookie"), "api-key");
|
|
39
|
+
assert.equal(authMode("x-api-key header"), "api-key");
|
|
40
|
+
assert.equal(authMode("session cookie or API key"), "session");
|
|
41
|
+
assert.equal(authMode("internal"), "other");
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
describe("seam checker: the three mismatches the audit found (#5338)", () => {
|
|
46
|
+
const refund = contract({ kind: "symbol", symbol: parseSeamForm("refund(job_id, amount_micro)").symbol, provider: ["worker/"], consumer: ["api/"] });
|
|
47
|
+
it("symbol: a refund primitive with the wrong signature, and a call that does not fit, are findings; a matching pair is clean", () => {
|
|
48
|
+
const bad = io({ "worker/refund.py": "async def refund(self, job_id: str) -> None:\n ...\n", "api/research.py": "await refund(job.id, amount_micro=5)\nawait refund(job.id, 5, 6)\n" });
|
|
49
|
+
const r = checkSeam(refund, bad);
|
|
50
|
+
assert.deepEqual(r.findings.map((f) => [f.side, f.file, f.line]), [["provider", "worker/refund.py", 1], ["consumer", "api/research.py", 2]]);
|
|
51
|
+
assert.match(r.findings[0].detail, /TypeError/);
|
|
52
|
+
assert.match(r.findings[1].detail, /too many arguments/);
|
|
53
|
+
const good = io({ "worker/refund.py": "async def refund(job_id: str, amount_micro: int, *, reason=None):\n ...\n", "api/research.py": "await refund(job.id, amount_micro=5)\nawait refund(job.id, 7)\n", "api/other.py": "refund(**kw)\n" });
|
|
54
|
+
assert.deepEqual(checkSeam(refund, good).findings, []);
|
|
55
|
+
assert.match(checkSeam(refund, io({ "worker/x.py": "pass", "api/y.py": "pass" })).findings[0].detail, /no definition of refund/);
|
|
56
|
+
});
|
|
57
|
+
it("symbol: TypeScript functions, arrow bindings and methods are definitions", () => {
|
|
58
|
+
const c = contract({ kind: "symbol", symbol: parseSeamForm("charge(id, cents)").symbol, provider: ["lib/"], consumer: ["app/"] });
|
|
59
|
+
for (const def of ["export async function charge(id: string, cents: number) {}", "export const charge = async (id: string, cents: number) => {}", "class B {\n async charge(id: string, cents: number): Promise<void> {}\n}"]) {
|
|
60
|
+
assert.deepEqual(checkSeam(c, io({ "lib/a.ts": def, "app/b.ts": "await charge(a, 3)" })).findings, [], def);
|
|
61
|
+
}
|
|
62
|
+
assert.equal(checkSeam(c, io({ "lib/a.ts": "export function charge(id: string) {}", "app/b.ts": "charge(a, 3)" })).findings.length, 1);
|
|
63
|
+
});
|
|
64
|
+
it("route: a web proxy that forwards the session cookie / JWT to an API-key-only route is flagged, one that sends the key is clean", () => {
|
|
65
|
+
const route = contract({ kind: "route", auth: "API key only, no session cookie", route: { method: "POST", path: "/v1/search" }, provider: ["api/"], consumer: ["web/"] });
|
|
66
|
+
const api = { "api/routes.py": "@router.post('/v1/search')\nasync def search(): ...\n" };
|
|
67
|
+
const cookie = checkSeam(route, io({ ...api, "web/app/api/search/route.ts": "export async function POST(req) {\n return fetch(`${API}/v1/search`, { headers: { cookie: req.headers.get('cookie') } });\n}" }));
|
|
68
|
+
assert.deepEqual(cookie.findings.map((f) => f.side), ["consumer", "consumer"]);
|
|
69
|
+
assert.match(cookie.findings[0].detail, /Cookie header/);
|
|
70
|
+
assert.match(cookie.findings[1].detail, /never sends one/);
|
|
71
|
+
const jwt = checkSeam(route, io({ ...api, "web/lib/s.ts": "const session = await getServerSession();\nfetch(`${API}/v1/search`, { headers: { Authorization: `Bearer ${session.accessToken}` } })" }));
|
|
72
|
+
assert.ok(jwt.findings.some((f) => /session token|session JWT/.test(f.detail)));
|
|
73
|
+
assert.deepEqual(checkSeam(route, io({ ...api, "web/lib/s.ts": "fetch(`${API}/v1/search`, { headers: { 'x-api-key': process.env.ALTERLAB_API_KEY } })" })).findings, []);
|
|
74
|
+
assert.match(checkSeam(route, io({ "api/other.py": "pass", "web/x.ts": "pass" })).findings[0].detail, /no handler for POST \/v1\/search/);
|
|
75
|
+
const next = checkSeam(contract({ ...route, route: { method: "GET", path: "/v1/jobs/{id}" } }), io({ "api/v1/jobs/[id]/route.ts": "export async function GET() {}", "web/a.ts": "x" }));
|
|
76
|
+
assert.deepEqual(next.findings, []);
|
|
77
|
+
});
|
|
78
|
+
it("payload: fields the API accepts and the worker handler drops are flagged on the side that drops them", () => {
|
|
79
|
+
const p = contract({ kind: "payload", payload: parseSeamForm("queue research.jobs {query, device, city, uule}").payload, provider: ["worker/"], consumer: ["api/"] });
|
|
80
|
+
const r = checkSeam(p, io({ "worker/handler.py": "def handle(job):\n return job['query'], job['device']\n", "api/search.py": "enqueue({'query': q, 'device': d, 'city': c, 'uule': u})\n" }));
|
|
81
|
+
assert.deepEqual(r.findings.map((f) => [f.side, /"(\w+)"/.exec(f.detail)[1]]), [["provider", "city"], ["provider", "uule"]]);
|
|
82
|
+
assert.deepEqual(checkSeam(p, io({ "worker/handler.py": "job['query'] job['device'] job['city'] job['uule']", "api/search.py": "query device city uule" })).findings, []);
|
|
83
|
+
});
|
|
84
|
+
it("a side with no source files is unchecked, never a silent pass", () => {
|
|
85
|
+
assert.match(checkSeam(refund, io({ "worker/refund.py": "def refund(job_id, amount_micro): ..." })).unchecked, /consumer anchors/);
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe("seamFailures at lane review and the generated contract test (#5338)", () => {
|
|
90
|
+
const rec = normaliseDecision({ id: "i9-1", choice: "Interface api -> worker: refund(job_id, amount_micro)", anchors: ["worker/", "api/"], issue: 9, seam: { kind: "symbol", auth: "internal", symbol: parseSeamForm("refund(job_id, amount_micro)").symbol, provider: ["worker/"], consumer: ["api/"] } });
|
|
91
|
+
const files = { "worker/refund.py": "def refund(job_id): ...", "api/r.py": "refund(a, b)", "docs/a.md": "x" };
|
|
92
|
+
it("flags a mismatch only when the lane touches the anchors, and not for a superseded record", () => {
|
|
93
|
+
assert.ok(rec.seam);
|
|
94
|
+
const f = seamFailures({ records: [rec], changedFiles: ["worker/refund.py"], ...io(files) });
|
|
95
|
+
assert.equal(f.length, 1);
|
|
96
|
+
assert.equal(f[0].kind, "interface_seam");
|
|
97
|
+
assert.equal(f[0].code, "conformance.preserve_violated");
|
|
98
|
+
assert.match(f[0].detail, /i9-1.*worker\/refund\.py:1.*supersedes:"i9-1"/);
|
|
99
|
+
assert.deepEqual(seamFailures({ records: [rec], changedFiles: ["docs/a.md"], ...io(files) }), []);
|
|
100
|
+
assert.deepEqual(seamFailures({ records: [rec], changedFiles: ["worker/refund.py"], superseded: ["i9-1"], ...io(files) }), []);
|
|
101
|
+
assert.deepEqual(seamFailures({ records: [{ ...rec, status: "superseded" }], changedFiles: ["worker/refund.py"], ...io(files) }), []);
|
|
102
|
+
});
|
|
103
|
+
it("the generated test file runs under node --test and fails for a broken seam, passes for a sound one (nothing mocked)", () => {
|
|
104
|
+
const root = tmpDir("seam-");
|
|
105
|
+
const write = (rel, text) => { mkdirSync(dirname(join(root, rel)), { recursive: true }); writeFileSync(join(root, rel), text); };
|
|
106
|
+
spawnSync("git", ["init", "-q"], { cwd: root });
|
|
107
|
+
write("contracts/seam-check.mjs", readFileSync(new URL("../../templates/contracts/seam-check.mjs", import.meta.url), "utf8"));
|
|
108
|
+
write("contracts/i9-1.contract.test.mjs", renderSeamTest(seamContract(rec)));
|
|
109
|
+
for (const [rel, t] of Object.entries(files)) write(rel, t);
|
|
110
|
+
const run = () => spawnSync(process.execPath, ["--test", "contracts/i9-1.contract.test.mjs"], { cwd: root, encoding: "utf8", env: Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== "NODE_TEST_CONTEXT")) });
|
|
111
|
+
const red = run();
|
|
112
|
+
assert.notEqual(red.status, 0);
|
|
113
|
+
assert.match(red.stdout + red.stderr, /provider and consumer disagree on i9-1/);
|
|
114
|
+
write("worker/refund.py", "def refund(job_id, amount_micro): ...");
|
|
115
|
+
const green = run();
|
|
116
|
+
assert.equal(green.status, 0, green.stdout + green.stderr);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
@@ -23,8 +23,16 @@ export const CASES = [
|
|
|
23
23
|
{ name: "help", args: ["help"], file: "help.txt" },
|
|
24
24
|
{ name: "doctor", args: ["doctor"], file: "doctor.txt" },
|
|
25
25
|
{ name: "errors", args: ["nosuchcommand"], file: "errors.txt" },
|
|
26
|
+
{ name: "no-splash", args: ["--no-splash"], file: "no-splash.txt" },
|
|
26
27
|
];
|
|
27
28
|
|
|
29
|
+
// The startup splash lines `npx forgedock` prints (#5312, bin/splash-install.mjs) and doctor's state line (#5532).
|
|
30
|
+
const SPLASH_NO_CLAUDE = /startup splash skipped: claude CLI not found/;
|
|
31
|
+
const SPLASH_OPTED_OUT = /startup splash skipped \(--no-splash\)/;
|
|
32
|
+
const SPLASH_INSTALLED = /startup splash (installed|already installed)\b/;
|
|
33
|
+
const DOCTOR_SPLASH = (state) => new RegExp(`Startup splash\\s+${state}\\b`);
|
|
34
|
+
const splashPlugins = (settings) => { try { return Object.entries(JSON.parse(settings).enabledPlugins ?? {}).filter(([k]) => k.startsWith("forgedock-splash@")); } catch { return []; } };
|
|
35
|
+
|
|
28
36
|
// Success wording that must not appear while node/git are all a clean machine has (the false banner of 2026-11-10).
|
|
29
37
|
const FALSE_SUCCESS = /(all checks passed|you'?re all set|setup complete|✔\s+(Claude Code|gh\b|GitHub CLI)\b)/i;
|
|
30
38
|
const JARGON = /\b(ENOENT|EACCES|ERR_[A-Z_]+|TypeError|ReferenceError|SyntaxError|undefined|\[object Object\])\b|\n\s+at \S+ \(/;
|
|
@@ -56,6 +64,14 @@ export function assertStage1(results) {
|
|
|
56
64
|
if (doctor && doctor.code === 0) bad.push(["doctor", "doctor exits 0 on a machine without gh and Claude Code"]);
|
|
57
65
|
if (doctor && !/claude/i.test(doctor.output)) bad.push(["doctor", "doctor output never names Claude Code"]);
|
|
58
66
|
if (doctor && !/\bgh\b|github cli/i.test(doctor.output)) bad.push(["doctor", "doctor output never names the gh CLI"]);
|
|
67
|
+
const banner = results.cases.banner, nosplash = results.cases["no-splash"];
|
|
68
|
+
// When setup stops at the not-ready screen (exit 1) it never reaches the splash step: only an install line is wrong then.
|
|
69
|
+
if (banner && SPLASH_INSTALLED.test(banner.output)) bad.push(["splash", "splash reported installed on a machine without the claude CLI"]);
|
|
70
|
+
if (banner?.code === 0 && !SPLASH_NO_CLAUDE.test(banner.output)) bad.push(["splash", "setup without the claude CLI never printed the splash skip line"]);
|
|
71
|
+
if (nosplash && SPLASH_INSTALLED.test(nosplash.output)) bad.push(["splash", "--no-splash still installed the splash"]);
|
|
72
|
+
if (nosplash?.code === 0 && !SPLASH_OPTED_OUT.test(nosplash.output)) bad.push(["splash", "--no-splash did not report the skip"]);
|
|
73
|
+
if (nosplash && nosplash.code !== 0 && nosplash.code !== banner?.code) bad.push(["splash", `setup with --no-splash exited ${nosplash.code}, setup without it ${banner?.code}`]);
|
|
74
|
+
if (doctor && !DOCTOR_SPLASH("not installed").test(doctor.output)) bad.push(["splash", "doctor does not report the splash state as not installed"]);
|
|
59
75
|
const errs = results.cases.errors;
|
|
60
76
|
if (errs && errs.code === 0) bad.push(["errors", "an unknown command exits 0"]);
|
|
61
77
|
for (const [path, content] of Object.entries(results.files)) {
|
|
@@ -114,6 +130,7 @@ export async function stage2(ctx) {
|
|
|
114
130
|
};
|
|
115
131
|
await run("setup", ["demo", dir, "--repo", repo]);
|
|
116
132
|
await run("doctor", ["doctor"]);
|
|
133
|
+
await splashStage(ctx, dir);
|
|
117
134
|
await run("first-merge", ["demo", dir, "--repo", repo, "--run"]);
|
|
118
135
|
const prs = JSON.parse(await io.gh(["pr", "list", "-R", repo, "--state", "merged", "--json", "number,mergedAt", "--limit", "20"]));
|
|
119
136
|
const merged = prs.map((p) => Date.parse(p.mergedAt)).filter((t) => t >= start).sort((a, b) => a - b)[0];
|
|
@@ -121,8 +138,28 @@ export async function stage2(ctx) {
|
|
|
121
138
|
ctx.ttfmMs = merged - start;
|
|
122
139
|
}
|
|
123
140
|
|
|
141
|
+
/** Setup with claude available installs forgedock-splash at user scope and doctor reports it; --no-splash installs nothing. Each run gets a throwaway HOME. */
|
|
142
|
+
async function splashStage(ctx, dir) {
|
|
143
|
+
const { io } = ctx;
|
|
144
|
+
const go = async (args, home) => {
|
|
145
|
+
const r = await io.cli(args, { cwd: dir, env: { HOME: home, CLAUDE_CONFIG_DIR: "" } });
|
|
146
|
+
return { ...r, text: `${r.stdout}\n${r.stderr}`, settings: await io.readFile(join(home, ".claude", "settings.json")) };
|
|
147
|
+
};
|
|
148
|
+
const home = await io.mkdir(), bare = await io.mkdir();
|
|
149
|
+
ctx.homes.push(home, bare);
|
|
150
|
+
const on = await go([], home);
|
|
151
|
+
if (!SPLASH_INSTALLED.test(on.text)) fail("splash", `setup with claude available did not report the splash installed: ${scrub(on.text).slice(0, 200)}`);
|
|
152
|
+
if (!splashPlugins(on.settings).some(([, v]) => v === true)) fail("splash", "forgedock-splash is not enabled at user scope in settings.json after setup");
|
|
153
|
+
const doc = await io.cli(["doctor"], { cwd: dir, env: { HOME: home, CLAUDE_CONFIG_DIR: "" } });
|
|
154
|
+
if (!DOCTOR_SPLASH("installed").test(`${doc.stdout}\n${doc.stderr}`)) fail("splash", "doctor does not report the splash as installed");
|
|
155
|
+
const off = await go(["--no-splash"], bare);
|
|
156
|
+
if (!SPLASH_OPTED_OUT.test(off.text)) fail("splash", "--no-splash did not report the skip");
|
|
157
|
+
if (SPLASH_INSTALLED.test(off.text) || splashPlugins(off.settings).length) fail("splash", "--no-splash still installed the splash");
|
|
158
|
+
}
|
|
159
|
+
|
|
124
160
|
async function cleanup2(ctx, errors) {
|
|
125
161
|
const { io, repo } = ctx;
|
|
162
|
+
for (const h of ctx.homes) try { await io.rm(h); } catch (e) { errors.push(`remove ${h}: ${String(e.message ?? e).slice(0, 120)}`); }
|
|
126
163
|
if (ctx.dir) try { await io.rm(ctx.dir); } catch (e) { errors.push(`remove ${ctx.dir}: ${String(e.message ?? e).slice(0, 120)}`); }
|
|
127
164
|
if (ctx.startedStage2) {
|
|
128
165
|
try {
|
|
@@ -134,7 +171,7 @@ async function cleanup2(ctx, errors) {
|
|
|
134
171
|
|
|
135
172
|
/** Run both stages; the first failure stops them, cleanup always runs. */
|
|
136
173
|
export async function runNewUserJourney({ repo, io, snapshotDir = SNAPSHOT_DIR, update = false }) {
|
|
137
|
-
const ctx = { io, repo, snapshotDir, update, notes: [], prompts: [], ttfmMs: null, dir: null, startedStage2: null };
|
|
174
|
+
const ctx = { io, repo, snapshotDir, update, notes: [], prompts: [], homes: [], ttfmMs: null, dir: null, startedStage2: null };
|
|
138
175
|
let out = { ok: true, step: null, message: null };
|
|
139
176
|
try {
|
|
140
177
|
await stage1(ctx);
|
|
@@ -195,7 +232,8 @@ export function realJourneyIo(env = process.env, { docker } = {}) {
|
|
|
195
232
|
gh: async (args) => { const r = sh("gh", args); if (r.status !== 0) throw new Error(r.stderr.trim() || `gh exited ${r.status}`); return r.stdout; },
|
|
196
233
|
mkdir: async () => mkdtempSync(join(scratch, "demo-")),
|
|
197
234
|
rm: async (d) => rmSync(d, { recursive: true, force: true }),
|
|
198
|
-
|
|
235
|
+
readFile: async (p) => { try { return readFileSync(p, "utf8"); } catch { return null; } },
|
|
236
|
+
cli: async (args, { cwd, env: extra } = {}) => { const r = sh(process.execPath, [cliPath, ...args], { cwd, env: { ...env, ...extra }, timeout: 45 * 60 * 1000, input: "" }); return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" }; },
|
|
199
237
|
dispose: () => rmSync(scratch, { recursive: true, force: true }),
|
|
200
238
|
};
|
|
201
239
|
}
|
|
@@ -9,19 +9,22 @@ import { selftestFromCli } from "./selftest-live.mjs";
|
|
|
9
9
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
10
10
|
|
|
11
11
|
const GOOD = {
|
|
12
|
-
banner: { code: 0, output: "ForgeDock v1.2.3\n ✖ Claude Code not found\n" },
|
|
12
|
+
banner: { code: 0, output: "ForgeDock v1.2.3\n ✖ Claude Code not found\n ! startup splash skipped: claude CLI not found re-run npx forgedock after installing Claude Code\n" },
|
|
13
13
|
help: { code: 0, output: "Usage: forgedock <command>\n" },
|
|
14
|
-
doctor: { code: 1, output: " ✗ gh CLI\n ✗ Claude Code settings\n" },
|
|
14
|
+
doctor: { code: 1, output: " ✗ gh CLI\n ✗ Claude Code settings\n ✔ Startup splash not installed (forgedock-splash)\n" },
|
|
15
15
|
errors: { code: 1, output: "Unknown command: nosuchcommand\n" },
|
|
16
|
+
"no-splash": { code: 0, output: " ! startup splash skipped (--no-splash)\n" },
|
|
16
17
|
};
|
|
17
18
|
const stage1Io = (over = {}, files = { "./forge.yaml": 'owner: "acme"\n' }) => ({
|
|
18
19
|
pack: async () => "/x/f.tgz",
|
|
19
20
|
clean: async (_t, args) => { const c = CASES.find((k) => k.args.join(" ") === args.join(" ")); return { ...(over[c.name] ?? GOOD[c.name]), files: c.name === "banner" ? files : {} }; },
|
|
20
21
|
});
|
|
21
22
|
const now = (() => { let t = 1000; return () => (t += 10); })();
|
|
23
|
+
let lastNoSplash = false;
|
|
22
24
|
const io2 = (over = {}) => ({
|
|
23
25
|
now, ghAuthed: async () => true, claudeAvailable: async () => true, mkdir: async () => "/d", rm: async () => {},
|
|
24
|
-
|
|
26
|
+
readFile: async () => (lastNoSplash ? null : JSON.stringify({ enabledPlugins: { "forgedock-splash@forgedock-local": true } })),
|
|
27
|
+
cli: async (args) => (lastNoSplash = args.includes("--no-splash"), { code: 0, stdout: args.includes("--run") ? "Proceed? [y/N]\nmerged\n" : args[0] === "doctor" ? " ✔ Startup splash installed (forgedock-splash)\n" : args.includes("--no-splash") ? " ! startup splash skipped (--no-splash)\n" : " ✔ startup splash installed turn off: x\n", stderr: "" }),
|
|
25
28
|
gh: async (a) => (a[0] === "pr" ? JSON.stringify([{ number: 1, mergedAt: new Date(5000).toISOString() }]) : "[]"),
|
|
26
29
|
...over,
|
|
27
30
|
});
|
|
@@ -53,6 +56,43 @@ describe("assertStage1 (the 2026-11-10 regression classes)", () => {
|
|
|
53
56
|
});
|
|
54
57
|
});
|
|
55
58
|
|
|
59
|
+
describe("splash assertions (#5312 R17)", () => {
|
|
60
|
+
const ok = { cases: GOOD, files: {} };
|
|
61
|
+
const msgs = (cases) => assertStage1({ ...ok, cases: { ...GOOD, ...cases } }).map((b) => b[1]).join("|");
|
|
62
|
+
it("stage 1 passes with the skip lines and fails when they are missing or an install is reported", () => {
|
|
63
|
+
assert.deepEqual(assertStage1(ok), []);
|
|
64
|
+
assert.match(msgs({ banner: { code: 0, output: "ForgeDock\n" } }), /never printed the splash skip line/);
|
|
65
|
+
assert.match(msgs({ banner: { code: 0, output: "startup splash skipped: claude CLI not found\nstartup splash installed" } }), /reported installed/);
|
|
66
|
+
assert.match(msgs({ "no-splash": { code: 0, output: "nothing" } }), /did not report the skip/);
|
|
67
|
+
assert.match(msgs({ "no-splash": { code: 0, output: "startup splash skipped (--no-splash)\nstartup splash installed" } }), /still installed/);
|
|
68
|
+
assert.deepEqual(msgs({ banner: { code: 1, output: "Not ready yet" }, "no-splash": { code: 1, output: "Not ready yet" } }), "");
|
|
69
|
+
assert.match(msgs({ banner: { code: 1, output: "Not ready yet" }, "no-splash": { code: 0, output: "x" } }), /exited 0|did not report/);
|
|
70
|
+
assert.match(msgs({ doctor: { code: 1, output: "gh claude" } }), /splash state/);
|
|
71
|
+
});
|
|
72
|
+
it("stage 2 asserts the install at user scope, doctor's state and the --no-splash skip", async () => {
|
|
73
|
+
const homes = [], envs = [];
|
|
74
|
+
const base = io2({ mkdir: async () => { const h = `/h${homes.length}`; homes.push(h); return h; }, cli: async (args, o = {}) => { envs.push(o.env?.HOME); return io2().cli(args, o); } });
|
|
75
|
+
let r = await run({ ...stage1Io(), ...base });
|
|
76
|
+
assert.equal(r.ok, true, r.message);
|
|
77
|
+
assert.ok(envs.includes("/h1") && envs.includes("/h2"), "setup runs under throwaway homes");
|
|
78
|
+
const bad = async (over) => run({ ...stage1Io(), ...io2(over) });
|
|
79
|
+
r = await bad({ readFile: async () => JSON.stringify({ enabledPlugins: {} }) });
|
|
80
|
+
assert.equal(r.step, "splash");
|
|
81
|
+
assert.match(r.message, /not enabled at user scope/);
|
|
82
|
+
r = await bad({ cli: async (a) => ({ code: 0, stdout: a[0] === "doctor" ? "nothing" : "startup splash installed", stderr: "" }) });
|
|
83
|
+
assert.match(r.message, /doctor does not report/);
|
|
84
|
+
r = await bad({ cli: async (a) => ({ code: 0, stdout: a.includes("--no-splash") ? "startup splash installed" : a[0] === "doctor" ? "Startup splash installed" : "startup splash installed", stderr: "" }) });
|
|
85
|
+
assert.match(r.message, /--no-splash did not report/);
|
|
86
|
+
r = await bad({ cli: async () => ({ code: 0, stdout: "ok", stderr: "" }) });
|
|
87
|
+
assert.match(r.message, /did not report the splash installed/);
|
|
88
|
+
});
|
|
89
|
+
it("removes the throwaway homes", async () => {
|
|
90
|
+
const removed = [];
|
|
91
|
+
await run({ ...stage1Io(), ...io2({ rm: async (d) => removed.push(d) }) });
|
|
92
|
+
assert.ok(removed.length >= 3);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
56
96
|
describe("snapshots", () => {
|
|
57
97
|
it("a missing snapshot fails naming the update flag; a changed one names the line", () => {
|
|
58
98
|
const dir = tmpDir("jt-");
|
|
@@ -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
|
+
}
|