forgedock 1.52.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.
- package/.claude-plugin/marketplace.json +51 -0
- package/README.md +8 -2
- package/bin/auth/app-manifest.mjs +89 -0
- package/bin/auth/app-manifest.test.mjs +75 -0
- package/bin/auth/app-token.mjs +256 -0
- package/bin/auth/app-token.test.mjs +232 -0
- package/bin/brand.mjs +7 -0
- package/bin/config-history.mjs +151 -0
- package/bin/config-schema.mjs +115 -0
- package/bin/demo.mjs +65 -11
- package/bin/engine/outcome-codes.mjs +9 -3
- package/bin/engine/telemetry-seam.mjs +11 -3
- package/bin/engine/telemetry-seam.test.mjs +17 -0
- package/bin/engine-cli.mjs +110 -36
- package/bin/experiment.mjs +58 -6
- package/bin/first-run.mjs +122 -0
- package/bin/forge-utils.mjs +6 -2
- package/bin/forgedock.mjs +138 -142
- package/bin/help-text.mjs +144 -0
- package/bin/hooks/pre-tool-use.mjs +7 -0
- package/bin/journey.mjs +82 -83
- package/bin/lean/acceptance.mjs +313 -0
- package/bin/lean/acceptance.test.mjs +215 -0
- package/bin/lean/account-watch.mjs +28 -0
- package/bin/lean/account-watch.test.mjs +30 -0
- package/bin/lean/activation.mjs +38 -0
- package/bin/lean/activation.test.mjs +36 -1
- package/bin/lean/basered.mjs +115 -0
- package/bin/lean/basered.test.mjs +66 -0
- package/bin/lean/batch-health.mjs +114 -7
- package/bin/lean/batch-health.test.mjs +87 -1
- package/bin/lean/batch.mjs +41 -2
- package/bin/lean/batch.test.mjs +115 -11
- package/bin/lean/branchlock.mjs +54 -0
- package/bin/lean/branchlock.test.mjs +49 -0
- package/bin/lean/ceiling.mjs +72 -0
- package/bin/lean/ceiling.test.mjs +54 -0
- package/bin/lean/checkpoint-reconcile.mjs +43 -0
- package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
- package/bin/lean/ci-budget.mjs +366 -0
- package/bin/lean/ci-budget.test.mjs +167 -0
- package/bin/lean/conformance.e2e.test.mjs +8 -1
- package/bin/lean/conformance.mjs +269 -38
- package/bin/lean/conformance.test.mjs +280 -7
- package/bin/lean/context.mjs +35 -6
- package/bin/lean/context.test.mjs +27 -1
- package/bin/lean/depcache.mjs +25 -1
- package/bin/lean/depcache.test.mjs +26 -0
- package/bin/lean/e2e.mjs +18 -2
- package/bin/lean/e2e.test.mjs +26 -1
- package/bin/lean/effects.mjs +47 -14
- package/bin/lean/execution.mjs +19 -3
- package/bin/lean/execution.test.mjs +63 -0
- package/bin/lean/facts.mjs +3 -3
- package/bin/lean/facts.test.mjs +5 -0
- package/bin/lean/findinglabel.mjs +16 -0
- package/bin/lean/findinglabel.test.mjs +39 -0
- package/bin/lean/fixround.mjs +14 -0
- package/bin/lean/fixround.test.mjs +25 -2
- package/bin/lean/gh-assoc.test.mjs +2 -1
- package/bin/lean/integration.mjs +100 -9
- package/bin/lean/integration.test.mjs +98 -0
- package/bin/lean/issuewatch-parity.mjs +64 -0
- package/bin/lean/issuewatch-parity.test.mjs +127 -0
- package/bin/lean/issuewatch-release.mjs +6 -2
- package/bin/lean/issuewatch-release.test.mjs +17 -1
- package/bin/lean/issuewatch.mjs +45 -6
- package/bin/lean/issuewatch.test.mjs +3 -2
- package/bin/lean/lanelock.mjs +14 -0
- package/bin/lean/lean.mjs +473 -100
- package/bin/lean/lean.test.mjs +686 -33
- package/bin/lean/light.mjs +48 -7
- package/bin/lean/light.test.mjs +37 -3
- package/bin/lean/limits.test.mjs +142 -9
- package/bin/lean/mechfix.mjs +124 -0
- package/bin/lean/mechfix.test.mjs +75 -0
- package/bin/lean/orchestrate-cancel.test.mjs +143 -0
- package/bin/lean/orchestrate.mjs +116 -28
- package/bin/lean/phaseledger.mjs +47 -5
- package/bin/lean/phaseledger.test.mjs +30 -1
- package/bin/lean/postdeploy-check.test.mjs +39 -0
- package/bin/lean/precheck.mjs +23 -4
- package/bin/lean/precheck.test.mjs +14 -1
- package/bin/lean/prereq.mjs +28 -0
- package/bin/lean/prereq.test.mjs +20 -0
- package/bin/lean/probe.mjs +4 -2
- package/bin/lean/prodparity.mjs +52 -0
- package/bin/lean/prodparity.test.mjs +67 -0
- package/bin/lean/prompts.mjs +77 -19
- package/bin/lean/quota.mjs +39 -0
- package/bin/lean/recovery.test.mjs +11 -1
- package/bin/lean/relaxation.mjs +73 -0
- package/bin/lean/relaxation.test.mjs +54 -0
- package/bin/lean/release-io.test.mjs +42 -0
- package/bin/lean/release-postmerge.mjs +125 -0
- package/bin/lean/release-preflight.mjs +58 -0
- package/bin/lean/release-preflight.test.mjs +114 -0
- package/bin/lean/release-rehearsal.mjs +64 -0
- package/bin/lean/release-rehearsal.test.mjs +93 -0
- package/bin/lean/release-review.e2e.test.mjs +77 -0
- package/bin/lean/release-review.mjs +254 -0
- package/bin/lean/release-review.test.mjs +307 -0
- package/bin/lean/release-snapshot.mjs +188 -0
- package/bin/lean/release-snapshot.test.mjs +190 -0
- package/bin/lean/release.mjs +296 -0
- package/bin/lean/release.test.mjs +387 -0
- package/bin/lean/render.mjs +1 -1
- package/bin/lean/replan.mjs +184 -0
- package/bin/lean/replan.test.mjs +110 -0
- package/bin/lean/resume.mjs +9 -7
- package/bin/lean/resume.test.mjs +16 -0
- package/bin/lean/rotator.mjs +150 -31
- package/bin/lean/rotator.test.mjs +105 -2
- package/bin/lean/sandbox-remote.mjs +9 -2
- package/bin/lean/schedd.mjs +83 -5
- package/bin/lean/schedd.test.mjs +108 -7
- package/bin/lean/selfreview.mjs +94 -0
- package/bin/lean/selfreview.test.mjs +58 -1
- package/bin/lean/selftest-gate.mjs +22 -0
- package/bin/lean/selftest-gate.test.mjs +18 -1
- package/bin/lean/selftest-journey.mjs +234 -0
- package/bin/lean/selftest-journey.test.mjs +130 -0
- package/bin/lean/selftest-live.mjs +2 -1
- package/bin/lean/seqlease.mjs +35 -1
- package/bin/lean/seqlease.test.mjs +15 -0
- package/bin/lean/seqreserve.e2e.test.mjs +135 -0
- package/bin/lean/seqreserve.mjs +73 -0
- package/bin/lean/seqreserve.test.mjs +134 -0
- package/bin/lean/sequence.mjs +35 -6
- package/bin/lean/seqversioned.mjs +147 -0
- package/bin/lean/stagestamp.mjs +28 -0
- package/bin/lean/stagestamp.test.mjs +32 -0
- package/bin/lean/surfaces.mjs +75 -0
- package/bin/lean/surfaces.test.mjs +59 -0
- package/bin/lean/toolplace.mjs +28 -0
- package/bin/lean/toolplace.test.mjs +24 -0
- package/bin/lean/toolstats.mjs +3 -1
- package/bin/lean/toolstats.test.mjs +11 -0
- package/bin/lean/validatebest.mjs +28 -0
- package/bin/lean/validatebest.test.mjs +27 -0
- package/bin/lean/verifier.mjs +3 -2
- package/bin/lean/verify.mjs +2 -1
- package/bin/lean/verify.test.mjs +6 -0
- package/bin/pool/agent.mjs +27 -4
- package/bin/pool/docker.mjs +5 -0
- package/bin/pool/router.mjs +74 -28
- package/bin/prereqs.mjs +111 -0
- package/bin/replay-timelapse.mjs +149 -0
- package/bin/review-staging.mjs +123 -16
- package/bin/review-staging.test.mjs +18 -0
- package/bin/runner.mjs +43 -6
- package/bin/splash-install.mjs +157 -0
- package/bin/stats/aggregate.mjs +8 -1
- package/bin/stats/conformance-outcomes.mjs +289 -0
- package/bin/stats/conformance-outcomes.test.mjs +274 -0
- package/bin/stats/depth.mjs +275 -0
- package/bin/stats/depth.test.mjs +158 -0
- package/bin/stats/efficiency.mjs +26 -5
- package/bin/stats/efficiency.test.mjs +45 -1
- package/bin/stats/experiment.mjs +7 -5
- package/bin/stats/first-review.mjs +77 -0
- package/bin/stats/first-review.test.mjs +36 -0
- package/bin/stats/firstmerge.mjs +40 -0
- package/bin/stats/firstmerge.test.mjs +41 -0
- package/bin/stats/github-source.mjs +53 -15
- package/bin/stats/index.mjs +147 -9
- package/bin/stats/local-source.mjs +12 -0
- package/bin/stats/origin.mjs +80 -0
- package/bin/stats/origin.test.mjs +58 -0
- package/bin/stats/query.mjs +69 -0
- package/bin/stats/render.mjs +3 -1
- package/bin/stats/scoreboard.mjs +137 -0
- package/bin/stats/scoreboard.test.mjs +87 -0
- package/bin/stats/selffiled.mjs +52 -0
- package/bin/stats/selffiled.test.mjs +71 -0
- package/bin/stats/stats.test.mjs +80 -0
- package/bin/tui.mjs +3 -2
- package/commands/bootstrap.md +15 -14
- package/commands/deploy-pr.md +18 -3
- package/commands/forge-stats.md +1 -1
- package/commands/forgedock-ci-setup.md +28 -0
- package/commands/forgedock-init.md +4 -5
- package/commands/issue.md +2 -0
- package/commands/milestone.md +9 -1
- package/commands/orchestrate.md +1 -1
- package/commands/replay.md +2 -0
- package/commands/review-pr-agents/security.md +4 -0
- package/commands/review-pr-staging.md +6 -1
- package/commands/work-on/build.md +4 -6
- package/commands/work-on/close.md +8 -0
- package/docs/CONFIG.md +170 -18
- package/docs/ISSUE-WATCH.md +25 -0
- package/docs/OUTCOME-CODES.md +4 -0
- package/docs/REPLAY.md +9 -0
- package/docs/SELFTEST.md +11 -0
- package/docs/STATS.md +61 -0
- package/docs/TELEMETRY.md +1 -1
- package/docs/eval/README.md +6 -0
- package/docs/eval/adversarial-bench.md +68 -0
- package/docs/eval/corpus/adversarial-v1.json +285 -0
- package/docs/eval/feature-bench.md +42 -0
- package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
- package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
- package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
- package/docs/site/start-a-new-project.md +2 -1
- package/package.json +5 -2
- package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
- package/plugins/forgedock-splash/README.md +27 -0
- package/plugins/forgedock-splash/hooks/hooks.json +1 -0
- package/plugins/forgedock-splash/hooks/register.tsx +74 -0
- package/plugins/forgedock-splash/hooks/scene.ts +222 -0
- package/plugins/forgedock-splash/types/index.d.ts +10 -0
- package/pool/README.md +1 -1
- package/pool/image/cs-cred +14 -1
- package/scripts/backfill-finding-labels.mjs +50 -0
- package/scripts/backfill-finding-labels.test.mjs +36 -0
- package/scripts/bench-adversarial.mjs +216 -0
- package/scripts/bench-feature.mjs +170 -0
- package/scripts/bench-lightlane.mjs +2 -2
- package/scripts/bootstrap-create.mjs +2 -2
- package/scripts/bootstrap-validate.mjs +35 -2
- package/scripts/check-spec-size.sh +4 -3
- package/scripts/check-spec-size.test.sh +3 -0
- package/scripts/doctor-pipeline-state.sh +21 -6
- package/scripts/file-deferred-followups.sh +59 -251
- package/scripts/file-deferred-followups.test.sh +85 -206
- package/scripts/followup-route.mjs +12 -0
- package/scripts/owner-route-parity.test.sh +17 -1
- package/scripts/plan-validate-live.mjs +40 -6
- package/scripts/review-pr-side-effects.test.sh +40 -0
- package/scripts/review-pr-staging-scope.test.sh +1 -1
- package/scripts/review-staging-post.sh +23 -0
- package/scripts/review-staging-post.test.sh +8 -0
|
@@ -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
|
+
});
|
package/bin/lean/sequence.mjs
CHANGED
|
@@ -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({
|
|
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
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { describe, it } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { checkStamp, stampText, stampRule } from "./stagestamp.mjs";
|
|
4
|
+
|
|
5
|
+
describe("stage stamps (#5333)", () => {
|
|
6
|
+
it("stampText carries the issue and the contract hash, `-` before the freeze", () => {
|
|
7
|
+
assert.equal(stampText({ issue: 7, hash: "abc123def456" }), "forge-stamp: issue=7 contract=abc123def456");
|
|
8
|
+
assert.equal(stampText({ issue: 7 }), "forge-stamp: issue=7 contract=-");
|
|
9
|
+
});
|
|
10
|
+
it("a matching stamp passes and is stripped", () => {
|
|
11
|
+
const c = checkStamp("forge-stamp: issue=7 contract=abc123\n### Approach\nx", { issue: 7, hash: "abc123" });
|
|
12
|
+
assert.deepEqual(c, { ok: true, md: "### Approach\nx" });
|
|
13
|
+
});
|
|
14
|
+
it("another issue's stamp is refused (the stash-pop case)", () => {
|
|
15
|
+
const c = checkStamp("forge-stamp: issue=37641 contract=ffff\ncurl_cffi", { issue: 40194, hash: "abc123" });
|
|
16
|
+
assert.equal(c.ok, false);
|
|
17
|
+
assert.match(c.reason, /issue #37641, run is #40194/);
|
|
18
|
+
});
|
|
19
|
+
it("same issue, other contract hash is refused; an unknown run hash or `-` is not checked", () => {
|
|
20
|
+
assert.equal(checkStamp("forge-stamp: issue=7 contract=aaa\nx", { issue: 7, hash: "bbb" }).ok, false);
|
|
21
|
+
assert.equal(checkStamp("forge-stamp: issue=7 contract=aaa\nx", { issue: 7, hash: null }).ok, true);
|
|
22
|
+
assert.equal(checkStamp("forge-stamp: issue=7 contract=-\nx", { issue: 7, hash: "bbb" }).ok, true);
|
|
23
|
+
});
|
|
24
|
+
it("an unstamped note is accepted unchanged", () => {
|
|
25
|
+
assert.deepEqual(checkStamp("### Approach\nx", { issue: 7 }), { ok: true, md: "### Approach\nx" });
|
|
26
|
+
assert.equal(checkStamp(null, { issue: 7 }).md, "");
|
|
27
|
+
});
|
|
28
|
+
it("stampRule names the stamp, empty without one", () => {
|
|
29
|
+
assert.match(stampRule("forge-stamp: issue=7 contract=-"), /first line[\s\S]*forge-stamp: issue=7/);
|
|
30
|
+
assert.equal(stampRule(null), "");
|
|
31
|
+
});
|
|
32
|
+
});
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Shared surfaces (#5340): files every lane of a feature may touch (registries, route tables, migration dirs, versioned
|
|
5
|
+
* dirs, OpenAPI, i18n catalogs). forge.yaml `engine.shared_surfaces` lists them as globs, one per entry
|
|
6
|
+
* (comma-separated scalar or block list); `glob => command` marks an append-only registry the repo regenerates, which
|
|
7
|
+
* lanes must not hand-edit and which is never reserved. A lane whose frozen contract touches a declared surface takes a
|
|
8
|
+
* host reservation (one slot per repo + surface, across the milestone lane and the default branch) until its merge and
|
|
9
|
+
* records what it will add, so sibling packs show it. Pure parsing here; the lease and declaration records are in seqlease.mjs.
|
|
10
|
+
* Fail-open: no declared surface, or a failed lease, changes nothing.
|
|
11
|
+
*/
|
|
12
|
+
export const SURFACE_LANE = "*"; // the lease key spans every lane branch: the milestone lane and the default branch share a surface
|
|
13
|
+
|
|
14
|
+
const escapeRe = (s) => s.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
15
|
+
/** A repo-relative glob as a RegExp: `**` any depth, `*` within a segment, `?` one char; a trailing `/` means the whole dir. */
|
|
16
|
+
export function surfaceGlobRegExp(glob) {
|
|
17
|
+
let g = String(glob).trim().replace(/^\.?\/+/, "");
|
|
18
|
+
if (g.endsWith("/")) g += "**";
|
|
19
|
+
let re = "";
|
|
20
|
+
for (let i = 0; i < g.length; i++) {
|
|
21
|
+
const c = g[i];
|
|
22
|
+
if (c === "*" && g[i + 1] === "*") { re += ".*"; i++; if (g[i + 1] === "/") i++; }
|
|
23
|
+
else if (c === "*") re += "[^/]*";
|
|
24
|
+
else if (c === "?") re += "[^/]";
|
|
25
|
+
else re += escapeRe(c);
|
|
26
|
+
}
|
|
27
|
+
return new RegExp(`^${re}$`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** engine.shared_surfaces (string or array) -> [{name, generate|null, test(path)}]; blanks and duplicates dropped. */
|
|
31
|
+
export function parseSharedSurfaces(raw) {
|
|
32
|
+
const items = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : [];
|
|
33
|
+
const seen = new Set(), out = [];
|
|
34
|
+
for (const it of items) {
|
|
35
|
+
const [glob, ...rest] = String(it ?? "").split("=>");
|
|
36
|
+
const name = glob.trim().replace(/^\.?\/+/, "");
|
|
37
|
+
if (!name || seen.has(name)) continue;
|
|
38
|
+
seen.add(name);
|
|
39
|
+
const generate = rest.join("=>").trim() || null;
|
|
40
|
+
const re = surfaceGlobRegExp(name);
|
|
41
|
+
out.push({ name, generate, test: (p) => re.test(String(p).replace(/^\.?\/+/, "")) });
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The surfaces `paths` touch: `reserved` (take a slot) and `generated` (declared generator, hand-edits discouraged). */
|
|
47
|
+
export function matchSurfaces(surfaces, paths) {
|
|
48
|
+
const reserved = [], generated = [];
|
|
49
|
+
for (const s of surfaces ?? []) {
|
|
50
|
+
const files = (paths ?? []).filter((p) => s.test(p));
|
|
51
|
+
if (!files.length) continue;
|
|
52
|
+
(s.generate ? generated : reserved).push({ name: s.name, files, generate: s.generate });
|
|
53
|
+
}
|
|
54
|
+
return { reserved, generated };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Builder note for the surfaces of an append-only registry: run the generator, never hand-edit the list. */
|
|
58
|
+
export function generatorNote(generated) {
|
|
59
|
+
if (!generated?.length) return "";
|
|
60
|
+
return `\n\nGenerated shared surfaces (forge.yaml engine.shared_surfaces): do not hand-edit ${generated.map((g) => g.name).join(", ")}; regenerate with ${generated.map((g) => `\`${g.generate}\``).join(", ")}.`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Take the reserved slot of every surface the contract's deliverables touch and declare them for sibling packs.
|
|
65
|
+
* `lease` is makeSequenceLeaseIo(). @returns {Promise<{names:string[], generated:object[], waitMs:number, timedOut:boolean, release:Function}|null>}
|
|
66
|
+
* null when nothing is declared or touched.
|
|
67
|
+
*/
|
|
68
|
+
export async function claimSurfaces({ lease, repo, issue, surfaces, paths, maxWaitS = 1800 }) {
|
|
69
|
+
const { reserved, generated } = matchSurfaces(surfaces, paths);
|
|
70
|
+
if (!reserved.length) return generated.length ? { names: [], generated, waitMs: 0, timedOut: false, release() {} } : null;
|
|
71
|
+
try { await lease.declare?.({ repo, issue, surfaces: reserved.map((r) => r.name), paths: reserved.flatMap((r) => r.files) }); } catch { /* fail-open */ }
|
|
72
|
+
let g = null;
|
|
73
|
+
try { g = await lease.acquire({ repo, lane: SURFACE_LANE, dirs: reserved.map((r) => `surface:${r.name}`), issue, maxWaitS }); } catch { g = null; }
|
|
74
|
+
return { names: reserved.map((r) => r.name), generated, waitMs: g?.waitMs ?? 0, timedOut: g?.timedOut ?? false, release: () => { try { g?.release(); } catch { /* fail-open */ } } };
|
|
75
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Shared surfaces (#5340): parse, match, reserved slots, generator exemption.
|
|
4
|
+
import { describe, it } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
7
|
+
import { makeSequenceLeaseIo } from "./seqlease.mjs";
|
|
8
|
+
import { parseSharedSurfaces, matchSurfaces, generatorNote, claimSurfaces, surfaceGlobRegExp } from "./surfaces.mjs";
|
|
9
|
+
|
|
10
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
11
|
+
const mk = () => makeSequenceLeaseIo({ dir: tmpDir("surf-"), pickDir: tmpDir("surfpick-"), declDir: tmpDir("surfdecl-"), pollMs: 20 });
|
|
12
|
+
const SURF = parseSharedSurfaces("db/migrations/**, api/routes.ts, src/registry.ts => npm run gen:registry, , api/routes.ts");
|
|
13
|
+
|
|
14
|
+
describe("parse and match (#5340)", () => {
|
|
15
|
+
it("parses a comma scalar and a list; drops blanks and duplicates; no declaration yields none", () => {
|
|
16
|
+
assert.deepEqual(SURF.map((s) => [s.name, s.generate]), [["db/migrations/**", null], ["api/routes.ts", null], ["src/registry.ts", "npm run gen:registry"]]);
|
|
17
|
+
assert.equal(parseSharedSurfaces(["a/", "b/**"]).length, 2);
|
|
18
|
+
assert.deepEqual(parseSharedSurfaces(undefined), []);
|
|
19
|
+
});
|
|
20
|
+
it("globs: ** any depth, * one segment, trailing slash is the dir", () => {
|
|
21
|
+
assert.ok(surfaceGlobRegExp("db/**").test("db/a/b.sql"));
|
|
22
|
+
assert.ok(surfaceGlobRegExp("db/*.sql").test("db/a.sql"));
|
|
23
|
+
assert.ok(!surfaceGlobRegExp("db/*.sql").test("db/x/a.sql"));
|
|
24
|
+
assert.ok(surfaceGlobRegExp("i18n/").test("i18n/en/x.json"));
|
|
25
|
+
});
|
|
26
|
+
it("a generated registry is exempt from reservation and gets a builder note", () => {
|
|
27
|
+
const m = matchSurfaces(SURF, ["db/migrations/0001.sql", "src/registry.ts", "README.md"]);
|
|
28
|
+
assert.deepEqual(m.reserved.map((r) => r.name), ["db/migrations/**"]);
|
|
29
|
+
assert.deepEqual(m.generated.map((g) => g.name), ["src/registry.ts"]);
|
|
30
|
+
assert.match(generatorNote(m.generated), /do not hand-edit src\/registry\.ts; regenerate with `npm run gen:registry`/);
|
|
31
|
+
assert.equal(generatorNote([]), "");
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe("reserved slot (#5340)", () => {
|
|
36
|
+
it("two lanes on one surface cannot both be admitted: the second waits for the first's release", async () => {
|
|
37
|
+
const lease = mk(), order = [];
|
|
38
|
+
const a = await claimSurfaces({ lease, repo: "o/r", issue: 1, surfaces: SURF, paths: ["api/routes.ts"], maxWaitS: 30 });
|
|
39
|
+
const b = claimSurfaces({ lease, repo: "o/r", issue: 2, surfaces: SURF, paths: ["api/routes.ts"], maxWaitS: 30 }).then((g) => { order.push("b"); return g; });
|
|
40
|
+
await sleep(150);
|
|
41
|
+
assert.deepEqual(order, [], "b is still waiting");
|
|
42
|
+
assert.deepEqual((await lease.declared({ repo: "o/r", except: 2 })).map((d) => d.issue), [1], "in-flight declaration is readable");
|
|
43
|
+
order.push("a-release"); a.release();
|
|
44
|
+
const gb = await b;
|
|
45
|
+
assert.deepEqual(order, ["a-release", "b"]);
|
|
46
|
+
gb.release();
|
|
47
|
+
});
|
|
48
|
+
it("different surfaces do not block; nothing declared or touched claims nothing; undeclare drops the record", async () => {
|
|
49
|
+
const lease = mk();
|
|
50
|
+
const a = await claimSurfaces({ lease, repo: "o/r", issue: 1, surfaces: SURF, paths: ["api/routes.ts"], maxWaitS: 30 });
|
|
51
|
+
const b = await claimSurfaces({ lease, repo: "o/r", issue: 2, surfaces: SURF, paths: ["db/migrations/1.sql"], maxWaitS: 30 });
|
|
52
|
+
assert.equal(b.timedOut, false);
|
|
53
|
+
assert.equal(await claimSurfaces({ lease, repo: "o/r", issue: 3, surfaces: [], paths: ["api/routes.ts"] }), null);
|
|
54
|
+
assert.equal(await claimSurfaces({ lease, repo: "o/r", issue: 3, surfaces: SURF, paths: ["x.md"] }), null);
|
|
55
|
+
a.release(); b.release();
|
|
56
|
+
await lease.undeclare({ repo: "o/r", issue: 1 });
|
|
57
|
+
assert.deepEqual((await lease.declared({ repo: "o/r" })).map((d) => d.issue), [2]);
|
|
58
|
+
});
|
|
59
|
+
});
|