forgedock 1.61.1 → 1.62.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 (134) hide show
  1. package/bin/config-schema.mjs +10 -1
  2. package/bin/engine/outcome-codes.mjs +4 -0
  3. package/bin/engine-cli.mjs +160 -18
  4. package/bin/env/env.mjs +6 -4
  5. package/bin/forge-home-check.mjs +91 -0
  6. package/bin/forgedock.mjs +50 -7
  7. package/bin/gc.mjs +2 -0
  8. package/bin/hooks/pre-tool-use.mjs +4 -0
  9. package/bin/journey.mjs +55 -5
  10. package/bin/lean/admission.mjs +16 -5
  11. package/bin/lean/batch-health.mjs +55 -16
  12. package/bin/lean/batch-health.test.mjs +67 -1
  13. package/bin/lean/batch.mjs +8 -0
  14. package/bin/lean/batch.test.mjs +5 -0
  15. package/bin/lean/ceiling.mjs +20 -0
  16. package/bin/lean/ceiling.test.mjs +33 -2
  17. package/bin/lean/ci-gate.mjs +240 -0
  18. package/bin/lean/ci-gate.test.mjs +227 -0
  19. package/bin/lean/ci-precheck.mjs +178 -0
  20. package/bin/lean/ci-precheck.test.mjs +149 -0
  21. package/bin/lean/conformance.mjs +118 -20
  22. package/bin/lean/conformance.test.mjs +193 -3
  23. package/bin/lean/context.test.mjs +7 -6
  24. package/bin/lean/dag.mjs +128 -0
  25. package/bin/lean/dag.test.mjs +131 -0
  26. package/bin/lean/decisions.mjs +5 -4
  27. package/bin/lean/decisions.test.mjs +11 -0
  28. package/bin/lean/delguard.mjs +84 -0
  29. package/bin/lean/delguard.test.mjs +104 -0
  30. package/bin/lean/depcache.mjs +125 -17
  31. package/bin/lean/depcache.test.mjs +111 -0
  32. package/bin/lean/design-gate.mjs +5 -5
  33. package/bin/lean/design-gate.test.mjs +14 -0
  34. package/bin/lean/effects.mjs +81 -7
  35. package/bin/lean/execution.mjs +81 -15
  36. package/bin/lean/execution.test.mjs +156 -3
  37. package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
  38. package/bin/lean/guardgate.mjs +30 -7
  39. package/bin/lean/guardgate.test.mjs +44 -1
  40. package/bin/lean/guards.test.mjs +1 -1
  41. package/bin/lean/heavy.test.mjs +87 -0
  42. package/bin/lean/hotarea.mjs +73 -0
  43. package/bin/lean/hotarea.test.mjs +73 -0
  44. package/bin/lean/issuewatch-reconcile.mjs +20 -1
  45. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  46. package/bin/lean/lanecheck.mjs +27 -3
  47. package/bin/lean/lanecheck.test.mjs +47 -5
  48. package/bin/lean/laneconfine.mjs +83 -0
  49. package/bin/lean/laneconfine.test.mjs +113 -0
  50. package/bin/lean/lean.mjs +398 -91
  51. package/bin/lean/lean.test.mjs +792 -26
  52. package/bin/lean/live-reconcile.mjs +169 -0
  53. package/bin/lean/live-reconcile.test.mjs +176 -0
  54. package/bin/lean/orchestrate-envhold.test.mjs +245 -0
  55. package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
  56. package/bin/lean/orchestrate.mjs +207 -17
  57. package/bin/lean/outcomeevidence.mjs +104 -0
  58. package/bin/lean/outcomeevidence.test.mjs +78 -0
  59. package/bin/lean/page-capture.mjs +68 -0
  60. package/bin/lean/page-capture.test.mjs +44 -0
  61. package/bin/lean/pagegate.mjs +46 -7
  62. package/bin/lean/pagegate.test.mjs +66 -1
  63. package/bin/lean/postdeploy-check.mjs +18 -4
  64. package/bin/lean/postdeploy-check.test.mjs +32 -1
  65. package/bin/lean/prefilter.mjs +36 -4
  66. package/bin/lean/prefilter.test.mjs +31 -1
  67. package/bin/lean/preflight.mjs +22 -0
  68. package/bin/lean/preflight.test.mjs +19 -1
  69. package/bin/lean/probe.mjs +18 -0
  70. package/bin/lean/probe.test.mjs +40 -0
  71. package/bin/lean/prompts.mjs +41 -4
  72. package/bin/lean/recovery.test.mjs +20 -0
  73. package/bin/lean/recurrence.mjs +133 -0
  74. package/bin/lean/recurrence.test.mjs +99 -0
  75. package/bin/lean/release-config.mjs +2 -1
  76. package/bin/lean/release-config.test.mjs +18 -0
  77. package/bin/lean/release-control.mjs +4 -2
  78. package/bin/lean/release-control.test.mjs +15 -0
  79. package/bin/lean/release-merge-hold.mjs +65 -0
  80. package/bin/lean/release-merge-hold.test.mjs +69 -0
  81. package/bin/lean/release-review.mjs +26 -9
  82. package/bin/lean/release-review.test.mjs +53 -0
  83. package/bin/lean/release-status.mjs +3 -1
  84. package/bin/lean/release-status.test.mjs +11 -0
  85. package/bin/lean/release.test.mjs +26 -1
  86. package/bin/lean/render.mjs +8 -7
  87. package/bin/lean/repro-output.test.mjs +45 -0
  88. package/bin/lean/routing.mjs +49 -0
  89. package/bin/lean/routing.test.mjs +54 -1
  90. package/bin/lean/run-issue-placement.test.mjs +30 -1
  91. package/bin/lean/sandbox-actions.mjs +121 -0
  92. package/bin/lean/sandbox-actions.test.mjs +94 -0
  93. package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
  94. package/bin/lean/sandbox-remote.mjs +3 -1
  95. package/bin/lean/schedd-health.mjs +14 -2
  96. package/bin/lean/schedd-health.test.mjs +13 -0
  97. package/bin/lean/schedd.mjs +43 -17
  98. package/bin/lean/schedd.test.mjs +61 -1
  99. package/bin/lean/toolchain.mjs +16 -6
  100. package/bin/lean/toolplace.mjs +12 -0
  101. package/bin/lean/weakguard.mjs +105 -0
  102. package/bin/lean/weakguard.test.mjs +59 -0
  103. package/bin/lean/winspawn.mjs +61 -0
  104. package/bin/lean/winspawn.test.mjs +45 -0
  105. package/bin/lean/worktree.mjs +3 -1
  106. package/bin/lean/worktree.test.mjs +11 -0
  107. package/bin/pool/agent.mjs +215 -15
  108. package/bin/pool/cache-sweep.mjs +74 -0
  109. package/bin/pool/cli.mjs +11 -3
  110. package/bin/pool/docker.mjs +33 -2
  111. package/bin/pool/health.mjs +38 -0
  112. package/bin/pool/lane-tools.mjs +23 -4
  113. package/bin/pool/lane-tools.test.mjs +12 -1
  114. package/bin/pool/router.mjs +21 -3
  115. package/bin/runner.mjs +37 -0
  116. package/bin/splash-scene.mjs +356 -0
  117. package/bin/win-hide-children.mjs +114 -0
  118. package/commands/orchestrate.md +18 -27
  119. package/commands/review-pr-agents/infra.md +1 -0
  120. package/commands/review-pr-staging.md +2 -2
  121. package/docs/CONFIG.md +60 -3
  122. package/docs/OUTCOME-CODES.md +3 -0
  123. package/package.json +1 -1
  124. package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
  125. package/plugins/forgedock-splash/README.md +1 -1
  126. package/plugins/forgedock-splash/hooks/scene.ts +142 -8
  127. package/pool/README.md +6 -0
  128. package/pool/image/entrypoint.sh +1 -0
  129. package/scripts/acceptance-red-green.sh +8 -3
  130. package/scripts/acceptance-red-green.test.sh +8 -0
  131. package/scripts/check-spec-size.sh +3 -1
  132. package/scripts/gen-splash-scene.mjs +24 -0
  133. package/scripts/review-staging-pre.sh +8 -3
  134. package/scripts/review-staging-pre.test.sh +2 -0
@@ -0,0 +1,128 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5824: the batch dependency DAG, built in code (no LLM): `forgedock orchestrate` prints it as the plan table before the
5
+ * first lane and keeps it in the batch plan, so a resume schedules from the same edges and the report counts false holds.
6
+ *
7
+ * Edge X -> N (N waits until X merges) comes from two sources only:
8
+ * - declared: N's trusted body has a `Depends on #X` / `Blocked by #X` line (bold, list, `:`, comma/and lists, any case),
9
+ * read by the engine's own parser (`parseDependsOn`), so the plan and the admission check agree;
10
+ * - logical: X's frozen contract (its last trusted FORGE:CONTRACT comment) delivers a file that is not on the base yet and
11
+ * N's body names that path (N uses what X creates). No contract, no logical edge.
12
+ * Predicted file overlap (paths named in both bodies, or a shared existing deliverable) is a warning in the plan, never an
13
+ * edge: each lane merges its base and resolves the conflict itself. A cycle that a logical edge closes drops that edge.
14
+ * False hold: a planned edge no longer present when the batch ends (an operator removed the line), counted per batch.
15
+ */
16
+ import { parseDependsOn, isTrustedActor } from "../engine/phases.mjs";
17
+ import { parseContractComment } from "./render.mjs";
18
+ import { namedPaths } from "./prefilter.mjs";
19
+ import { cyclicNodes } from "./orchestrate.mjs";
20
+
21
+ const CONTRACT_HEAD = "<!-- FORGE:CONTRACT -->";
22
+ const commentTrusted = (c) => isTrustedActor({ association: c?.authorAssociation ?? c?.author_association, type: c?.author?.is_bot ? "Bot" : c?.user?.type, login: c?.author?.login ?? c?.user?.login });
23
+
24
+ /** Deliverable paths of the last trusted, parseable FORGE:CONTRACT comment (`gh --json comments` shape), or []. */
25
+ export function contractDeliverables(comments, { trusted = commentTrusted } = {}) {
26
+ let out = [];
27
+ for (const c of Array.isArray(comments) ? comments : []) {
28
+ const body = String(c?.body ?? "").trimStart();
29
+ if (!body.startsWith(CONTRACT_HEAD) || !trusted(c)) continue;
30
+ const d = parseContractComment(body)?.contract?.deliverables;
31
+ if (Array.isArray(d)) out = [...new Set(d.map((x) => x?.path).filter((p) => typeof p === "string" && p))];
32
+ }
33
+ return out;
34
+ }
35
+
36
+ /** One issue's plan inputs from a `gh issue view` object: `{title, body, trusted, files, deliverables}`. */
37
+ export function planView(v, { trusted = false } = {}) {
38
+ const body = String(v?.body ?? "");
39
+ return { title: String(v?.title ?? ""), body, trusted: trusted === true, files: namedPaths(body), deliverables: contractDeliverables(v?.comments) };
40
+ }
41
+
42
+ /** Declared dependencies of `n` (only a trusted body declares, the engine admission's rule). */
43
+ export function declaredDeps(n, view) {
44
+ return view?.trusted ? parseDependsOn(view.body, n) : [];
45
+ }
46
+
47
+ /**
48
+ * The batch DAG. `views`: Map issue -> planView; `exists(path)`: the path is on the lane base (a deliverable already there
49
+ * is shared work, an overlap, not a prerequisite). Returns `{edges:[{from,to,kind,why?}], outside:[{issue,dep}],
50
+ * overlaps:[{a,b,files}], dropped:[edge]}`; `outside` lists declared dependencies not in the batch (the runner pulls open ones in).
51
+ */
52
+ export function buildDag(issues, views, { exists = () => false } = {}) {
53
+ const set = new Set(issues), edges = [], outside = [], seen = new Set();
54
+ const add = (e) => { const k = `${e.from}>${e.to}`; if (e.from === e.to || seen.has(k)) return; seen.add(k); edges.push(e); };
55
+ for (const n of issues) for (const d of declaredDeps(n, views.get(n))) {
56
+ if (set.has(d)) add({ from: d, to: n, kind: "declared" }); else outside.push({ issue: n, dep: d });
57
+ }
58
+ const isNew = (p) => { try { return !exists(p); } catch { return false; } };
59
+ for (const x of issues) for (const p of (views.get(x)?.deliverables ?? []).filter(isNew)) {
60
+ for (const n of issues) {
61
+ const v = views.get(n);
62
+ if (n === x || !v?.files.includes(p) || v.deliverables.includes(p)) continue;
63
+ add({ from: x, to: n, kind: "logical", why: p });
64
+ }
65
+ }
66
+ const dropped = [];
67
+ const depsOf = (n) => edges.filter((e) => e.to === n).map((e) => e.from);
68
+ for (let cyc = cyclicNodes(issues, depsOf); cyc.size; cyc = cyclicNodes(issues, depsOf)) {
69
+ const weak = edges.filter((e) => e.kind === "logical" && cyc.has(e.from) && cyc.has(e.to));
70
+ if (!weak.length) break; // a declared cycle stays: the runner reports it (#5162)
71
+ for (const e of weak) { dropped.push(e); edges.splice(edges.indexOf(e), 1); }
72
+ }
73
+ const overlaps = [];
74
+ for (let i = 0; i < issues.length; i++) for (let j = i + 1; j < issues.length; j++) {
75
+ const a = views.get(issues[i]), b = views.get(issues[j]);
76
+ if (!a || !b) continue;
77
+ const fa = new Set([...a.files, ...a.deliverables]);
78
+ const files = [...new Set([...b.files, ...b.deliverables])].filter((f) => fa.has(f));
79
+ if (files.length && !seen.has(`${issues[i]}>${issues[j]}`) && !seen.has(`${issues[j]}>${issues[i]}`)) overlaps.push({ a: issues[i], b: issues[j], files });
80
+ }
81
+ return { edges, outside, overlaps, dropped };
82
+ }
83
+
84
+ /** Logical dependencies of `n` in a (persisted) DAG: the runner adds them to the declared ones. */
85
+ export function logicalDepsOf(dag, n) {
86
+ return (dag?.edges ?? []).filter((e) => e.kind === "logical" && e.to === n).map((e) => e.from);
87
+ }
88
+
89
+ const cell = (s, max = 48) => { const t = String(s ?? "").replace(/\s+/g, " ").replace(/\|/g, "/").trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t || "-"; };
90
+
91
+ /** The plan table (issue, title, waits on, likely files, overlap warning) and its summary lines. */
92
+ export function formatPlan(issues, views, dag, { parallel = null, parallelFrom = null } = {}) {
93
+ const lines = [`plan: ${issues.length} issue(s), ${dag.edges.length} edge(s) (declared ${dag.edges.filter((e) => e.kind === "declared").length}, logical ${dag.edges.filter((e) => e.kind === "logical").length})${parallel ? `, K=${parallel}${parallelFrom ? ` (${parallelFrom})` : ""}` : ""}`,
94
+ "| issue | title | waits on | likely files | overlap (warning) |", "| --- | --- | --- | --- | --- |"];
95
+ for (const n of issues) {
96
+ const v = views.get(n);
97
+ const waits = dag.edges.filter((e) => e.to === n).map((e) => `#${e.from}${e.kind === "logical" ? ` (logical: ${e.why})` : ""}`);
98
+ const out = dag.outside.filter((o) => o.issue === n).map((o) => `#${o.dep} (outside)`);
99
+ const ov = dag.overlaps.filter((o) => o.a === n || o.b === n).map((o) => `#${o.a === n ? o.b : o.a}`);
100
+ lines.push(`| #${n} | ${cell(v?.title)} | ${[...waits, ...out].join(", ") || "-"} | ${cell((v?.files ?? []).slice(0, 3).join(", "), 60)} | ${ov.join(", ") || "-"} |`);
101
+ }
102
+ for (const e of dag.dropped) lines.push(`plan: dropped logical edge #${e.from} -> #${e.to} (${e.why}): it closed a cycle`);
103
+ if (dag.overlaps.length) lines.push(`plan: overlaps are warnings only, never edges: ${dag.overlaps.map((o) => `#${o.a}/#${o.b} (${o.files.slice(0, 2).join(", ")})`).join("; ")}`);
104
+ return lines;
105
+ }
106
+
107
+ /**
108
+ * False holds: planned edges an operator removed before the batch ended. `currentDeps(n)` is n's declared dependencies now
109
+ * (null = unreadable: its edges are not judged). Logical edges are code-derived and not judged. Returns the removed edges.
110
+ */
111
+ export async function falseHolds(dag, currentDeps) {
112
+ const removed = [], byTo = new Map();
113
+ for (const e of (dag?.edges ?? []).filter((x) => x.kind === "declared")) byTo.set(e.to, [...(byTo.get(e.to) ?? []), e]);
114
+ for (const [n, es] of byTo) {
115
+ let now;
116
+ try { now = await currentDeps(n); } catch { now = null; }
117
+ if (!Array.isArray(now)) continue;
118
+ for (const e of es) if (!now.includes(e.from)) removed.push(e);
119
+ }
120
+ return removed;
121
+ }
122
+
123
+ /** `false holds: R/P planned edges removed by an operator (...)`, or null without planned edges. */
124
+ export function formatFalseHolds(dag, removed) {
125
+ const planned = (dag?.edges ?? []).length;
126
+ if (!planned) return null;
127
+ return `false holds: ${removed.length}/${planned} planned edge(s) removed by an operator${removed.length ? ` (${removed.map((e) => `#${e.to} on #${e.from}`).join(", ")})` : ""}`;
128
+ }
@@ -0,0 +1,131 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5824: the batch dependency DAG in code: declared and logical edges, overlap warnings, plan table, false holds.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { buildDag, contractDeliverables, declaredDeps, falseHolds, formatFalseHolds, formatPlan, logicalDepsOf, planView } from "./dag.mjs";
7
+ import { renderContract } from "./render.mjs";
8
+ import { orchestrate } from "./orchestrate.mjs";
9
+
10
+ const OWNER = { authorAssociation: "OWNER", author: { login: "maintainer" } };
11
+ const contractComment = (paths, who = OWNER) => ({ ...who, body: `<!-- FORGE:CONTRACT -->\n${renderContract({ requirements: [], deliverables: paths.map((path, i) => ({ id: `D${i + 1}`, path, change: "x", requirements: [] })), preserve: [], validate: [] }, "0123456789ab")}` });
12
+ const view = (body, { title = "t", comments = [], trusted = true } = {}) => planView({ title, body, comments }, { trusted });
13
+ const viewsOf = (o) => new Map(Object.entries(o).map(([k, v]) => [Number(k), v]));
14
+
15
+ describe("#5824 declared edges", () => {
16
+ it("reads every form the command spec lists: bold, list, colon, comma/and lists, any case, Blocked by", () => {
17
+ const forms = ["Depends on #1", "**Depends on** #1", "- Depends on: #1, #2", "* depends ON #1 and #2", "**Blocked by:** #2", "blocked by #1, #2 (needs the helper)", "__Depends on__ #1 & #2"];
18
+ for (const f of forms) {
19
+ const want = /#2/.test(f) ? (/#1/.test(f) ? [1, 2] : [2]) : [1];
20
+ assert.deepEqual(declaredDeps(9, view(`Intro\n${f}\nmore`)).sort(), want, f);
21
+ }
22
+ });
23
+
24
+ it("ignores mid-line mentions, self references and an untrusted body", () => {
25
+ assert.deepEqual(declaredDeps(9, view("This depends on #1 somehow.\nDepends on #9")), []);
26
+ assert.deepEqual(declaredDeps(9, view("Depends on #1", { trusted: false })), []);
27
+ });
28
+
29
+ it("in-batch dependencies are edges, out-of-batch ones are listed as outside", () => {
30
+ const dag = buildDag([1, 2], viewsOf({ 1: view(""), 2: view("Depends on #1, #7") }));
31
+ assert.deepEqual(dag.edges, [{ from: 1, to: 2, kind: "declared" }]);
32
+ assert.deepEqual(dag.outside, [{ issue: 2, dep: 7 }]);
33
+ });
34
+ });
35
+
36
+ describe("#5824 logical edges and overlap", () => {
37
+ it("a dependency's new contract deliverable named by the dependent is a logical edge", () => {
38
+ const v = viewsOf({ 1: view("adds the helper", { comments: [contractComment(["bin/lean/newhelper.mjs"])] }), 2: view("use `bin/lean/newhelper.mjs` in the runner") });
39
+ const dag = buildDag([1, 2], v, { exists: () => false });
40
+ assert.deepEqual(dag.edges, [{ from: 1, to: 2, kind: "logical", why: "bin/lean/newhelper.mjs" }]);
41
+ assert.deepEqual(logicalDepsOf(dag, 2), [1]);
42
+ assert.deepEqual(dag.overlaps, []);
43
+ });
44
+
45
+ it("no contract, an existing deliverable, or an untrusted contract gives no edge; shared files are a warning only", () => {
46
+ const noContract = buildDag([1, 2], viewsOf({ 1: view("edit `bin/a/x.mjs`"), 2: view("also `bin/a/x.mjs`") }));
47
+ assert.deepEqual(noContract.edges, []);
48
+ assert.deepEqual(noContract.overlaps, [{ a: 1, b: 2, files: ["bin/a/x.mjs"] }]);
49
+ const existing = buildDag([1, 2], viewsOf({ 1: view("", { comments: [contractComment(["bin/a/x.mjs"])] }), 2: view("touch bin/a/x.mjs") }), { exists: () => true });
50
+ assert.deepEqual(existing.edges, []);
51
+ assert.equal(existing.overlaps.length, 1);
52
+ const stranger = { authorAssociation: "NONE", author: { login: "someone" } };
53
+ assert.deepEqual(contractDeliverables([contractComment(["bin/a/y.mjs"], stranger)]), []);
54
+ assert.deepEqual(contractDeliverables([contractComment(["bin/a/y.mjs"]), contractComment(["bin/a/z.mjs"])]), ["bin/a/z.mjs"]);
55
+ });
56
+
57
+ it("a cycle closed by logical edges drops them; a declared cycle stays for the runner", () => {
58
+ const v = viewsOf({
59
+ 1: view("Depends on #2\nuses `bin/b/one.mjs`", { comments: [contractComment(["bin/b/two.mjs"])] }),
60
+ 2: view("uses `bin/b/two.mjs`", { comments: [contractComment(["bin/b/one.mjs"])] }),
61
+ });
62
+ const dag = buildDag([1, 2], v);
63
+ assert.deepEqual(dag.edges, [{ from: 2, to: 1, kind: "declared" }]);
64
+ assert.equal(dag.dropped.length, 1);
65
+ const decl = buildDag([1, 2], viewsOf({ 1: view("Depends on #2"), 2: view("Depends on #1") }));
66
+ assert.equal(decl.edges.length, 2);
67
+ });
68
+ });
69
+
70
+ describe("#5824 plan table and false holds", () => {
71
+ it("prints one row per issue with waits-on, files and overlap warnings", () => {
72
+ const v = viewsOf({ 1: view("edit `bin/a/x.mjs`", { title: "first | piped" }), 2: view("Depends on #1\n`bin/a/x.mjs`"), 3: view("also `bin/a/x.mjs`") });
73
+ const dag = buildDag([1, 2, 3], v);
74
+ const lines = formatPlan([1, 2, 3], v, dag, { parallel: 3, parallelFrom: "--parallel" });
75
+ assert.match(lines[0], /^plan: 3 issue\(s\), 1 edge\(s\) \(declared 1, logical 0\), K=3 \(--parallel\)$/);
76
+ assert.match(lines.find((l) => l.startsWith("| #2 ")), /\| #1 \| bin\/a\/x\.mjs \| #3 \|$/);
77
+ assert.match(lines.find((l) => l.startsWith("| #1 ")), /first \/ piped/);
78
+ assert.match(lines.at(-1), /overlaps are warnings only, never edges: #1\/#3 .*#2\/#3/);
79
+ });
80
+
81
+ it("counts planned declared edges an operator removed; unreadable issues are not judged", async () => {
82
+ const dag = { edges: [{ from: 1, to: 2, kind: "declared" }, { from: 3, to: 2, kind: "declared" }, { from: 1, to: 4, kind: "declared" }, { from: 1, to: 5, kind: "logical", why: "p" }] };
83
+ const removed = await falseHolds(dag, async (n) => { if (n === 4) throw new Error("gh down"); return n === 2 ? [3] : []; });
84
+ assert.deepEqual(removed, [{ from: 1, to: 2, kind: "declared" }]);
85
+ assert.equal(formatFalseHolds(dag, removed), "false holds: 1/4 planned edge(s) removed by an operator (#2 on #1)");
86
+ assert.equal(formatFalseHolds({ edges: [] }, []), null);
87
+ });
88
+ });
89
+
90
+ describe("#5824 orchestrate honours logical edges", () => {
91
+ it("an issue with a logical dependency starts only after it merges, without a Depends on line", async () => {
92
+ const started = [], done = [];
93
+ const rows = await orchestrate({ issues: [2, 1], parallel: 2, readBody: async () => "", recovery: { maxAttempts: 0 }, logicalDeps: (n) => (n === 2 ? [1] : []),
94
+ runOne: async (n) => { started.push({ n, after: [...done] }); await new Promise((r) => setTimeout(r, 5)); done.push(n); return { terminalReason: "merged", pr: 100 + n }; } });
95
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
96
+ assert.deepEqual(started.find((s) => s.n === 2).after, [1]);
97
+ });
98
+ });
99
+
100
+ describe("#5824 forgedock orchestrate prints the plan from code and reports false holds", () => {
101
+ it("plan table before the first lane, DAG kept in the plan, one view per issue, a removed edge counted", async () => {
102
+ const { tmpDir } = await import("../tests/_tmp.mjs");
103
+ const { openBatch } = await import("./batch.mjs");
104
+ const { orchestrateFromCli } = await import("../engine-cli.mjs");
105
+ const { writeFileSync, readdirSync } = await import("node:fs");
106
+ const { join } = await import("node:path");
107
+ const bodies = { 1: "adds the thing", 2: "**Depends on:** #1" }, views = { 1: 0, 2: 0 };
108
+ const leanIo = { gh: async (a) => {
109
+ if (a[0] === "api") return "OWNER\n";
110
+ if (a[0] === "issue" && a[1] === "view") { if (a.some((x) => /^title,body,/.test(x))) views[a[2]] = (views[a[2]] ?? 0) + 1; return JSON.stringify({ title: `issue ${a[2]}`, body: bodies[a[2]] ?? "", milestone: null, comments: [], author: { login: "o" } }); }
111
+ return a[0] === "repo" ? "main\n" : "[]";
112
+ }, git: async (a) => (a[0] === "ls-remote" ? "abc\tref\n" : "") };
113
+ const batchRoot = tmpDir("dag-batch-");
114
+ const deps = { dir: tmpDir("dag-run-"), batchRoot, sched: null, allowTmpfs: true, emitTelemetry: async () => {}, leanIo, pollMs: 5, preflight: null,
115
+ io: { gh: async (a) => (a[0] === "issue" ? JSON.stringify({ body: bodies[a[2]] ?? "", state: "OPEN" }) : "o/r\n"), git: async () => "" },
116
+ leanModule: { runCore: async (o) => { if (o.issue === 1) bodies[2] = "operator dropped the line"; return { terminalReason: "merged", pr: o.issue, cost_usd: 0, wall_ms: 1 }; } } };
117
+ const adm = tmpDir("dag-adm-"), prevCwd = process.cwd();
118
+ writeFileSync(join(adm, "forge.yaml"), "engine:\n admission_enabled: false\n");
119
+ process.chdir(adm);
120
+ const lines = [], l = console.log; console.log = (...a) => lines.push(a.join(" "));
121
+ try { await orchestrateFromCli(["1", "2", "--repo", "o/r", "--no-prefilter", "--parallel", "2"], deps); } finally { console.log = l; process.chdir(prevCwd); }
122
+ const out = lines.join("\n");
123
+ assert.match(out, /plan: 2 issue\(s\), 1 edge\(s\) \(declared 1, logical 0\), K=2 \(--parallel\)/);
124
+ assert.match(out, /\| #2 \| issue 2 \| #1 \|/);
125
+ assert.match(out, /false holds: 1\/1 planned edge\(s\) removed by an operator \(#2 on #1\)/);
126
+ assert.equal(views[1], 1, "the plan pass's view is reused by the runner");
127
+ const b = openBatch(batchRoot, readdirSync(batchRoot)[0]);
128
+ assert.deepEqual(b.readPlan().dag.edges, [{ from: 1, to: 2, kind: "declared" }]);
129
+ assert.equal(b.readReport().dag.falseHolds.length, 1);
130
+ });
131
+ });
@@ -22,9 +22,9 @@ const TEXT_MAX = 200;
22
22
  const ANCHORS_MAX = 10;
23
23
  const MARKER_RE = /^<!--\s*FORGE:DECISION\s+(\{.*\})\s*-->/;
24
24
 
25
- const one = (v, max = TEXT_MAX) => {
25
+ const one = (v, max = TEXT_MAX, ellipsis = true) => {
26
26
  const t = typeof v === "string" ? noComments(v, " ").replace(/\s+/g, " ").trim() : "";
27
- return t.length > max ? `${t.slice(0, max - 1)}…` : t;
27
+ return t.length > max ? (ellipsis ? `${t.slice(0, max - 1)}…` : t.slice(0, max).trimEnd()) : t;
28
28
  };
29
29
  const strs = (v, max = ANCHORS_MAX, len = 200) => [...new Set((Array.isArray(v) ? v : []).map((x) => one(x, len)).filter(Boolean))].slice(0, max);
30
30
  const cleanAnchor = (a) => String(a).replace(/^\.\//, "").replace(/^\/+/, "");
@@ -81,7 +81,7 @@ export function parseDecisionComment(body, { issue = null } = {}) {
81
81
  } catch { return null; }
82
82
  }
83
83
 
84
- /** #5547: `<!-- FORGE:DECISION {"requirement":"R2","disposition":"post-deploy","why":"..."} -->` -> {requirement, disposition, why}; null for anything else (anchored records included). */
84
+ /** #5547: `<!-- FORGE:DECISION {"requirement":"R2","disposition":"post-deploy","why":"...","quote":"..."} -->` -> {requirement, disposition, why, quote?}; null for anything else (anchored records included). */
85
85
  export function parseRequirementDecision(body) {
86
86
  const m = MARKER_RE.exec(String(body ?? "").split("\n", 1)[0]);
87
87
  if (!m) return null;
@@ -89,7 +89,8 @@ export function parseRequirementDecision(body) {
89
89
  const raw = JSON.parse(m[1]);
90
90
  const id = typeof raw?.requirement === "string" ? raw.requirement.trim() : "";
91
91
  if (!/^R\d+$/.test(id) || raw.disposition !== "post-deploy") return null;
92
- return { requirement: id, disposition: "post-deploy", why: one(raw.why) };
92
+ const quote = one(raw.quote, 400, false); // #5773: the row's quote, so the decision survives a renumbering; #5786: clipped with no ellipsis so it stays a prefix of the row quote
93
+ return { requirement: id, disposition: "post-deploy", why: one(raw.why), ...(quote ? { quote } : {}) };
93
94
  } catch { return null; }
94
95
  }
95
96
 
@@ -97,4 +97,15 @@ describe("#5547 requirement decisions", () => {
97
97
  assert.equal(parseRequirementDecision('<!-- FORGE:DECISION {"choice":"x","anchors":["a.js"]} -->'), null);
98
98
  assert.equal(parseRequirementDecision("FORGE:DECISION prose"), null);
99
99
  });
100
+ it("#5786 a quote over 400 chars is clipped without an ellipsis, so it stays a prefix of the row quote", () => {
101
+ const long = `${"word ".repeat(100)}end`;
102
+ const q = parseRequirementDecision(`<!-- FORGE:DECISION ${JSON.stringify({ requirement: "R2", disposition: "post-deploy", quote: long })} -->`).quote;
103
+ assert.ok(q.length >= 399 && q.length <= 400);
104
+ assert.equal(q.includes("…"), false);
105
+ assert.ok(long.startsWith(q));
106
+ });
107
+ it("#5773 an optional quote is returned; without it the decision parses as before", () => {
108
+ assert.deepEqual(parseRequirementDecision('<!-- FORGE:DECISION {"requirement":"R12","disposition":"post-deploy","quote":" the real run creates invoices "} -->'), { requirement: "R12", disposition: "post-deploy", why: "", quote: "the real run creates invoices" });
109
+ assert.equal("quote" in parseRequirementDecision('<!-- FORGE:DECISION {"requirement":"R2","disposition":"post-deploy"} -->'), false);
110
+ });
100
111
  });
@@ -0,0 +1,84 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5819: the checkpoint's deletion guard. A checkpoint stages everything (`git add -A`), so anything that removed files from
5
+ * the worktree behind the builder's back (a failed dependency-cache publish, a stray recursive delete) would be committed and
6
+ * pushed to the PR branch. Before the commit, the staged deletions of files the base tracks are compared with the contract's
7
+ * deliverables: deletions outside them (more than `max`, default 0) are unstaged and restored in the worktree, and the caller
8
+ * refuses to push. Deliverable deletions, and deletions of files the lane itself added, commit as before. Git is injected:
9
+ * `git(args) -> stdout`, throws on failure.
10
+ */
11
+ export const MAX_FOREIGN_DELETIONS_ENV = "FORGE_CHECKPOINT_MAX_DELETIONS";
12
+
13
+ /** The tolerated number of non-deliverable deletions: `FORGE_CHECKPOINT_MAX_DELETIONS` (a non-negative integer), else 0. */
14
+ export function maxForeignDeletions(env = process.env) {
15
+ const v = String(env?.[MAX_FOREIGN_DELETIONS_ENV] ?? "").trim();
16
+ return /^\d+$/.test(v) ? Number(v) : 0;
17
+ }
18
+
19
+ const CHUNK = 200;
20
+ const chunks = (l) => { const out = []; for (let i = 0; i < l.length; i += CHUNK) out.push(l.slice(i, i + CHUNK)); return out; };
21
+ const clean = (p) => String(p ?? "").trim().replace(/^\.\//, "").replace(/\/+$/, "");
22
+
23
+ /**
24
+ * Staged deletions as {path, to}: `to` is the rename destination (null for a plain deletion). Plumbing (`diff-index`), so a
25
+ * porcelain diff config never changes the format. Entries with a newline are not git -z output and are ignored.
26
+ */
27
+ export function parseStagedDeletions(out) {
28
+ const f = String(out ?? "").split("\0");
29
+ const res = [];
30
+ for (let i = 0; i < f.length;) {
31
+ const st = f[i++];
32
+ if (!st) continue;
33
+ if (/^R\d*$/.test(st)) { const path = f[i++], to = f[i++]; if (path && to && !/\n/.test(path + to)) res.push({ path, to }); }
34
+ else if (st === "D") { const path = f[i++]; if (path && !/\n/.test(path)) res.push({ path, to: null }); }
35
+ else return res; // not --name-status -z output (an injected fake): nothing parsed past it
36
+ }
37
+ return res;
38
+ }
39
+
40
+ /** Is `p` a deliverable (an exact path, or under a deliverable directory)? */
41
+ const covered = (p, keep) => keep.some((k) => k && (p === k || p.startsWith(`${k}/`)));
42
+
43
+ /**
44
+ * After `git add -A`, before the checkpoint commit. Returns {refused, deleted, foreign, restored}: `foreign` are the staged
45
+ * deletions of base-tracked files outside `keep` (contract deliverable paths). When there are more than `max` of them they are
46
+ * unstaged and checked out again (refused: true, restored: whether every one is back on disk per git). Never throws: a git
47
+ * failure while listing is a refusal-free pass (nothing parsed), a failure while restoring is reported in `error`.
48
+ */
49
+ export async function guardStagedDeletions({ git, base = null, keep = [], max = 0 }) {
50
+ const want = (keep ?? []).map(clean).filter(Boolean);
51
+ let dels = [];
52
+ try { dels = parseStagedDeletions(await git(["diff-index", "--cached", "--name-status", "-z", "-M", "--diff-filter=DR", "HEAD"])); } catch { return { refused: false, deleted: [], foreign: [] }; }
53
+ if (!dels.length) return { refused: false, deleted: [], foreign: [] };
54
+ // A rename into or out of a deliverable is the lane's own move; any other rename still removes the original path.
55
+ const cands = dels.filter((d) => !covered(d.path, want) && !(d.to && covered(d.to, want))).map((d) => d.path);
56
+ let foreign = cands;
57
+ if (base && cands.length) { // files the lane added itself (absent on the base) are its own to delete
58
+ try {
59
+ const onBase = new Set();
60
+ for (const c of chunks(cands)) for (const p of String(await git(["ls-tree", "-r", "--name-only", "-z", base, "--", ...c])).split("\0")) if (p) onBase.add(p);
61
+ foreign = cands.filter((p) => onBase.has(p));
62
+ } catch { foreign = cands; } // unreadable base: every candidate counts
63
+ }
64
+ const deleted = dels.map((d) => d.path);
65
+ if (foreign.length <= max) return { refused: false, deleted, foreign };
66
+ // Unstage the whole rename (both sides), then bring the originals back from HEAD.
67
+ const renamedTo = dels.filter((d) => d.to && foreign.includes(d.path)).map((d) => d.to);
68
+ try {
69
+ for (const c of chunks([...foreign, ...renamedTo])) await git(["reset", "-q", "--", ...c]);
70
+ for (const c of chunks(foreign)) await git(["checkout", "-q", "HEAD", "--", ...c]);
71
+ let still = [];
72
+ try { still = String(await git(["ls-files", "--deleted", "-z"])).split("\0").filter((p) => p && foreign.includes(p)); } catch { /* unverified */ }
73
+ return { refused: true, deleted, foreign, restored: still.length === 0 };
74
+ } catch (e) {
75
+ return { refused: true, deleted, foreign, restored: false, error: String(e?.message ?? e).slice(0, 300) };
76
+ }
77
+ }
78
+
79
+ /** One-line evidence for the run log, the trajectory and the engine-error detail. */
80
+ export function deletionEvidence(g, reason = "checkpoint") {
81
+ const sample = g.foreign.slice(0, 8).map((p) => `\`${p}\``).join(", ");
82
+ return `${reason}: the staged diff deleted ${g.foreign.length} tracked file(s) outside the contract deliverables (${sample}${g.foreign.length > 8 ? ", ..." : ""}); `
83
+ + `${g.restored ? "they were restored in the worktree" : `restoring them failed${g.error ? ` (${g.error})` : ""}`} and nothing was pushed (#5819)`;
84
+ }
@@ -0,0 +1,104 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /** #5819: the checkpoint deletion guard on a real git repo. */
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { execFileSync } from "node:child_process";
7
+ import { mkdirSync, writeFileSync, existsSync, rmSync, renameSync } from "node:fs";
8
+ import { join, dirname } from "node:path";
9
+ import { tmpDir } from "../tests/_tmp.mjs";
10
+ import { guardStagedDeletions, parseStagedDeletions, maxForeignDeletions, deletionEvidence } from "./delguard.mjs";
11
+
12
+ const sh = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8" });
13
+ const put = (cwd, f, t = "x\n") => { mkdirSync(dirname(join(cwd, f)), { recursive: true }); writeFileSync(join(cwd, f), t); };
14
+ const PKG = Array.from({ length: 12 }, (_, i) => `packages/adapters/src/f${i}.ts`);
15
+ const repo = () => {
16
+ const d = tmpDir("delguard-repo-");
17
+ sh(d, "init", "-q", "-b", "main"); sh(d, "config", "user.email", "t@t"); sh(d, "config", "user.name", "t");
18
+ for (const f of ["src/a.js", "src/b.js", "docs/old.md", ...PKG]) put(d, f, `${f}\n`);
19
+ sh(d, "add", "-A"); sh(d, "commit", "-q", "-m", "base");
20
+ sh(d, "checkout", "-q", "-b", "lane");
21
+ return d;
22
+ };
23
+ const gitIn = (d) => async (args) => execFileSync("git", args, { cwd: d, encoding: "utf8" });
24
+ const stagedNames = (d) => sh(d, "diff", "--cached", "--name-status").trim().split("\n").filter(Boolean);
25
+ const checkpoint = async (d, o) => { sh(d, "add", "-A"); const g = await guardStagedDeletions({ git: gitIn(d), base: "main", ...o }); return g; };
26
+
27
+ describe("guardStagedDeletions (#5819)", () => {
28
+ it("a staged diff deleting tracked files outside the deliverables is refused: the files are unstaged and back on disk, the rest still commits", async () => {
29
+ const d = repo();
30
+ put(d, "src/a.js", "fixed\n");
31
+ rmSync(join(d, "packages"), { recursive: true }); // what the failed publish did
32
+ const g = await checkpoint(d, { keep: ["src/a.js"] });
33
+ assert.equal(g.refused, true);
34
+ assert.equal(g.foreign.length, PKG.length);
35
+ assert.equal(g.restored, true);
36
+ for (const f of PKG) assert.ok(existsSync(join(d, f)), f);
37
+ assert.deepEqual(stagedNames(d), ["M\tsrc/a.js"], "only the real change stays staged");
38
+ sh(d, "commit", "-q", "-m", "wip(forge): checkpoint after exit (needs-human)");
39
+ assert.equal(sh(d, "diff", "--name-status", "main", "HEAD").trim(), "M\tsrc/a.js");
40
+ assert.match(deletionEvidence(g), /deleted 12 tracked file\(s\) outside the contract deliverables .*restored in the worktree and nothing was pushed/);
41
+ });
42
+
43
+ it("deletions listed as deliverables (a file or a directory) commit unchanged", async () => {
44
+ const d = repo();
45
+ rmSync(join(d, "src/b.js")); rmSync(join(d, "packages"), { recursive: true });
46
+ const g = await checkpoint(d, { keep: ["src/b.js", "packages/adapters/"] });
47
+ assert.equal(g.refused, false);
48
+ assert.equal(g.deleted.length, PKG.length + 1);
49
+ assert.deepEqual(g.foreign, []);
50
+ assert.ok(!existsSync(join(d, "src/b.js")));
51
+ assert.equal(stagedNames(d).filter((l) => l.startsWith("D\t")).length, PKG.length + 1);
52
+ });
53
+
54
+ it("a file the lane added itself (absent on the base) is the lane's to delete", async () => {
55
+ const d = repo();
56
+ put(d, "src/tmp-helper.js"); sh(d, "add", "-A"); sh(d, "commit", "-q", "-m", "lane add");
57
+ rmSync(join(d, "src/tmp-helper.js"));
58
+ const g = await checkpoint(d, { keep: [] });
59
+ assert.equal(g.refused, false);
60
+ assert.deepEqual(g.deleted, ["src/tmp-helper.js"]);
61
+ });
62
+
63
+ it("the threshold tolerates up to `max` foreign deletions", async () => {
64
+ const d = repo();
65
+ rmSync(join(d, "src/b.js")); rmSync(join(d, "docs/old.md"));
66
+ assert.equal((await checkpoint(d, { keep: [], max: 2 })).refused, false);
67
+ const g = await checkpoint(d, { keep: [], max: 1 });
68
+ assert.equal(g.refused, true);
69
+ assert.ok(existsSync(join(d, "src/b.js")) && existsSync(join(d, "docs/old.md")));
70
+ });
71
+
72
+ it("a rename into a deliverable commits; a rename of a non-deliverable is undone on both sides", async () => {
73
+ const d = repo();
74
+ renameSync(join(d, "docs/old.md"), join(d, "docs/new.md"));
75
+ assert.equal((await checkpoint(d, { keep: ["docs/new.md"] })).refused, false);
76
+ sh(d, "reset", "-q"); renameSync(join(d, "docs/new.md"), join(d, "docs/old.md"));
77
+ renameSync(join(d, "src/b.js"), join(d, "src/c.js"));
78
+ const g = await checkpoint(d, { keep: ["src/a.js"] });
79
+ assert.equal(g.refused, true);
80
+ assert.deepEqual(g.foreign, ["src/b.js"]);
81
+ assert.ok(existsSync(join(d, "src/b.js")), "original restored");
82
+ assert.deepEqual(stagedNames(d), [], "neither side of the rename stays staged");
83
+ });
84
+
85
+ it("nothing staged, or git unreadable: no refusal", async () => {
86
+ const d = repo();
87
+ assert.deepEqual(await checkpoint(d, { keep: [] }), { refused: false, deleted: [], foreign: [] });
88
+ assert.equal((await guardStagedDeletions({ git: async () => { throw new Error("boom"); } })).refused, false);
89
+ });
90
+ });
91
+
92
+ describe("delguard helpers (#5819)", () => {
93
+ it("parses diff-index -z output and ignores anything else", () => {
94
+ assert.deepEqual(parseStagedDeletions("D\0a/b.js\0R087\0old.js\0new.js\0"), [{ path: "a/b.js", to: null }, { path: "old.js", to: "new.js" }]);
95
+ assert.deepEqual(parseStagedDeletions("diff --git a/src/foo.js b/src/foo.js\n+fix"), []);
96
+ assert.deepEqual(parseStagedDeletions(""), []);
97
+ });
98
+ it("FORGE_CHECKPOINT_MAX_DELETIONS: a non-negative integer, else 0", () => {
99
+ assert.equal(maxForeignDeletions({}), 0);
100
+ assert.equal(maxForeignDeletions({ FORGE_CHECKPOINT_MAX_DELETIONS: "5" }), 5);
101
+ assert.equal(maxForeignDeletions({ FORGE_CHECKPOINT_MAX_DELETIONS: "-1" }), 0);
102
+ assert.equal(maxForeignDeletions({ FORGE_CHECKPOINT_MAX_DELETIONS: "lots" }), 0);
103
+ });
104
+ });