forgedock 1.53.0 → 1.54.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 (185) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +6 -3
  12. package/bin/engine/telemetry-seam.mjs +8 -2
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +57 -20
  15. package/bin/first-run.mjs +122 -0
  16. package/bin/forgedock.mjs +128 -146
  17. package/bin/help-text.mjs +144 -0
  18. package/bin/hooks/pre-tool-use.mjs +7 -0
  19. package/bin/journey.mjs +82 -83
  20. package/bin/lean/acceptance.mjs +313 -0
  21. package/bin/lean/acceptance.test.mjs +215 -0
  22. package/bin/lean/activation.mjs +18 -0
  23. package/bin/lean/activation.test.mjs +23 -1
  24. package/bin/lean/batch-health.mjs +74 -1
  25. package/bin/lean/batch-health.test.mjs +54 -1
  26. package/bin/lean/batch.test.mjs +11 -9
  27. package/bin/lean/branchlock.mjs +54 -0
  28. package/bin/lean/branchlock.test.mjs +49 -0
  29. package/bin/lean/ceiling.mjs +72 -0
  30. package/bin/lean/ceiling.test.mjs +54 -0
  31. package/bin/lean/ci-budget.mjs +366 -0
  32. package/bin/lean/ci-budget.test.mjs +167 -0
  33. package/bin/lean/conformance.e2e.test.mjs +7 -0
  34. package/bin/lean/conformance.mjs +77 -19
  35. package/bin/lean/conformance.test.mjs +129 -3
  36. package/bin/lean/context.mjs +35 -6
  37. package/bin/lean/context.test.mjs +27 -1
  38. package/bin/lean/depcache.mjs +25 -1
  39. package/bin/lean/depcache.test.mjs +26 -0
  40. package/bin/lean/e2e.mjs +18 -2
  41. package/bin/lean/e2e.test.mjs +26 -1
  42. package/bin/lean/effects.mjs +40 -11
  43. package/bin/lean/execution.test.mjs +24 -0
  44. package/bin/lean/facts.mjs +3 -3
  45. package/bin/lean/facts.test.mjs +5 -0
  46. package/bin/lean/fixround.mjs +14 -0
  47. package/bin/lean/fixround.test.mjs +25 -2
  48. package/bin/lean/gh-assoc.test.mjs +2 -1
  49. package/bin/lean/integration.mjs +100 -9
  50. package/bin/lean/integration.test.mjs +98 -0
  51. package/bin/lean/issuewatch-parity.mjs +64 -0
  52. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  53. package/bin/lean/issuewatch-release.test.mjs +1 -1
  54. package/bin/lean/issuewatch.mjs +34 -5
  55. package/bin/lean/issuewatch.test.mjs +3 -2
  56. package/bin/lean/lean.mjs +316 -74
  57. package/bin/lean/lean.test.mjs +397 -24
  58. package/bin/lean/mechfix.mjs +124 -0
  59. package/bin/lean/mechfix.test.mjs +75 -0
  60. package/bin/lean/orchestrate.mjs +20 -2
  61. package/bin/lean/phaseledger.mjs +47 -5
  62. package/bin/lean/phaseledger.test.mjs +30 -1
  63. package/bin/lean/precheck.mjs +23 -4
  64. package/bin/lean/precheck.test.mjs +14 -1
  65. package/bin/lean/prereq.mjs +28 -0
  66. package/bin/lean/prereq.test.mjs +20 -0
  67. package/bin/lean/probe.mjs +4 -2
  68. package/bin/lean/prodparity.mjs +52 -0
  69. package/bin/lean/prodparity.test.mjs +67 -0
  70. package/bin/lean/prompts.mjs +69 -12
  71. package/bin/lean/recovery.test.mjs +1 -1
  72. package/bin/lean/release-io.test.mjs +42 -0
  73. package/bin/lean/release-postmerge.mjs +6 -0
  74. package/bin/lean/release-preflight.mjs +58 -0
  75. package/bin/lean/release-preflight.test.mjs +114 -0
  76. package/bin/lean/release-rehearsal.mjs +8 -7
  77. package/bin/lean/release-review.mjs +67 -11
  78. package/bin/lean/release-review.test.mjs +128 -1
  79. package/bin/lean/release-snapshot.mjs +188 -0
  80. package/bin/lean/release-snapshot.test.mjs +190 -0
  81. package/bin/lean/release.mjs +80 -12
  82. package/bin/lean/release.test.mjs +95 -0
  83. package/bin/lean/render.mjs +1 -1
  84. package/bin/lean/replan.mjs +184 -0
  85. package/bin/lean/replan.test.mjs +110 -0
  86. package/bin/lean/resume.mjs +9 -7
  87. package/bin/lean/resume.test.mjs +16 -0
  88. package/bin/lean/schedd.mjs +34 -1
  89. package/bin/lean/schedd.test.mjs +21 -1
  90. package/bin/lean/selfreview.mjs +94 -0
  91. package/bin/lean/selfreview.test.mjs +58 -1
  92. package/bin/lean/selftest-gate.mjs +22 -0
  93. package/bin/lean/selftest-gate.test.mjs +18 -1
  94. package/bin/lean/selftest-journey.mjs +234 -0
  95. package/bin/lean/selftest-journey.test.mjs +130 -0
  96. package/bin/lean/selftest-live.mjs +2 -1
  97. package/bin/lean/seqlease.mjs +35 -1
  98. package/bin/lean/seqlease.test.mjs +15 -0
  99. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  100. package/bin/lean/seqreserve.mjs +73 -0
  101. package/bin/lean/seqreserve.test.mjs +134 -0
  102. package/bin/lean/sequence.mjs +35 -6
  103. package/bin/lean/seqversioned.mjs +147 -0
  104. package/bin/lean/stagestamp.mjs +28 -0
  105. package/bin/lean/stagestamp.test.mjs +32 -0
  106. package/bin/lean/surfaces.mjs +75 -0
  107. package/bin/lean/surfaces.test.mjs +59 -0
  108. package/bin/lean/toolplace.mjs +28 -0
  109. package/bin/lean/toolplace.test.mjs +24 -0
  110. package/bin/lean/toolstats.mjs +3 -1
  111. package/bin/lean/toolstats.test.mjs +11 -0
  112. package/bin/lean/validatebest.mjs +28 -0
  113. package/bin/lean/validatebest.test.mjs +27 -0
  114. package/bin/pool/agent.mjs +9 -0
  115. package/bin/pool/docker.mjs +5 -0
  116. package/bin/pool/router.mjs +8 -4
  117. package/bin/prereqs.mjs +111 -0
  118. package/bin/replay-timelapse.mjs +149 -0
  119. package/bin/review-staging.mjs +100 -16
  120. package/bin/review-staging.test.mjs +18 -0
  121. package/bin/runner.mjs +43 -6
  122. package/bin/splash-install.mjs +157 -0
  123. package/bin/stats/aggregate.mjs +8 -1
  124. package/bin/stats/conformance-outcomes.mjs +100 -19
  125. package/bin/stats/conformance-outcomes.test.mjs +87 -1
  126. package/bin/stats/depth.mjs +88 -31
  127. package/bin/stats/depth.test.mjs +63 -38
  128. package/bin/stats/efficiency.mjs +26 -5
  129. package/bin/stats/efficiency.test.mjs +45 -1
  130. package/bin/stats/first-review.mjs +77 -0
  131. package/bin/stats/first-review.test.mjs +36 -0
  132. package/bin/stats/firstmerge.mjs +40 -0
  133. package/bin/stats/firstmerge.test.mjs +41 -0
  134. package/bin/stats/github-source.mjs +51 -13
  135. package/bin/stats/index.mjs +91 -15
  136. package/bin/stats/local-source.mjs +1 -0
  137. package/bin/stats/origin.mjs +80 -0
  138. package/bin/stats/origin.test.mjs +58 -0
  139. package/bin/stats/render.mjs +3 -1
  140. package/bin/stats/scoreboard.mjs +137 -0
  141. package/bin/stats/scoreboard.test.mjs +87 -0
  142. package/bin/stats/stats.test.mjs +80 -0
  143. package/bin/tui.mjs +3 -2
  144. package/commands/bootstrap.md +15 -14
  145. package/commands/deploy-pr.md +18 -3
  146. package/commands/forge-stats.md +1 -1
  147. package/commands/forgedock-ci-setup.md +28 -0
  148. package/commands/forgedock-init.md +4 -5
  149. package/commands/issue.md +2 -0
  150. package/commands/milestone.md +9 -1
  151. package/commands/replay.md +2 -0
  152. package/commands/review-pr-staging.md +4 -1
  153. package/commands/work-on/close.md +8 -0
  154. package/docs/CONFIG.md +105 -10
  155. package/docs/ISSUE-WATCH.md +23 -0
  156. package/docs/OUTCOME-CODES.md +1 -0
  157. package/docs/REPLAY.md +9 -0
  158. package/docs/SELFTEST.md +11 -0
  159. package/docs/STATS.md +19 -2
  160. package/docs/eval/README.md +6 -0
  161. package/docs/eval/adversarial-bench.md +68 -0
  162. package/docs/eval/corpus/adversarial-v1.json +285 -0
  163. package/docs/eval/feature-bench.md +42 -0
  164. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  165. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  166. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  167. package/docs/site/start-a-new-project.md +2 -1
  168. package/package.json +5 -2
  169. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  170. package/plugins/forgedock-splash/README.md +27 -0
  171. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  172. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  173. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  174. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  175. package/scripts/bench-adversarial.mjs +216 -0
  176. package/scripts/bench-feature.mjs +170 -0
  177. package/scripts/bench-lightlane.mjs +2 -2
  178. package/scripts/bootstrap-create.mjs +2 -2
  179. package/scripts/bootstrap-validate.mjs +35 -2
  180. package/scripts/check-spec-size.sh +4 -3
  181. package/scripts/check-spec-size.test.sh +3 -0
  182. package/scripts/plan-validate-live.mjs +40 -6
  183. package/scripts/review-pr-staging-scope.test.sh +1 -1
  184. package/scripts/review-staging-post.sh +23 -0
  185. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,135 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5235 end-to-end replay of the AlterLab 0616/v23 collisions (batch b20261107-065813-1951070) through runCore on a
5
+ * disposable REAL git repo (bare origin, clone, lane worktree, real commits, real --no-ff merge). GitHub is in-memory.
6
+ * While the lane builds, a sibling lane merges its own 0616 migration and v23 backup-contracts into staging; the lane
7
+ * must be renumbered (0617 / v24, companion rewritten), re-validated and merged without needs-human.
8
+ */
9
+ import { describe, it } from "node:test";
10
+ import assert from "node:assert/strict";
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { execFileSync, spawnSync } from "node:child_process";
14
+ import { tmpDir } from "../tests/_tmp.mjs";
15
+ import { runCore } from "./lean.mjs";
16
+ import { makeLeanIo } from "./effects.mjs";
17
+ import { reserveForBuild } from "./seqreserve.mjs";
18
+
19
+ const GIT_ENV = { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@example.invalid", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@example.invalid", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" };
20
+ const git = (args, cwd) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: GIT_ENV });
21
+ const HAVE_GIT = spawnSync("git", ["--version"]).status === 0;
22
+ const writeAll = (root, files) => { for (const [p, c] of Object.entries(files)) { fs.mkdirSync(path.dirname(path.join(root, p)), { recursive: true }); fs.writeFileSync(path.join(root, p), c); } };
23
+
24
+ const ISSUE = { number: 7, title: "Add a backup contract and a migration", body: "## Requirements\n1. Add a new migration and a new backup-contracts version.\n" };
25
+ const BASE = { "package.json": '{ "name": "f", "type": "module", "private": true }\n', "db/0614_z.sql": "select 0;\n", "db/0615_a.sql": "select 1;\n", "scripts/backup-contracts/v22/c.json": "{}\n", "src/version.ts": "export const VERSION = 22;\n" };
26
+ const VERSIONED = [{ dir: "scripts/backup-contracts", pattern: "scripts/backup-contracts/v{N}", companions: ["src/version.ts=VERSION = {N}"] }];
27
+ const V1 = "node -e \"process.exit(require('fs').readdirSync('db').some((f)=>f.endsWith('_lane.sql'))?0:1)\""; // numbering-independent: it must pass before and after the renumber
28
+
29
+ function makeWorld(dir) {
30
+ const origin = path.join(dir, "origin.git"), repo = path.join(dir, "repo"), merger = path.join(dir, "merger");
31
+ git(["init", "-q", "--bare", "-b", "main", origin], dir);
32
+ git(["clone", "-q", origin, repo], dir);
33
+ writeAll(repo, BASE);
34
+ git(["add", "-A"], repo); git(["commit", "-q", "-m", "base"], repo);
35
+ git(["push", "-q", "origin", "main"], repo); git(["push", "-q", "origin", "main:staging"], repo); git(["fetch", "-q", "origin"], repo);
36
+ git(["clone", "-q", origin, merger], dir);
37
+ const gh = { issue: { ...ISSUE, state: "OPEN", labels: new Set(), comments: [] }, prs: [] };
38
+ const sibling = () => {
39
+ git(["checkout", "-q", "-B", "staging", "origin/staging"], merger);
40
+ writeAll(merger, { "db/0616_sibling.sql": "select 3;\n", "scripts/backup-contracts/v23/c.json": '{"sib":1}\n', "src/version.ts": "export const VERSION = 23;\n" });
41
+ git(["add", "-A"], merger); git(["commit", "-q", "-m", "sibling lane merged"], merger); git(["push", "-q", "origin", "staging"], merger);
42
+ };
43
+ let n = 0;
44
+ const io = {
45
+ gh: async (a) => {
46
+ const k = a.slice(0, 2).join(" "), val = (f) => a[a.indexOf(f) + 1];
47
+ if (a[0] === "api") return "";
48
+ if (k === "repo view") return "main\n";
49
+ if (k === "issue view" && a.includes("milestone")) return JSON.stringify({ milestone: null });
50
+ if (k === "issue view") return JSON.stringify({ number: 7, title: ISSUE.title, body: ISSUE.body, state: gh.issue.state, comments: [] });
51
+ if (k === "issue comment") { gh.issue.comments.push(val("--body")); return "https://github.com/o/r/issues/7#c1\n"; }
52
+ if (k === "issue edit") { for (let i = 0; i < a.length; i++) { if (a[i] === "--add-label") a[i + 1].split(",").forEach((l) => gh.issue.labels.add(l)); if (a[i] === "--remove-label") a[i + 1].split(",").forEach((l) => gh.issue.labels.delete(l)); } return ""; }
53
+ if (k === "issue close") { gh.issue.state = "CLOSED"; return ""; }
54
+ if (k === "pr list") return "[]";
55
+ if (k === "pr create") { const p = { number: 300, base: val("--base"), head: val("--head"), state: "OPEN" }; gh.prs.push(p); return "https://github.com/o/r/pull/300\n"; }
56
+ if (k === "pr view") { // GitHub's answer, computed from the real branches: the sibling's v23 makes the lane CONFLICTING
57
+ git(["fetch", "-q", "origin"], merger);
58
+ const p = gh.prs[0];
59
+ const clean = spawnSync("git", ["merge-tree", "--write-tree", `origin/${p.base}`, `origin/${p.head}`], { cwd: merger, env: GIT_ENV }).status === 0;
60
+ return JSON.stringify(clean ? { mergeable: "MERGEABLE", mergeStateStatus: "CLEAN" } : { mergeable: "CONFLICTING", mergeStateStatus: "DIRTY" });
61
+ }
62
+ if (k === "pr merge") {
63
+ const p = gh.prs[0];
64
+ git(["fetch", "-q", "origin"], merger);
65
+ git(["checkout", "-q", "-B", p.base, `origin/${p.base}`], merger);
66
+ git(["merge", "-q", "--no-ff", "-m", "Merge PR #300", `origin/${p.head}`], merger);
67
+ git(["push", "-q", "origin", p.base], merger);
68
+ p.state = "MERGED"; return "";
69
+ }
70
+ throw new Error(`unexpected gh ${a.join(" ")}`);
71
+ },
72
+ git: async (args, { cwd } = {}) => git(args, cwd ?? repo),
73
+ runner: async (c) => {
74
+ n++;
75
+ if (c.role !== "builder") {
76
+ const rv = { verdict: "CONFORMS", summary: "ok", issue_coverage: [{ quote: "Add a new migration and a new backup-contracts version.", status: "covered" }],
77
+ requirements: [{ id: "R1", status: "implemented", evidence: "src/version.ts:1", validated_by: "V1" }],
78
+ scope: ["db/0617_lane.sql", "scripts/backup-contracts/v24/c.json", "src/version.ts"].map((f) => ({ file: f, authorized_by: "D1" })), preserve: [], regressions: [] };
79
+ return { text: "```json\n" + JSON.stringify({ ...rv, fixes_issue: true, regression: false, reason: "ok", verdict_pass: true }) + "\n```", sessionId: "s", usage: { input_tokens: 1, output_tokens: 1 }, costUsd: 0, durationMs: 1, turns: 1, model: "m" };
80
+ }
81
+ const lean = (name, v) => writeAll(c.cwd, { [`.forge-lean/${name}`]: typeof v === "string" ? v : JSON.stringify(v) });
82
+ const nb = ++io.builders;
83
+ if (nb === 1) {
84
+ lean("investigation.md", "**Verdict**: CONFIRMED\n**Confidence**: high\n**Severity**: high\n**Task Type**: feature\n\n### Root Cause\nmissing");
85
+ lean("contract.json", { requirements: [{ id: "R1", quote: "Add a new migration and a new backup-contracts version.", disposition: "deliver" }],
86
+ deliverables: [{ id: "D1", path: "db/0616_lane.sql", change: "migration", requirements: ["R1"] }, { id: "D2", path: "scripts/backup-contracts/v23/c.json", change: "contract", requirements: ["R1"] }, { id: "D3", path: "src/version.ts", change: "bump", requirements: ["R1"] }],
87
+ preserve: [], validate: [{ id: "V1", command: V1 }] });
88
+ } else if (nb === 2) {
89
+ writeAll(c.cwd, { "db/0616_lane.sql": "select 2;\n", "scripts/backup-contracts/v23/c.json": '{"lane":1}\n', "src/version.ts": "export const VERSION = 23;\n" });
90
+ git(["add", "-A"], c.cwd); git(["commit", "-q", "-m", "feat: migration + contract"], c.cwd);
91
+ sibling(); // the sibling lane merges the same 0616 / v23 while this lane builds
92
+ lean("implementation.md", "### Approach\nadd\n\n### Changes\n- db/0616_lane.sql\n\n### Acceptance Criteria Status\n- R1\n\n### Verification\n- none\n\n### Notes\nnone");
93
+ lean("result.json", { status: "fixed", summary: "added", requirements: [{ id: "R1", status: "implemented", evidence: "db/0616_lane.sql:1" }], validation: [{ id: "V1", command: V1, exit: 0 }], amendments: [] });
94
+ }
95
+ return { text: "done", sessionId: "s", usage: { input_tokens: 1, output_tokens: 1 }, costUsd: 0, durationMs: 1, turns: 1, model: "m" };
96
+ },
97
+ builders: 0,
98
+ reservations: [],
99
+ // the real build-start reservation (reserveForBuild on the lane worktree's git); only the host lease store is an in-memory counter
100
+ sequenceReserveBuild: async ({ cwd, base, deliverables, versioned }) => {
101
+ const rs = await reserveForBuild({ git: async (a) => git(a, cwd), base, deliverables, versioned, reserve: async ({ floor, count }) => ({ numbers: Array.from({ length: count }, (_, i) => floor + 1 + i) }) });
102
+ io.reservations.push(...rs); return rs;
103
+ },
104
+ // the engine's real sequence effects (check, snapshot, renumber, verify, base-sync resolve); the host lease store stays out of the test
105
+ ...Object.fromEntries(Object.entries(makeLeanIo({ repo: "o/r" })).filter(([k]) => /^sequence(Check|Snapshot|Verify|Renumber|Resolve)$/.test(k))),
106
+ transitionLabel: async () => {},
107
+ requiredChecks: async () => [],
108
+ fileFollowups: async () => ({}),
109
+ fs: { read: async (p) => fs.readFileSync(p, "utf8"), stat: async (p) => fs.statSync(p), append: async (p, t) => fs.appendFileSync(p, t), write: async (p, t) => fs.writeFileSync(p, t),
110
+ exists: async (p) => fs.existsSync(p), rmdir: async (p) => fs.rmSync(p, { recursive: true, force: true }) },
111
+ };
112
+ return { io, repo, merger, gh };
113
+ }
114
+
115
+ describe("#5235 e2e: 0616/v23 replay through runCore (real git)", { skip: !HAVE_GIT && "git not available" }, () => {
116
+ it("renumbers to 0617/v24, revalidates, merges without needs-human", async () => {
117
+ // the engine's real effects spawn git with process.env, so a CI host without a global git identity needs it there too
118
+ const saved = {}; for (const k of Object.keys(GIT_ENV)) if (/^GIT_/.test(k)) { saved[k] = process.env[k]; process.env[k] = GIT_ENV[k]; }
119
+ const restore = () => { for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } };
120
+ try {
121
+ const dir = tmpDir("seq-e2e-"), w = makeWorld(dir);
122
+ const ret = await runCore({ issue: 7, repo: "o/r", lane: "staging", cwd: w.repo, worktreeRoot: path.join(dir, "wt"), dir: path.join(dir, "runs"), io: w.io, random: () => 0.5, stableMs: 0, livePollMs: 20, sequenceVersioned: VERSIONED });
123
+ assert.equal(ret.terminalReason, "merged", JSON.stringify(ret));
124
+ assert.ok(!w.gh.issue.labels.has("needs-human"));
125
+ assert.ok(w.io.reservations.some((r) => r.kind === "numbered" && r.numbers.includes(616)) && w.io.reservations.some((r) => r.kind === "versioned" && r.numbers.includes(23)), JSON.stringify(w.io.reservations));
126
+ git(["fetch", "-q", "origin"], w.merger);
127
+ const at = (p) => git(["show", `origin/staging:${p}`], w.merger);
128
+ assert.equal(at("scripts/backup-contracts/v23/c.json"), '{"sib":1}\n');
129
+ assert.equal(at("scripts/backup-contracts/v24/c.json"), '{"lane":1}\n');
130
+ assert.match(at("src/version.ts"), /VERSION = 24/);
131
+ assert.equal(at("db/0617_lane.sql"), "select 2;\n");
132
+ assert.equal(at("db/0616_sibling.sql"), "select 3;\n");
133
+ } finally { restore(); }
134
+ });
135
+ });
@@ -0,0 +1,73 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Build-start number reservation (#5235). The #4386/#4526 reservation covers numbers at renumber time; a builder still picks
5
+ * its migration number or `vN` dir from its own base snapshot, so siblings collide and are renumbered after validation ran.
6
+ * `reserveForBuild` reserves, before the build, one number per numbered series dir (and one version per configured versioned
7
+ * class) that the frozen contract's deliverables touch, above the base, the other open PRs and every live sibling
8
+ * reservation (`seqlease.reserve`); `sequenceBuildNote` tells the builder which. `revalidate` reruns the frozen validate
9
+ * commands after a renumber. Fail-open: any error means no reservation and the late bind stays the gate.
10
+ */
11
+ import { posix } from "node:path";
12
+ import { baseSeries, seqNumber } from "./sequence.mjs";
13
+ import { maxVersion, parseVersioned } from "./seqversioned.mjs";
14
+
15
+ const MAX_DIRS = 8;
16
+
17
+ /**
18
+ * @param {object} o `git(args)` in the lane worktree; `base` ref; `deliverables` the frozen contract's rows; `versioned` the
19
+ * configured classes; `reserve({dir, floor, count})`; `openNumbers({dir})` / `openVersions({cls})` numbers other open PRs carry.
20
+ * @returns {Promise<Array<{kind:"numbered"|"versioned", dir:string, numbers:number[], width?:number, cls?:string}>>}
21
+ */
22
+ export async function reserveForBuild({ git, base, deliverables = [], versioned = [], reserve, openNumbers = null, openVersions = null }) {
23
+ const res = [];
24
+ if (!reserve) return res;
25
+ try {
26
+ await git(["rev-parse", "--verify", "-q", base]); // an unreadable base must not reserve from a floor of 0
27
+ const paths = (deliverables ?? []).map((d) => String(d?.path ?? "")).filter(Boolean);
28
+ const classes = parseVersioned(versioned);
29
+ for (const c of classes) {
30
+ if (!paths.some((p) => c.dir ? p.startsWith(`${c.dir}/`) : true)) continue;
31
+ let floor = await maxVersion({ git, ref: base, cls: c });
32
+ if (openVersions) { try { floor = Math.max(floor, ...(await openVersions({ cls: c })).map(Number).filter(Number.isFinite)); } catch { /* fail-open */ } }
33
+ const got = await reserve({ dir: c.pattern, floor, count: 1 });
34
+ const numbers = Array.isArray(got?.numbers) ? got.numbers.map(Number).filter(Number.isInteger) : [];
35
+ if (numbers.length) res.push({ kind: "versioned", dir: c.dir, cls: c.pattern, numbers });
36
+ }
37
+ const dirs = [...new Set(paths.map((p) => posix.dirname(p)))].filter((d) => !classes.some((c) => d === c.dir || d.startsWith(`${c.dir}/`))).slice(0, MAX_DIRS);
38
+ for (const dir of dirs) {
39
+ const s = await baseSeries({ git, ref: base, dir });
40
+ if (!s.series) continue;
41
+ const count = Math.min(5, Math.max(1, paths.filter((p) => posix.dirname(p) === dir && (seqNumber(p) || /\.sql$/i.test(p))).length));
42
+ let floor = s.max;
43
+ if (openNumbers) { try { floor = Math.max(floor, ...(await openNumbers({ dir })).map(Number).filter(Number.isFinite)); } catch { /* fail-open */ } }
44
+ const got = await reserve({ dir, floor, count });
45
+ const numbers = Array.isArray(got?.numbers) ? got.numbers.map(Number).filter(Number.isInteger) : [];
46
+ if (numbers.length === count) res.push({ kind: "numbered", dir, numbers, width: s.width });
47
+ }
48
+ } catch { /* fail-open */ }
49
+ return res;
50
+ }
51
+
52
+ /** The builder-prompt paragraph for `reserveForBuild`'s result; "" when nothing was reserved. */
53
+ export function sequenceBuildNote(reservations = []) {
54
+ const rows = (reservations ?? []).map((r) => (r.kind === "versioned"
55
+ ? `- ${r.cls}: the next version is v${r.numbers[0]} (create ${posix.join(r.dir, `v${r.numbers[0]}`)}/; never reuse a version the base already has) and update the files that reference the version`
56
+ : `- ${r.dir}/: use ${r.numbers.map((n) => String(n).padStart(r.width ?? 0, "0")).join(", ")} for the new numbered file${r.numbers.length > 1 ? "s, in order" : ""} (do not derive the number from the files you see)`));
57
+ return rows.length ? `\n\nSequence numbers reserved for this lane (sibling lanes on the same branch hold the others; the engine renumbers anything else after the fact):\n${rows.join("\n")}` : "";
58
+ }
59
+
60
+ /**
61
+ * Rerun the frozen validate commands after a renumber. `runOne(validate)` -> {rc, output}.
62
+ * @returns {Promise<Array<{id:string, rc:number, output:string}>>} the failures
63
+ */
64
+ export async function revalidate({ validates = [], runOne }) {
65
+ const failed = [];
66
+ for (const v of validates ?? []) {
67
+ if (!v?.command || !runOne) continue;
68
+ let x;
69
+ try { x = await runOne(v); } catch (e) { x = { rc: 127, output: String(e?.message ?? e) }; }
70
+ if (x && Number.isInteger(x.rc) && x.rc !== 0) failed.push({ id: v.id, rc: x.rc, output: String(x.output ?? "") });
71
+ }
72
+ return failed;
73
+ }
@@ -0,0 +1,134 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // Build-start reservation, versioned-dir classes and the post-renumber revalidate (#5235).
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { execFileSync } from "node:child_process";
7
+ import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
8
+ import { dirname, join } from "node:path";
9
+ import { tmpDir } from "../tests/_tmp.mjs";
10
+ import { reserveForBuild, sequenceBuildNote, revalidate } from "./seqreserve.mjs";
11
+ import { sequenceCollisions, renumberLane, snapshotLane, verifyRenumber } from "./sequence.mjs";
12
+ import { makeSequenceLeaseIo } from "./seqlease.mjs";
13
+ import { sequenceBuildRule } from "./prompts.mjs";
14
+ // R4: V1 runs the real-git runCore 0616/v23 replay.
15
+ import "./seqreserve.e2e.test.mjs";
16
+ // The real-git runCore replay (R4) is part of this file's run, so the frozen V1 executes it.
17
+ import "./seqreserve.e2e.test.mjs";
18
+
19
+ const sh = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } });
20
+ const gitIn = (cwd) => async (a) => sh(cwd, ...a);
21
+ const put = (root, files) => { for (const [p, t] of Object.entries(files)) { mkdirSync(dirname(join(root, p)), { recursive: true }); writeFileSync(join(root, p), t); } };
22
+ const commit = (d, m) => { sh(d, "add", "-A"); sh(d, "commit", "-qm", m); };
23
+ const VERSIONED = "scripts/backup-contracts/v{N} -> src/version.ts=VERSION = {N}";
24
+
25
+ /** main: migrations up to 0615, backup-contracts up to v22; a lane on top of it. */
26
+ function repo() {
27
+ const d = tmpDir("seqres-");
28
+ sh(d, "init", "-q", "-b", "main");
29
+ put(d, { "db/0614_z.sql": "select 0;\n", "db/0615_a.sql": "select 1;\n", "scripts/backup-contracts/v22/c.json": "{}\n", "src/version.ts": "export const VERSION = 22;\n" });
30
+ commit(d, "init");
31
+ return d;
32
+ }
33
+
34
+ /** An in-memory stand-in for seqlease.reserve: distinct numbers per (dir) above the floor. */
35
+ const memLease = () => { const top = new Map(); return async ({ dir, floor, count }) => { const s = Math.max(top.get(dir) ?? 0, floor); top.set(dir, s + count); return { numbers: Array.from({ length: count }, (_, i) => s + 1 + i) }; }; };
36
+
37
+ describe("reserveForBuild (#5235)", () => {
38
+ const deliverables = [{ path: "db/0616_x.sql" }, { path: "scripts/backup-contracts/v23/c.json" }];
39
+ it("two lanes on one branch receive distinct numbers and versions before building", async () => {
40
+ const d = repo(), reserve = memLease(), git = gitIn(d);
41
+ const a = await reserveForBuild({ git, base: "main", deliverables, versioned: VERSIONED, reserve });
42
+ const b = await reserveForBuild({ git, base: "main", deliverables, versioned: VERSIONED, reserve });
43
+ const num = (r, k) => r.find((x) => x.kind === k).numbers[0];
44
+ assert.equal(num(a, "numbered"), 616); assert.equal(num(b, "numbered"), 617);
45
+ assert.equal(num(a, "versioned"), 23); assert.equal(num(b, "versioned"), 24);
46
+ });
47
+ it("floors above the numbers other open PRs carry", async () => {
48
+ const d = repo();
49
+ const r = await reserveForBuild({ git: gitIn(d), base: "main", deliverables, versioned: VERSIONED, reserve: memLease(), openNumbers: async () => [616, 617], openVersions: async () => [23] });
50
+ assert.equal(r.find((x) => x.kind === "numbered").numbers[0], 618);
51
+ assert.equal(r.find((x) => x.kind === "versioned").numbers[0], 24);
52
+ });
53
+ it("is fail-open: a throwing reserve or git yields no reservation; no series, no note", async () => {
54
+ const d = repo();
55
+ assert.deepEqual(await reserveForBuild({ git: gitIn(d), base: "main", deliverables, reserve: async () => { throw new Error("x"); } }), []);
56
+ assert.deepEqual(await reserveForBuild({ git: async () => { throw new Error("x"); }, base: "main", deliverables, versioned: VERSIONED, reserve: memLease() }), []);
57
+ assert.deepEqual(await reserveForBuild({ git: gitIn(d), base: "main", deliverables: [{ path: "README.md" }], reserve: memLease() }), []);
58
+ assert.equal(sequenceBuildRule([]), "");
59
+ });
60
+ it("the build note names the reserved number and version", async () => {
61
+ const d = repo();
62
+ const note = sequenceBuildRule(await reserveForBuild({ git: gitIn(d), base: "main", deliverables, versioned: VERSIONED, reserve: memLease() }));
63
+ assert.match(note, /db\/: use 0616/); assert.match(note, /v23/);
64
+ });
65
+ });
66
+
67
+ describe("versioned class collisions and renumber (#5235)", () => {
68
+ /** The AlterLab replay: lane adds 0616 + v23; a sibling merges the same into main. */
69
+ function replay() {
70
+ const d = repo();
71
+ sh(d, "checkout", "-qb", "lane");
72
+ put(d, { "db/0616_lane.sql": "select 2;\n", "scripts/backup-contracts/v23/c.json": '{"lane":1}\n', "src/version.ts": "export const VERSION = 23;\n" });
73
+ commit(d, "lane");
74
+ sh(d, "checkout", "-q", "main");
75
+ put(d, { "db/0616_sibling.sql": "select 3;\n", "scripts/backup-contracts/v23/c.json": '{"sib":1}\n', "src/version.ts": "export const VERSION = 23;\n" });
76
+ commit(d, "sibling");
77
+ sh(d, "checkout", "-q", "lane");
78
+ return d;
79
+ }
80
+ it("detects the lane's v23 colliding with the base's", async () => {
81
+ const d = replay();
82
+ const cols = await sequenceCollisions({ git: gitIn(d), base: "main", versioned: VERSIONED });
83
+ assert.ok(cols.some((c) => /v23/.test(c.lane)), JSON.stringify(cols));
84
+ });
85
+ it("0616/v23 replay: renumbered deterministically, companion rewritten, collisions gone", async () => {
86
+ const d = replay();
87
+ const r = await renumberLane({ git: gitIn(d), base: "main", cwd: d, versioned: VERSIONED, reserve: null });
88
+ assert.ok(r.ok, JSON.stringify(r));
89
+ assert.ok(existsSync(join(d, "scripts/backup-contracts/v24/c.json")));
90
+ assert.equal(readFileSync(join(d, "scripts/backup-contracts/v23/c.json"), "utf8"), '{"sib":1}\n');
91
+ assert.equal(readFileSync(join(d, "scripts/backup-contracts/v24/c.json"), "utf8"), '{"lane":1}\n');
92
+ assert.match(readFileSync(join(d, "src/version.ts"), "utf8"), /VERSION = 24/);
93
+ assert.ok(existsSync(join(d, "db/0617_lane.sql")));
94
+ assert.deepEqual(await sequenceCollisions({ git: gitIn(d), base: "main", versioned: VERSIONED }), []);
95
+ });
96
+ it("e2e: the hand-off gate (check, snapshot, renumber, verify) passes on the replay, so no needs-human", async () => {
97
+ const d = replay(), git = gitIn(d);
98
+ assert.ok((await sequenceCollisions({ git, base: "main", versioned: VERSIONED })).length >= 2);
99
+ const before = await snapshotLane({ git, base: "main" });
100
+ const r = await renumberLane({ git, base: "main", cwd: d, versioned: VERSIONED, reserve: null });
101
+ assert.ok(r.ok && r.moves.length >= 2, JSON.stringify(r));
102
+ const v = await verifyRenumber({ git, base: "main", before, moves: r.moves.filter((m) => !m.versioned), versioned: VERSIONED });
103
+ assert.ok(v.ok, JSON.stringify(v));
104
+ });
105
+ it("without versioned config nothing versioned is touched", async () => {
106
+ const d = replay();
107
+ const cols = await sequenceCollisions({ git: gitIn(d), base: "main" });
108
+ assert.ok(!cols.some((c) => /v23/.test(c.lane)));
109
+ });
110
+ });
111
+
112
+ describe("seqlease-backed reservation (#5235)", () => {
113
+ it("the real lease hands two lanes distinct numbers", async () => {
114
+ const d = repo(), lease = makeSequenceLeaseIo(), repoName = `t/${Date.now()}-${process.pid}`;
115
+ const mk = (issue) => reserveForBuild({ git: gitIn(d), base: "main", deliverables: [{ path: "db/0616_x.sql" }], reserve: (x) => lease.reserve({ repo: repoName, lane: "main", issue, ...x }) });
116
+ const [a, b] = [await mk(1), await mk(2)];
117
+ assert.notEqual(a[0]?.numbers[0], b[0]?.numbers[0]);
118
+ assert.ok(a[0].numbers[0] >= 616);
119
+ await lease.unreserve?.({ repo: repoName, lane: "main", issue: 1 }); await lease.unreserve?.({ repo: repoName, lane: "main", issue: 2 });
120
+ });
121
+ });
122
+
123
+ describe("revalidate after a renumber (#5235)", () => {
124
+ it("reruns every validate and returns the failures", async () => {
125
+ const ran = [];
126
+ const bad = await revalidate({ validates: [{ id: "V1", command: "a" }, { id: "V2", command: "b" }, { id: "V3" }], runOne: async (v) => { ran.push(v.id); return v.id === "V2" ? { rc: 1, output: "boom" } : { rc: 0, output: "" }; } });
127
+ assert.deepEqual(ran, ["V1", "V2"]);
128
+ assert.deepEqual(bad, [{ id: "V2", rc: 1, output: "boom" }]);
129
+ });
130
+ it("a throwing runner counts as a failure", async () => {
131
+ const bad = await revalidate({ validates: [{ id: "V1", command: "a" }], runOne: async () => { throw new Error("x"); } });
132
+ assert.equal(bad[0].rc, 127);
133
+ });
134
+ });
@@ -21,6 +21,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod
21
21
  import { tmpdir } from "node:os";
22
22
  import { basename, dirname, join, posix } from "node:path";
23
23
  import { promisify } from "node:util";
24
+ import { parseVersioned, renumberVersioned, versionedCollisions } from "./seqversioned.mjs";
24
25
 
25
26
  const NUM_RE = /^(\d{3,})[_-]/;
26
27
  const DATE_RE = /^(?:19|20)\d\d(-?)(?:0[1-9]|1[0-2])\1(?:0[1-9]|[12]\d|3[01])[_-]/;
@@ -56,12 +57,21 @@ async function seriesDir(g, ref, dir) {
56
57
  };
57
58
  }
58
59
 
60
+ /** #5235: whether `dir` holds a numbered series at `ref`, its highest number and width. @returns {Promise<{series:boolean, max:number, width:number}>} */
61
+ export async function baseSeries({ git, ref, dir }) {
62
+ const g = out(git), series = await seriesDir(g, ref, dir);
63
+ const nums = lines(await g(["-c", "core.quotepath=off", "ls-tree", "--name-only", ref, ...inDir(dir)])).filter((p) => dirname(p) === dir).map(numOf).filter(Boolean);
64
+ const width = Math.max(0, ...nums.map((n) => n.length));
65
+ return { series: width > 0 && series(width), max: Math.max(0, ...nums.map(Number)), width };
66
+ }
67
+
59
68
  /**
60
69
  * Collisions: in each directory where a lane-added numbered file shares its number with a different base file (another
61
70
  * name, or the same path with other content), every lane-added numbered file there must move, in order, above the base's
62
71
  * highest number. @returns {Promise<Array<{dir, number, lane, base:string[], next}>>} (base [] = moves only to keep order)
63
72
  */
64
- export async function sequenceCollisions({ git, base, ref = "HEAD" }) {
73
+ export async function sequenceCollisions({ git, base, ref = "HEAD", versioned = [] }) {
74
+ const more = versioned?.length ? await versionedCollisions({ git, base, ref, versioned }) : []; // #5235: versioned dirs (`<dir>/v{N}`)
65
75
  try {
66
76
  const g = out(git);
67
77
  const lane = await laneNumbered(git, base, ref);
@@ -81,8 +91,8 @@ export async function sequenceCollisions({ git, base, ref = "HEAD" }) {
81
91
  let next = Math.max(0, ...theirs.map((t) => Number(numOf(t.path))));
82
92
  for (const f of mine) res.push({ dir, number: numOf(f.path), lane: f.path, base: clash(f), next: String(++next).padStart(width, "0") });
83
93
  }
84
- return res;
85
- } catch { return []; }
94
+ return [...res, ...more];
95
+ } catch { return more; }
86
96
  }
87
97
 
88
98
  /**
@@ -181,10 +191,10 @@ function retitle(text, oldNum, newNum) {
181
191
  * `moves` ([{from,to}]) defaults to the pairing of recorded and current lane files by the name after the number.
182
192
  * @returns {Promise<{ok, problems}>}
183
193
  */
184
- export async function verifyRenumber({ git, base, before = [], moves = null }) {
194
+ export async function verifyRenumber({ git, base, before = [], moves = null, versioned = [] }) {
185
195
  try {
186
196
  const g = out(git), problems = [];
187
- const left = await sequenceCollisions({ git, base });
197
+ const left = await sequenceCollisions({ git, base, versioned });
188
198
  for (const c of left.filter((x) => x.base.length)) problems.push(`${c.lane} still shares number ${c.number} with ${c.base.join(", ")}`);
189
199
  const now = await laneNumbered(git, base);
190
200
  const rest = (p) => basename(p).slice(numOf(p).length);
@@ -301,7 +311,26 @@ const writeJson = (p, o) => writeFileSync(p, `${JSON.stringify(o, null, 2)}\n`);
301
311
  * where it started. Never throws.
302
312
  * @returns {Promise<{ok:true, moves:Array<{from,to}>, commit:string|null}|{unsupported:string, nonSequence?:string[]}>}
303
313
  */
304
- export async function renumberLane({ git, base, cwd, laneRef = "HEAD", regenerate = null, regenerateCustom = null, run = null, uuid = randomUUID, reserve = null, openNumbers = null }) {
314
+ export async function renumberLane({ versioned = [], ...o }) {
315
+ let r = await renumberNumbered(o);
316
+ if (r.unsupported && versioned?.length && r.nonSequence?.length) {
317
+ // #5235: base-merge conflicts only inside versioned dirs: the versioned pass takes the base side, then the numbered pass reruns
318
+ const cls = parseVersioned(versioned), inCls = (f) => cls.some((c) => (!c.dir || f.startsWith(`${c.dir}/`)) && c.re.test(posix.relative(c.dir || ".", f).split("/")[0]));
319
+ if (r.nonSequence.every(inCls)) {
320
+ const pre = await renumberVersioned({ git: o.git, base: o.base, cwd: o.cwd, laneRef: o.laneRef ?? "HEAD", versioned, reserve: o.reserve ? (x) => o.reserve({ ...x }) : null });
321
+ if (pre.unsupported) return pre;
322
+ const r2 = await renumberNumbered({ ...o, laneRef: "HEAD" });
323
+ return r2.unsupported ? r2 : { ...r2, ok: true, moves: [...(r2.moves ?? []), ...pre.moves], commit: r2.commit ?? pre.commit ?? null };
324
+ }
325
+ }
326
+ if (r.unsupported || !versioned?.length) return r;
327
+ // #5235: versioned dirs after the numbered files (the base is merged by then); a failure leaves the numbered commit in place
328
+ const v = await renumberVersioned({ git: o.git, base: o.base, cwd: o.cwd, laneRef: o.laneRef ?? "HEAD", versioned, reserve: o.reserve ? (x) => o.reserve({ ...x }) : null });
329
+ if (v.unsupported) return v;
330
+ return { ...r, ok: true, moves: [...(r.moves ?? []), ...v.moves], commit: v.commit ?? r.commit ?? null };
331
+ }
332
+
333
+ async function renumberNumbered({ git, base, cwd, laneRef = "HEAD", regenerate = null, regenerateCustom = null, run = null, uuid = randomUUID, reserve = null, openNumbers = null }) {
305
334
  const custom = regenerateCustom ?? (regenerate ? `${regenerate} --custom` : null);
306
335
  const g = out(git);
307
336
  const start = (await g(["rev-parse", "HEAD"])).trim();
@@ -0,0 +1,147 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Versioned-directory sequence class (#5235): `<dir>/v{N}/` directories (e.g. `scripts/backup-contracts/v{N}`) that are
5
+ * immutable once published, so two lanes adding the same version collide like two migrations with one number. Configured by
6
+ * forge.yaml `lean.sequence_versioned`: `<dir>/v{N} [= companion[, companion...]]; ...`. A companion is a file that
7
+ * references the version, as `path` (the class's name template, `v{N}`) or `path=template` (e.g. `src/version.ts=VERSION = {N}`).
8
+ * Detection (`versionedCollisions`) and the deterministic renumber (`renumberVersioned`) are git only and never throw.
9
+ */
10
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
11
+ import { dirname, join, posix } from "node:path";
12
+
13
+ const lines = (s) => String(s ?? "").split("\n").map((x) => x.trim()).filter(Boolean);
14
+ const esc = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15
+ const out = (git) => async (args) => { try { return String(await git(args)); } catch { return ""; } };
16
+
17
+ /** `scripts/x/v{N}` -> { dir, pattern, name: "v{N}", re } (null unless the last segment holds `{N}`). */
18
+ function classOf(pattern, companions = []) {
19
+ const p = String(pattern ?? "").trim().replace(/\/+$/, ""), name = posix.basename(p);
20
+ if (!name.includes("{N}")) return null;
21
+ const [pre, post] = name.split("{N}");
22
+ return { dir: posix.dirname(p) === "." ? "" : posix.dirname(p), pattern: p, name, companions, re: new RegExp(`^${esc(pre)}(\\d+)${esc(post)}$`) };
23
+ }
24
+
25
+ /** The configured classes from the flat string form or an already-parsed list ([{pattern, companions}]). */
26
+ export function parseVersioned(spec) {
27
+ const list = Array.isArray(spec) ? spec : String(spec ?? "").split(";").map((s) => s.trim()).filter(Boolean).map((s) => {
28
+ const i = s.indexOf("->"), pattern = (i < 0 ? s : s.slice(0, i)).trim(), rest = i < 0 ? "" : s.slice(i + 2);
29
+ return { pattern, companions: rest.split(",").map((x) => x.trim()).filter(Boolean) };
30
+ });
31
+ return list.map((c) => classOf(c.pattern ?? c.dir, c.companions ?? [])).filter(Boolean);
32
+ }
33
+
34
+ const versionDir = (c, n) => posix.join(c.dir, c.name.replace("{N}", String(n)));
35
+ const tokenOf = (c, tpl, n) => (tpl ?? c.name).replace("{N}", String(n));
36
+ const companion = (c, spec) => { const i = String(spec).indexOf("="); return i < 0 ? { path: String(spec).trim(), tpl: c.name } : { path: spec.slice(0, i).trim(), tpl: spec.slice(i + 1) }; };
37
+
38
+ /** version -> [{path, blob}] of every file under `<dir>/<name>` at `ref`. */
39
+ async function versionsAt(g, ref, c) {
40
+ const res = new Map();
41
+ for (const l of lines(await g(["-c", "core.quotepath=off", "ls-tree", "-r", ref, "--", ...(c.dir ? [`${c.dir}/`] : [])]))) {
42
+ const m = /^\d+\s+blob\s+(\S+)\t(.+)$/.exec(l);
43
+ if (!m) continue;
44
+ const seg = posix.relative(c.dir || ".", m[2]).split("/")[0], v = c.re.exec(seg)?.[1];
45
+ if (v) res.set(Number(v), [...(res.get(Number(v)) ?? []), { path: m[2], blob: m[1] }]);
46
+ }
47
+ return res;
48
+ }
49
+
50
+ /** The highest version of class `c` at `ref` (0 when none). */
51
+ export async function maxVersion({ git, ref, cls }) {
52
+ return Math.max(0, ...(await versionsAt(out(git), ref, cls)).keys());
53
+ }
54
+
55
+ /**
56
+ * Versions the lane added (base...ref) that the base already holds with other content, and the versions above them that must
57
+ * keep their order. @returns {Promise<Array<{dir, number, lane, base:string[], next, cls}>>} (`next` above the base's highest)
58
+ */
59
+ export async function versionedCollisions({ git, base, ref = "HEAD", versioned = [] }) {
60
+ const res = [];
61
+ try {
62
+ const g = out(git), classes = parseVersioned(versioned);
63
+ const added = new Set(lines(await g(["-c", "core.quotepath=off", "diff", "--name-only", "--diff-filter=A", `${base}...${ref}`])));
64
+ for (const c of classes) {
65
+ const mine = [...(await versionsAt(g, ref, c)).entries()].map(([v, fs]) => [v, fs.filter((f) => added.has(f.path))]).filter(([, fs]) => fs.length).sort((a, b) => a[0] - b[0]);
66
+ if (!mine.length) continue;
67
+ const theirs = await versionsAt(g, base, c);
68
+ const clash = ([v, fs]) => { const t = theirs.get(v) ?? []; return t.length && (t.length !== fs.length || t.some((x) => !fs.some((f) => f.path === x.path && f.blob === x.blob))); };
69
+ if (!mine.some(clash)) continue;
70
+ let next = Math.max(0, ...theirs.keys());
71
+ for (const m of mine) res.push({ dir: c.dir, number: String(m[0]), lane: versionDir(c, m[0]), base: clash(m) ? [versionDir(c, m[0])] : [], next: String(++next), cls: c.pattern });
72
+ }
73
+ } catch { /* detection is best effort */ }
74
+ return res;
75
+ }
76
+
77
+ /**
78
+ * Renumber the lane's colliding versioned dirs: the files move to the next free version (`reserve({dir, floor, count})` first,
79
+ * else base max + 1), the companions' references to the old version are rewritten on the lines the lane added, one commit.
80
+ * Conflicts of the base merge that lie only inside versioned dirs take the base side. Anything else: {unsupported}, branch reset.
81
+ * @returns {Promise<{ok:true, moves:Array<{from,to,versioned:true}>, commit:string|null}|{unsupported:string}>}
82
+ */
83
+ export async function renumberVersioned({ git, base, cwd, laneRef = "HEAD", versioned = [], reserve = null }) {
84
+ const g = out(git), classes = parseVersioned(versioned);
85
+ if (!classes.length) return { ok: true, moves: [], commit: null };
86
+ const start = (await g(["rev-parse", "HEAD"])).trim();
87
+ const fail = async (why) => {
88
+ try { await git(["merge", "--abort"]); } catch { /* none in progress */ }
89
+ try { await git(["reset", "-q", "--hard", start]); } catch { /* best effort */ }
90
+ return { unsupported: why };
91
+ };
92
+ try {
93
+ const lane = (await g(["rev-parse", laneRef])).trim() || start;
94
+ const cols = (await versionedCollisions({ git, base, ref: lane, versioned: classes }));
95
+ if (!cols.length) return { ok: true, moves: [], commit: null };
96
+ if (!(await git(["merge-base", "--is-ancestor", base, "HEAD"]).then(() => true, () => false))) {
97
+ try { await git(["merge", "--no-edit", base]); } catch {
98
+ const files = lines(await g(["-c", "core.quotepath=off", "diff", "--name-only", "--diff-filter=U"]));
99
+ const inClass = (f) => classes.some((c) => f.startsWith(`${c.dir ? `${c.dir}/` : ""}`) && c.re.test(posix.relative(c.dir || ".", f).split("/")[0]));
100
+ const rest = files.filter((f) => !inClass(f));
101
+ if (rest.length) return await fail(`non-versioned conflict: ${rest.join(", ")}`);
102
+ for (const f of files) { try { await git(["checkout", "--theirs", "--", f]); } catch { await git(["rm", "-q", "-f", "--", f]); } await git(["add", "--", f]); }
103
+ await git(["commit", "-q", "--no-edit"]);
104
+ }
105
+ }
106
+ const added = new Set(lines(await g(["-c", "core.quotepath=off", "diff", "--name-only", "--diff-filter=A", `${base}...${lane}`])));
107
+ const touched = new Set(), moves = [], renames = [];
108
+ for (const c of classes) {
109
+ const mine = cols.filter((x) => x.cls === c.pattern).sort((a, b) => Number(a.number) - Number(b.number));
110
+ if (!mine.length) continue;
111
+ let floor = await maxVersion({ git, ref: base, cls: c }), nums = null;
112
+ try { nums = (await reserve?.({ dir: c.pattern, floor, count: mine.length }))?.numbers?.map(Number); } catch { /* fail-open */ }
113
+ if (!(nums?.length === mine.length && nums.every(Number.isInteger))) nums = mine.map((_, i) => floor + 1 + i);
114
+ const have = await versionsAt(g, lane, c), baseHas = await versionsAt(g, base, c), head = new Set(lines(await g(["ls-files"])));
115
+ for (const [i, m] of [...mine.entries()].reverse()) {
116
+ const from = Number(m.number), to = nums[i];
117
+ for (const f of (have.get(from) ?? []).filter((x) => added.has(x.path))) {
118
+ const rel = posix.relative(versionDir(c, from), f.path), dest = posix.join(versionDir(c, to), rel);
119
+ const src = await g(["cat-file", "blob", f.blob]);
120
+ mkdirSync(dirname(join(cwd, dest)), { recursive: true });
121
+ writeFileSync(join(cwd, dest), src);
122
+ touched.add(dest);
123
+ if ((baseHas.get(from) ?? []).some((x) => x.path === f.path)) await git(["checkout", base, "--", f.path]);
124
+ else if (head.has(f.path)) await git(["rm", "-q", "-f", "--", f.path]);
125
+ }
126
+ moves.push({ from: versionDir(c, from), to: versionDir(c, to), versioned: true });
127
+ renames.push({ c, from, to });
128
+ }
129
+ }
130
+ // companions: the lane's own lines that name the old version
131
+ const mb = (await g(["merge-base", base, lane])).trim() || base;
132
+ for (const { c, from, to } of renames) {
133
+ for (const spec of c.companions) {
134
+ const { path, tpl } = companion(c, spec), p = join(cwd, path);
135
+ let text; try { text = readFileSync(p, "utf8"); } catch { continue; }
136
+ const was = new Set((await g(["show", `${mb}:${path}`])).split("\n")), mine = new Set((await g(["show", `${lane}:${path}`])).split("\n").filter((l) => !was.has(l)));
137
+ const tok = tokenOf(c, tpl, from), src = `${/^\w/.test(tok) ? "(?<![A-Za-z0-9_])" : ""}${esc(tok)}(?!\\d)`;
138
+ const has = new RegExp(src), re = new RegExp(src, "g");
139
+ const next = text.split("\n").map((l) => (mine.has(l) && has.test(l) ? l.replace(re, () => tokenOf(c, tpl, to)) : l)).join("\n");
140
+ if (next !== text) { writeFileSync(p, next); touched.add(path); }
141
+ }
142
+ }
143
+ await git(["add", "-A", "--", ...touched]);
144
+ await git(["commit", "-q", "-m", `chore(sequence): renumber ${moves.map((m) => `${m.from} → ${m.to}`).join(", ")} (deterministic, #5235)`]);
145
+ return { ok: true, moves, commit: (await g(["rev-parse", "HEAD"])).trim() || null };
146
+ } catch (e) { return await fail(`versioned renumber failed: ${String(e?.message ?? e).split("\n")[0]}`); }
147
+ }
@@ -0,0 +1,28 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Stage-file provenance (#5333): the builder writes `forge-stamp: issue=N contract=HASH` as the first line of each
5
+ * `.forge-lean/*.md` stage note. A note stamped for another issue or contract (a `git stash pop` that applied another
6
+ * lane's files) is never posted. Pure: no I/O. A missing stamp is accepted (older notes, builders that skipped it).
7
+ */
8
+
9
+ const STAMP_RE = /^[ \t]*forge-stamp:[ \t]*issue=(\d+)(?:[ \t]+contract=([0-9a-f]+|-))?[ \t]*$/im;
10
+
11
+ /** The stamp line for this run; `hash` is null before the contract is frozen (planning). */
12
+ export const stampText = ({ issue, hash = null }) => `forge-stamp: issue=${issue} contract=${hash ?? "-"}`;
13
+
14
+ /** Prompt text telling the builder to stamp its stage notes and not to use the shared stash. */
15
+ export const stampRule = (stamp) => (stamp ? `\n\nStage notes: make the first line of every ${"`.forge-lean/*.md`"} file you write exactly \`${stamp}\` (the engine refuses to post a note stamped for another issue or contract).` : "");
16
+
17
+ /**
18
+ * @returns {{ok: boolean, md: string, reason?: string}} md is the note without its stamp line; ok=false on an issue/contract mismatch.
19
+ */
20
+ export function checkStamp(md, { issue, hash = null }) {
21
+ const text = String(md ?? "");
22
+ const m = STAMP_RE.exec(text);
23
+ if (!m) return { ok: true, md: text };
24
+ const stripped = text.replace(m[0], "").replace(/^\s*\n/, "");
25
+ if (Number(m[1]) !== Number(issue)) return { ok: false, md: stripped, reason: `stamped for issue #${m[1]}, run is #${issue}` };
26
+ if (hash && m[2] && m[2] !== "-" && m[2] !== hash) return { ok: false, md: stripped, reason: `stamped for contract ${m[2]}, run froze ${hash}` };
27
+ return { ok: true, md: stripped };
28
+ }