forgedock 1.61.1 → 1.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +10 -1
- package/bin/engine/outcome-codes.mjs +4 -0
- package/bin/engine-cli.mjs +160 -18
- package/bin/env/env.mjs +6 -4
- package/bin/forge-home-check.mjs +91 -0
- package/bin/forgedock.mjs +50 -7
- package/bin/gc.mjs +2 -0
- package/bin/hooks/pre-tool-use.mjs +4 -0
- package/bin/journey.mjs +55 -5
- package/bin/lean/admission.mjs +16 -5
- package/bin/lean/batch-health.mjs +55 -16
- package/bin/lean/batch-health.test.mjs +67 -1
- package/bin/lean/batch.mjs +8 -0
- package/bin/lean/batch.test.mjs +5 -0
- package/bin/lean/ceiling.mjs +20 -0
- package/bin/lean/ceiling.test.mjs +33 -2
- package/bin/lean/ci-gate.mjs +240 -0
- package/bin/lean/ci-gate.test.mjs +227 -0
- package/bin/lean/ci-precheck.mjs +178 -0
- package/bin/lean/ci-precheck.test.mjs +149 -0
- package/bin/lean/conformance.mjs +118 -20
- package/bin/lean/conformance.test.mjs +193 -3
- package/bin/lean/context.test.mjs +7 -6
- package/bin/lean/dag.mjs +128 -0
- package/bin/lean/dag.test.mjs +131 -0
- package/bin/lean/decisions.mjs +5 -4
- package/bin/lean/decisions.test.mjs +11 -0
- package/bin/lean/delguard.mjs +84 -0
- package/bin/lean/delguard.test.mjs +104 -0
- package/bin/lean/depcache.mjs +125 -17
- package/bin/lean/depcache.test.mjs +111 -0
- package/bin/lean/design-gate.mjs +5 -5
- package/bin/lean/design-gate.test.mjs +14 -0
- package/bin/lean/effects.mjs +81 -7
- package/bin/lean/execution.mjs +81 -15
- package/bin/lean/execution.test.mjs +156 -3
- package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
- package/bin/lean/guardgate.mjs +30 -7
- package/bin/lean/guardgate.test.mjs +44 -1
- package/bin/lean/guards.test.mjs +1 -1
- package/bin/lean/heavy.test.mjs +87 -0
- package/bin/lean/hotarea.mjs +73 -0
- package/bin/lean/hotarea.test.mjs +73 -0
- package/bin/lean/issuewatch-reconcile.mjs +20 -1
- package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
- package/bin/lean/lanecheck.mjs +27 -3
- package/bin/lean/lanecheck.test.mjs +47 -5
- package/bin/lean/laneconfine.mjs +83 -0
- package/bin/lean/laneconfine.test.mjs +113 -0
- package/bin/lean/lean.mjs +398 -91
- package/bin/lean/lean.test.mjs +792 -26
- package/bin/lean/live-reconcile.mjs +169 -0
- package/bin/lean/live-reconcile.test.mjs +176 -0
- package/bin/lean/orchestrate-envhold.test.mjs +245 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
- package/bin/lean/orchestrate.mjs +207 -17
- package/bin/lean/outcomeevidence.mjs +104 -0
- package/bin/lean/outcomeevidence.test.mjs +78 -0
- package/bin/lean/page-capture.mjs +68 -0
- package/bin/lean/page-capture.test.mjs +44 -0
- package/bin/lean/pagegate.mjs +46 -7
- package/bin/lean/pagegate.test.mjs +66 -1
- package/bin/lean/postdeploy-check.mjs +18 -4
- package/bin/lean/postdeploy-check.test.mjs +32 -1
- package/bin/lean/prefilter.mjs +36 -4
- package/bin/lean/prefilter.test.mjs +31 -1
- package/bin/lean/preflight.mjs +22 -0
- package/bin/lean/preflight.test.mjs +19 -1
- package/bin/lean/probe.mjs +18 -0
- package/bin/lean/probe.test.mjs +40 -0
- package/bin/lean/prompts.mjs +41 -4
- package/bin/lean/recovery.test.mjs +20 -0
- package/bin/lean/recurrence.mjs +133 -0
- package/bin/lean/recurrence.test.mjs +99 -0
- package/bin/lean/release-config.mjs +2 -1
- package/bin/lean/release-config.test.mjs +18 -0
- package/bin/lean/release-control.mjs +4 -2
- package/bin/lean/release-control.test.mjs +15 -0
- package/bin/lean/release-merge-hold.mjs +65 -0
- package/bin/lean/release-merge-hold.test.mjs +69 -0
- package/bin/lean/release-review.mjs +26 -9
- package/bin/lean/release-review.test.mjs +53 -0
- package/bin/lean/release-status.mjs +3 -1
- package/bin/lean/release-status.test.mjs +11 -0
- package/bin/lean/release.test.mjs +26 -1
- package/bin/lean/render.mjs +8 -7
- package/bin/lean/repro-output.test.mjs +45 -0
- package/bin/lean/routing.mjs +49 -0
- package/bin/lean/routing.test.mjs +54 -1
- package/bin/lean/run-issue-placement.test.mjs +30 -1
- package/bin/lean/sandbox-actions.mjs +121 -0
- package/bin/lean/sandbox-actions.test.mjs +94 -0
- package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
- package/bin/lean/sandbox-remote.mjs +3 -1
- package/bin/lean/schedd-health.mjs +14 -2
- package/bin/lean/schedd-health.test.mjs +13 -0
- package/bin/lean/schedd.mjs +43 -17
- package/bin/lean/schedd.test.mjs +61 -1
- package/bin/lean/toolchain.mjs +16 -6
- package/bin/lean/toolplace.mjs +12 -0
- package/bin/lean/weakguard.mjs +105 -0
- package/bin/lean/weakguard.test.mjs +59 -0
- package/bin/lean/winspawn.mjs +61 -0
- package/bin/lean/winspawn.test.mjs +45 -0
- package/bin/lean/worktree.mjs +3 -1
- package/bin/lean/worktree.test.mjs +11 -0
- package/bin/pool/agent.mjs +215 -15
- package/bin/pool/cache-sweep.mjs +74 -0
- package/bin/pool/cli.mjs +11 -3
- package/bin/pool/docker.mjs +33 -2
- package/bin/pool/health.mjs +38 -0
- package/bin/pool/lane-tools.mjs +23 -4
- package/bin/pool/lane-tools.test.mjs +12 -1
- package/bin/pool/router.mjs +21 -3
- package/bin/runner.mjs +37 -0
- package/bin/splash-scene.mjs +356 -0
- package/bin/win-hide-children.mjs +114 -0
- package/commands/orchestrate.md +18 -27
- package/commands/review-pr-agents/infra.md +1 -0
- package/commands/review-pr-staging.md +2 -2
- package/docs/CONFIG.md +60 -3
- package/docs/OUTCOME-CODES.md +3 -0
- package/package.json +1 -1
- package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
- package/plugins/forgedock-splash/README.md +1 -1
- package/plugins/forgedock-splash/hooks/scene.ts +142 -8
- package/pool/README.md +6 -0
- package/pool/image/entrypoint.sh +1 -0
- package/scripts/acceptance-red-green.sh +8 -3
- package/scripts/acceptance-red-green.test.sh +8 -0
- package/scripts/check-spec-size.sh +3 -1
- package/scripts/gen-splash-scene.mjs +24 -0
- package/scripts/review-staging-pre.sh +8 -3
- package/scripts/review-staging-pre.test.sh +2 -0
package/bin/lean/heavy.test.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { guardChain, isPassThroughWrapper, SHIM_LOOP_MAX, SHIM_DEPTH_MAX, classi
|
|
|
10
10
|
import { checkAdmission, ADMISSION_DEFAULTS, localLaneCap } from "./admission.mjs";
|
|
11
11
|
import { formatAlertLines, formatWaitSummary } from "./orchestrate.mjs";
|
|
12
12
|
import { readHeavy, readAdmission, liveLaneCap } from "../engine-cli.mjs";
|
|
13
|
+
import { makeRampStore } from "./effects.mjs";
|
|
13
14
|
|
|
14
15
|
// Injected pids, clock and host: `live` is the set of pids the registry sees as alive; `mem` the MemAvailable in MB.
|
|
15
16
|
const world = ({ mem = 12000, cores = 4, swapFree = 0 } = {}) => {
|
|
@@ -401,3 +402,89 @@ describe("#5148 dynamic-name pass-through wrapper", () => {
|
|
|
401
402
|
assert.ok(lines(log).length < 13);
|
|
402
403
|
});
|
|
403
404
|
});
|
|
405
|
+
|
|
406
|
+
// #5845: a fake host whose ramp stamps are an in-memory list on a fake clock; each admitted lane adds a stamp and its memory only
|
|
407
|
+
// shows up in MemAvailable once the ramp window has passed.
|
|
408
|
+
const rampHost = ({ mem = 16384, footprint = null, clock = { t: 0 } } = {}) => {
|
|
409
|
+
const stamps = [];
|
|
410
|
+
const live = (s) => stamps.filter((x) => clock.t - x.at < s * 1000);
|
|
411
|
+
const h = {
|
|
412
|
+
memAvailableMb: () => mem, freeMb: async () => 50000, tmpPaths: () => ["/tmp"],
|
|
413
|
+
rampingMb: (s) => live(s).reduce((t, x) => t + x.mb, 0), rampingLanes: (s) => live(s).length,
|
|
414
|
+
...(footprint ? { laneFootprintMb: () => footprint } : {}),
|
|
415
|
+
};
|
|
416
|
+
const admit = async (cfg = {}) => {
|
|
417
|
+
const a = await checkAdmission({ cfg: { max_new_per_ramp: 0, ...cfg }, host: h });
|
|
418
|
+
if (a.ok) stamps.push({ at: clock.t, mb: footprint ?? ADMISSION_DEFAULTS.lane_mem_mb });
|
|
419
|
+
return a;
|
|
420
|
+
};
|
|
421
|
+
return { h, admit, stamps, clock };
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
describe("admission ramp (#5845)", () => {
|
|
425
|
+
it("admission ramp: 20 lanes against 16 GB stop once projected memory falls below footprint plus reserve", async () => {
|
|
426
|
+
const r = rampHost();
|
|
427
|
+
const results = [];
|
|
428
|
+
for (let i = 0; i < 20; i++) results.push(await r.admit());
|
|
429
|
+
// 16384 − n·2048 ≥ 2048 + 2048 → n ≤ 6 lanes ramping, so the 7th is admitted and the 8th is refused
|
|
430
|
+
assert.equal(results.filter((a) => a.ok).length, 7);
|
|
431
|
+
assert.equal(results.findIndex((a) => !a.ok), 7);
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
it("admission ramp: projected memory", async () => {
|
|
435
|
+
const r = rampHost();
|
|
436
|
+
for (let i = 0; i < 20; i++) await r.admit();
|
|
437
|
+
assert.equal((await r.admit()).ok, false);
|
|
438
|
+
r.clock.t += 61_000; // the ramp window passed: those lanes are in MemAvailable now (fixed here), admission resumes
|
|
439
|
+
assert.equal((await r.admit()).ok, true);
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
it("admission ramp: rate limit", async () => {
|
|
443
|
+
const r = rampHost({ mem: 1_000_000 });
|
|
444
|
+
const res = [];
|
|
445
|
+
for (let i = 0; i < 6; i++) res.push(await r.admit({ max_new_per_ramp: 3 }));
|
|
446
|
+
assert.deepEqual(res.map((a) => a.ok), [true, true, true, false, false, false]);
|
|
447
|
+
assert.match(res[3].detail, /3 lanes admitted in the last 60s >= 3/);
|
|
448
|
+
r.clock.t += 60_000;
|
|
449
|
+
assert.equal((await r.admit({ max_new_per_ramp: 3 })).ok, true);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
it("admission ramp: learned footprint", async () => {
|
|
453
|
+
const def = rampHost({ mem: 8192 }), big = rampHost({ mem: 8192, footprint: 3072 });
|
|
454
|
+
let nd = 0, nb = 0;
|
|
455
|
+
while ((await def.admit()).ok && nd < 50) nd++;
|
|
456
|
+
while ((await big.admit()).ok && nb < 50) nb++;
|
|
457
|
+
assert.ok(nb < nd, `a larger learned footprint admits fewer lanes (${nb} < ${nd})`);
|
|
458
|
+
const dir = tmpDir("ramp-"), clock = { t: 5_000_000 };
|
|
459
|
+
const st = makeRampStore({ dir, now: () => clock.t });
|
|
460
|
+
assert.equal(st.laneFootprintMb(), 2048, "no record: the default");
|
|
461
|
+
st.recordPeakRss(3000); st.recordPeakRss(3500);
|
|
462
|
+
assert.equal(st.laneFootprintMb(), 3500, "the median or 90% of the max, whichever is larger");
|
|
463
|
+
st.recordPeakRss(100);
|
|
464
|
+
assert.ok(st.laneFootprintMb() >= 2048, "never under the default");
|
|
465
|
+
assert.equal(st.rampingLanes(60), 0);
|
|
466
|
+
assert.equal(st.recordAdmission(), true);
|
|
467
|
+
assert.equal(st.rampingLanes(60), 1); assert.equal(st.rampingMb(60), st.laneFootprintMb());
|
|
468
|
+
clock.t += 61_000;
|
|
469
|
+
assert.equal(st.rampingLanes(60), 0, "a stamp past the ramp window no longer counts");
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
it("admission ramp: refusal detail", async () => {
|
|
473
|
+
const r = rampHost({ mem: 6000 });
|
|
474
|
+
r.stamps.push({ at: 0, mb: 4096 });
|
|
475
|
+
const a = await r.admit();
|
|
476
|
+
assert.equal(a.ok, false);
|
|
477
|
+
assert.equal(a.detail, "host busy: projected mem 1.9G (free 5.9G − ramping 4G) < need 4G; retry in 60s");
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
it("admission ramp: missing or throwing probes stay fail-open and unchanged", async () => {
|
|
481
|
+
const base = { memAvailableMb: () => 8192, freeMb: async () => 50000, tmpPaths: () => ["/tmp"] };
|
|
482
|
+
assert.equal((await checkAdmission({ host: base })).ok, true);
|
|
483
|
+
const throwing = { ...base, rampingMb: () => { throw new Error("x"); }, rampingLanes: () => NaN, laneFootprintMb: () => { throw new Error("y"); } };
|
|
484
|
+
assert.equal((await checkAdmission({ host: throwing })).ok, true);
|
|
485
|
+
assert.equal((await checkAdmission({ host: { ...base, memAvailableMb: () => 1000 } })).detail, "host busy: mem 1.0G < 2G; retry in 60s");
|
|
486
|
+
assert.equal(localLaneCap({ cfg: {}, cores: 16, memAvailableMb: 16384 }), 7);
|
|
487
|
+
assert.equal(localLaneCap({ cfg: {}, cores: 16, memAvailableMb: 16384, rampingMb: 6144 }), 4, "ramping memory lowers the live cap");
|
|
488
|
+
assert.equal(makeRampStore({ dir: join(tmpDir("ramp-"), "none", "x") }).rampingMb(60), null, "an unreadable stamp dir is unknown, not zero");
|
|
489
|
+
});
|
|
490
|
+
});
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5751: repo-declared hot areas (one lane at a time) and named counters (must not keep growing).
|
|
5
|
+
* A hot area is admitted through the branch lock (branchlock.mjs) keyed `hot-area:<name>`: host-wide and pid-aware, but
|
|
6
|
+
* host-local (lanes on another host are not excluded). A counter is a `git grep -c -E` pattern evaluated at a ref, so the
|
|
7
|
+
* base side needs no checkout; growth fails conformance unless a contract decision row says `counter-ok: <name> <reason>`.
|
|
8
|
+
*/
|
|
9
|
+
import { OUTCOME_CODES as C } from "../engine/outcome-codes.mjs";
|
|
10
|
+
import { acquireBranchLock } from "./branchlock.mjs";
|
|
11
|
+
import { globToRegex } from "../../scripts/ci-local/lib.mjs";
|
|
12
|
+
import { pathsOverlap } from "./recurrence.mjs";
|
|
13
|
+
|
|
14
|
+
export const HOT_AREA_PREFIX = "hot-area:";
|
|
15
|
+
|
|
16
|
+
/** Names of the declared hot areas any of `paths` falls in (glob match, or a named directory containing a glob's root). */
|
|
17
|
+
export function areaOf(paths = [], hotAreas = []) {
|
|
18
|
+
const ps = (paths ?? []).map((p) => String(p ?? "").trim().replace(/^\.?\/+/, "")).filter(Boolean);
|
|
19
|
+
const hit = (g) => ps.some((p) => globToRegex(g).test(p) || pathsOverlap(p, g.split(/[*?[{]/)[0]));
|
|
20
|
+
return [...new Set((hotAreas ?? []).filter((a) => (a.paths ?? []).some(hit)).map((a) => a.name))].sort();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Take every lock in `areas` (sorted, so two lanes never deadlock). On a refusal the locks already taken are released and
|
|
25
|
+
* the holder is reported. `lock` is the lock primitive (acquireBranchLock), injectable for tests.
|
|
26
|
+
* @returns {Promise<{ok:true, release:() => void, areas:string[]} | {ok:false, area:string, holder:object|null}>}
|
|
27
|
+
*/
|
|
28
|
+
export async function acquireHotArea({ gitCommonDir, areas = [], owner, waitMs = 0, lock = acquireBranchLock, ...rest }) {
|
|
29
|
+
const held = [];
|
|
30
|
+
const release = () => { for (const h of held.splice(0).reverse()) h.release(); };
|
|
31
|
+
for (const area of [...new Set(areas)].sort()) {
|
|
32
|
+
const r = await lock({ gitCommonDir, branch: `${HOT_AREA_PREFIX}${area}`, owner, waitMs, ...rest });
|
|
33
|
+
if (!r.ok) { release(); return { ok: false, area, holder: r.holder ?? null }; }
|
|
34
|
+
held.push(r);
|
|
35
|
+
}
|
|
36
|
+
return { ok: true, release, areas: [...new Set(areas)].sort() };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Each counter's match count at `ref` (git grep -c -E; no checkout). `git(args)` returns stdout and throws on a non-zero
|
|
41
|
+
* exit: git grep exits 1 on no match, so a throw counts as 0.
|
|
42
|
+
* @returns {Promise<Record<string, number>>}
|
|
43
|
+
*/
|
|
44
|
+
export async function countCounters({ git, ref = "HEAD", counters = [] }) {
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const c of counters ?? []) {
|
|
47
|
+
let n = 0;
|
|
48
|
+
try {
|
|
49
|
+
const txt = String(await git(["grep", "-c", "-E", "-e", c.pattern, ref, "--", ...(c.paths?.length ? c.paths : ["."])]));
|
|
50
|
+
for (const line of txt.split("\n")) { const m = /:(\d+)\s*$/.exec(line); if (m) n += Number(m[1]); }
|
|
51
|
+
} catch { n = 0; }
|
|
52
|
+
out[c.name] = n;
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const okRe = (name) => new RegExp(`counter-ok:\\s*${String(name).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s+\\S`, "i");
|
|
58
|
+
/** True when the contract decisions (or a result decision amendment) carry `counter-ok: <name> <reason>`. */
|
|
59
|
+
export function counterExempt(name, contract, result = null) {
|
|
60
|
+
const re = okRe(name);
|
|
61
|
+
const texts = [...(contract?.decisions ?? []).flatMap((d) => [d?.choice, d?.justification, d?.why]),
|
|
62
|
+
...(Array.isArray(result?.amendments) ? result.amendments : []).filter((a) => a?.kind === "decision").flatMap((a) => [a?.decision?.choice, a?.why])];
|
|
63
|
+
return texts.some((t) => typeof t === "string" && re.test(t));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Failures for every counter that grew from `before` to `after` without an explicit decision. */
|
|
67
|
+
export function counterGrowth({ before = null, after = null, contract = null, result = null } = {}) {
|
|
68
|
+
if (!before || !after) return [];
|
|
69
|
+
return Object.keys(after)
|
|
70
|
+
.filter((name) => Number.isFinite(before[name]) && Number(after[name]) > Number(before[name]) && !counterExempt(name, contract, result))
|
|
71
|
+
.map((name) => ({ code: C.MAINTENANCE_COUNTER_GROWTH, kind: "counter_growth",
|
|
72
|
+
detail: `counter ${name} grew from ${before[name]} to ${after[name]} without a contract decision "counter-ok: ${name} <reason>"` }));
|
|
73
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { existsSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { areaOf, acquireHotArea, countCounters, counterGrowth, counterExempt } from "./hotarea.mjs";
|
|
8
|
+
import { LOCK_DIR } from "./branchlock.mjs";
|
|
9
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
10
|
+
|
|
11
|
+
const AREAS = [{ name: "billing", paths: ["src/billing/**"] }, { name: "auth", paths: ["src/auth.js"] }];
|
|
12
|
+
|
|
13
|
+
describe("hot areas (#5751)", () => {
|
|
14
|
+
it("areaOf matches declared globs, and a named directory containing a glob's root", () => {
|
|
15
|
+
assert.deepEqual(areaOf(["src/billing/reserve.js", "README.md"], AREAS), ["billing"]);
|
|
16
|
+
assert.deepEqual(areaOf(["./src/auth.js", "src/billing/x.js"], AREAS), ["auth", "billing"]);
|
|
17
|
+
assert.deepEqual(areaOf(["src/billing"], AREAS), ["billing"]);
|
|
18
|
+
assert.deepEqual(areaOf(["docs/x.md"], AREAS), []);
|
|
19
|
+
assert.deepEqual(areaOf(["src/billing/x.js"], []), [], "no declared areas: inert");
|
|
20
|
+
});
|
|
21
|
+
it("a second lane cannot enter a hot area another lane holds, and is told the holder", async () => {
|
|
22
|
+
const dir = tmpDir("hotarea-");
|
|
23
|
+
const a = await acquireHotArea({ gitCommonDir: dir, areas: ["billing"], owner: "lane-A", alive: () => true });
|
|
24
|
+
assert.equal(a.ok, true);
|
|
25
|
+
assert.ok(readdirSync(join(dir, LOCK_DIR)).includes(encodeURIComponent("hot-area:billing")));
|
|
26
|
+
const b = await acquireHotArea({ gitCommonDir: dir, areas: ["billing"], owner: "lane-B", alive: () => true });
|
|
27
|
+
assert.equal(b.ok, false);
|
|
28
|
+
assert.equal(b.area, "billing");
|
|
29
|
+
assert.equal(b.holder.owner, "lane-A");
|
|
30
|
+
assert.equal((await acquireHotArea({ gitCommonDir: dir, areas: ["auth"], owner: "lane-B", alive: () => true })).ok, true, "another area is independent");
|
|
31
|
+
});
|
|
32
|
+
it("a refused lane holds nothing: locks taken before the refusal are released", async () => {
|
|
33
|
+
const dir = tmpDir("hotarea-");
|
|
34
|
+
await acquireHotArea({ gitCommonDir: dir, areas: ["billing"], owner: "lane-A", alive: () => true });
|
|
35
|
+
const b = await acquireHotArea({ gitCommonDir: dir, areas: ["billing", "auth"], owner: "lane-B", alive: () => true });
|
|
36
|
+
assert.equal(b.ok, false);
|
|
37
|
+
assert.equal((await acquireHotArea({ gitCommonDir: dir, areas: ["auth"], owner: "lane-C", alive: () => true })).ok, true);
|
|
38
|
+
});
|
|
39
|
+
it("release lets a waiting lane in; a dead holder is taken over", async () => {
|
|
40
|
+
const dir = tmpDir("hotarea-");
|
|
41
|
+
const a = await acquireHotArea({ gitCommonDir: dir, areas: ["billing"], owner: "lane-A", alive: () => true });
|
|
42
|
+
let waited = 0;
|
|
43
|
+
const b = await acquireHotArea({ gitCommonDir: dir, areas: ["billing"], owner: "lane-B", alive: () => true, waitMs: 1000, pollMs: 10, sleep: async () => { if (++waited === 2) a.release(); } });
|
|
44
|
+
assert.equal(b.ok, true);
|
|
45
|
+
b.release();
|
|
46
|
+
assert.equal(existsSync(join(dir, LOCK_DIR, encodeURIComponent("hot-area:billing"))), false);
|
|
47
|
+
mkdirSync(join(dir, LOCK_DIR), { recursive: true });
|
|
48
|
+
writeFileSync(join(dir, LOCK_DIR, encodeURIComponent("hot-area:auth")), JSON.stringify({ owner: "gone", pid: 999999 }));
|
|
49
|
+
assert.equal((await acquireHotArea({ gitCommonDir: dir, areas: ["auth"], owner: "lane-C", alive: (p) => p !== 999999 })).ok, true);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
describe("named counters (#5751)", () => {
|
|
54
|
+
it("countCounters sums git grep -c at a ref; no match counts 0", async () => {
|
|
55
|
+
const calls = [];
|
|
56
|
+
const git = async (a) => { calls.push(a); if (a.includes("NONE")) throw new Error("exit 1"); return "origin/main:src/a.js:3\norigin/main:src/b.js:2\n"; };
|
|
57
|
+
const c = await countCounters({ git, ref: "origin/main", counters: [{ name: "flags", pattern: "FLAG_", paths: ["src/**"] }, { name: "none", pattern: "NONE", paths: [] }] });
|
|
58
|
+
assert.deepEqual(c, { flags: 5, none: 0 });
|
|
59
|
+
assert.deepEqual(calls[0], ["grep", "-c", "-E", "-e", "FLAG_", "origin/main", "--", "src/**"]);
|
|
60
|
+
assert.deepEqual(calls[1].slice(-2), ["--", "."]);
|
|
61
|
+
});
|
|
62
|
+
it("growth fails without a decision and passes with a counter-ok decision", () => {
|
|
63
|
+
const f = counterGrowth({ before: { flags: 5 }, after: { flags: 6 }, contract: { decisions: [] } });
|
|
64
|
+
assert.equal(f.length, 1);
|
|
65
|
+
assert.equal(f[0].code, "maintenance.counter_growth");
|
|
66
|
+
assert.equal(counterGrowth({ before: { flags: 5 }, after: { flags: 6 }, contract: { decisions: [{ choice: "counter-ok: flags one rollout flag, removed in #9" }] } }).length, 0);
|
|
67
|
+
assert.equal(counterGrowth({ before: { flags: 5 }, after: { flags: 6 }, result: { amendments: [{ kind: "decision", decision: { choice: "counter-ok: flags needed" }, why: "x" }] } }).length, 0);
|
|
68
|
+
assert.equal(counterExempt("flags", { decisions: [{ choice: "counter-ok: flags" }] }), false, "a reason is required");
|
|
69
|
+
assert.equal(counterExempt("flags", { decisions: [{ choice: "counter-ok: flagsx because" }] }), false, "another counter's decision does not exempt");
|
|
70
|
+
assert.equal(counterGrowth({ before: { flags: 5 }, after: { flags: 5 } }).length, 0);
|
|
71
|
+
assert.equal(counterGrowth({ before: null, after: { flags: 9 } }).length, 0);
|
|
72
|
+
});
|
|
73
|
+
});
|
|
@@ -76,6 +76,25 @@ export function reconcileClaims({ state, results, now, fail, settle }) {
|
|
|
76
76
|
|
|
77
77
|
const labelsOf = (v) => (v?.labels ?? []).map((l) => String(l?.name ?? l));
|
|
78
78
|
|
|
79
|
+
/** #5704: the hand-off a remediation merge posts; `kind=remediation` tells the live reconcile it is not a deferral. */
|
|
80
|
+
export const REMEDIATION_TRACKED_MARKER = "<!-- FORGE:TRACKED kind=remediation -->";
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* #5704: a remediation lane that exited 0 merged without the normal lane close or hand-off (the AlterLab#40851 orphan): post one
|
|
84
|
+
* FORGE:TRACKED comment while the issue is still open, so it stays open until the live reconcile sees it promoted and verified.
|
|
85
|
+
* Idempotent by the marker; best effort (a gh failure leaves the claim state as is).
|
|
86
|
+
*/
|
|
87
|
+
export async function postRemediationTracked({ watch, repo, io, issue, code }) {
|
|
88
|
+
try {
|
|
89
|
+
const v = JSON.parse(String(await io.gh(["issue", "view", String(issue), "-R", repo, "--json", "state,comments"])));
|
|
90
|
+
if (String(v?.state).toUpperCase() !== "OPEN" || (v.comments ?? []).some((c) => String(c?.body ?? "").includes(REMEDIATION_TRACKED_MARKER))) return false;
|
|
91
|
+
await io.gh(["issue", "comment", String(issue), "-R", repo, "--body", `${REMEDIATION_TRACKED_MARKER}
|
|
92
|
+
## Merged by remediation
|
|
93
|
+
issue-watch ${watch.name} remediated this parked issue (\`${code}\`) and the lane merged. It stays open until the fix is promoted to the live release and verified there (\`forgedock close reconcile\`, also run by \`probe --due\`).`]);
|
|
94
|
+
return true;
|
|
95
|
+
} catch { return false; }
|
|
96
|
+
}
|
|
97
|
+
|
|
79
98
|
/**
|
|
80
99
|
* One remediation lane per parked claim, at most `watch.max_remediations` per watch. A launched lane is polled each pass: exit 0 hands
|
|
81
100
|
* the issue to verification, any other exit makes it `needs-human` with the reason in a comment. A restarted watch re-launches a
|
|
@@ -98,7 +117,7 @@ export async function remediateStep({ watch, repo, io, state, handles, lanes = {
|
|
|
98
117
|
const res = h.poll();
|
|
99
118
|
if (!res) continue;
|
|
100
119
|
handles.delete(key(n));
|
|
101
|
-
if (res.code === 0) { r.status = "done"; settle(Number(n)); continue; }
|
|
120
|
+
if (res.code === 0) { r.status = "done"; settle(Number(n)); await postRemediationTracked({ watch, repo, io, issue: Number(n), code: r.code }); continue; }
|
|
102
121
|
r.status = "failed";
|
|
103
122
|
const reason = `remediation lane for \`${r.code}\` exited ${res.code}`;
|
|
104
123
|
state.outcomes[n] = { kind: "needs-human", code: r.code, at: now, reason };
|
|
@@ -49,3 +49,33 @@ test("#5529 redriveStep waits for claude on a missing-executable claim, re-drive
|
|
|
49
49
|
assert.equal(driven.filter((n) => n === 2).length, 2, "budget of 2 re-drives");
|
|
50
50
|
assert.equal(state.outcomes[3].kind, "parked");
|
|
51
51
|
});
|
|
52
|
+
|
|
53
|
+
test("remediateStep: a remediation exit 0 posts one FORGE:TRACKED hand-off while the issue is open (#5704)", async () => {
|
|
54
|
+
const { remediateStep, REMEDIATION_TRACKED_MARKER } = await import("./issuewatch-reconcile.mjs");
|
|
55
|
+
const comments = [];
|
|
56
|
+
let state = "OPEN";
|
|
57
|
+
const io = {
|
|
58
|
+
remediate: () => ({ poll: () => ({ code: 0 }) }),
|
|
59
|
+
gh: async (a) => {
|
|
60
|
+
if (a[1] === "view") return JSON.stringify({ state, comments: comments.map((body) => ({ body })) });
|
|
61
|
+
if (a[1] === "comment") { comments.push(a[a.indexOf("--body") + 1]); return ""; }
|
|
62
|
+
throw new Error(`unexpected gh ${a.join(" ")}`);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
const settled = [], failed = [];
|
|
66
|
+
const run = async (st) => { const handles = new Map(); await remediateStep({ watch: { name: "w" }, repo: "o/r", io, state: st, handles, now: 1, settle: (n) => settled.push(n), fail: (n) => failed.push(n) }); await remediateStep({ watch: { name: "w" }, repo: "o/r", io, state: st, handles, now: 2, settle: (n) => settled.push(n), fail: (n) => failed.push(n) }); };
|
|
67
|
+
const st = { outcomes: { 7: { kind: "parked", code: "conformance.e2e_unverified" } } };
|
|
68
|
+
await run(st);
|
|
69
|
+
assert.equal(st.remediated[7].status, "done");
|
|
70
|
+
assert.deepEqual(settled, [7]);
|
|
71
|
+
assert.deepEqual(failed, []);
|
|
72
|
+
assert.equal(comments.length, 1);
|
|
73
|
+
assert.ok(comments[0].startsWith(REMEDIATION_TRACKED_MARKER));
|
|
74
|
+
// idempotent: a second remediation of the same issue finds the marker and posts nothing
|
|
75
|
+
await run({ outcomes: { 7: { kind: "parked", code: "x" } } });
|
|
76
|
+
assert.equal(comments.length, 1);
|
|
77
|
+
// a closed issue gets nothing
|
|
78
|
+
state = "CLOSED"; comments.length = 0;
|
|
79
|
+
await run({ outcomes: { 7: { kind: "parked", code: "x" } } });
|
|
80
|
+
assert.equal(comments.length, 0);
|
|
81
|
+
});
|
package/bin/lean/lanecheck.mjs
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { readFileSync } from "node:fs";
|
|
11
11
|
import { findShimLoops } from "./heavy.mjs";
|
|
12
|
+
import { which } from "./toolchain.mjs";
|
|
12
13
|
|
|
13
14
|
/** The running CLI's package version. */
|
|
14
15
|
export const cliVersion = () => JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
@@ -76,13 +77,20 @@ export async function checkPoolAuth({ exec, router = null, credential = () => nu
|
|
|
76
77
|
return pass(code, `token resolved from ${source}${r ? "" : "; router unreachable (not an auth failure)"}`, "remote");
|
|
77
78
|
}
|
|
78
79
|
|
|
79
|
-
/**
|
|
80
|
+
/** #5745: `1.61.1`, `v1.61.1` or `1.61.1-rc.1` as [major, minor, patch]; null when it is not a semver. */
|
|
81
|
+
const semverOf = (v) => { const m = /^v?(\d+)\.(\d+)\.(\d+)(?:[-+][0-9A-Za-z.+-]*)?$/.exec(String(v ?? "").trim()); return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null; };
|
|
82
|
+
/** Same major version: the lane protocol is compatible across minor and patch releases. */
|
|
83
|
+
const sameMajor = (a, b) => { const x = semverOf(a), y = semverOf(b); return !!x && !!y && x[0] === y[0]; };
|
|
84
|
+
|
|
85
|
+
/** Every online pool agent runs the CLI's version, or a same-major one (#5745: skew warns in the detail, a major skew or an unparseable version blocks). `agents` is the router's `GET /agents` list (each spreads versionOf: version, image). */
|
|
80
86
|
export function checkPoolVersion({ exec, agents = null, cliVersion }) {
|
|
81
87
|
const code = C.PREFLIGHT_POOL_VERSION;
|
|
82
88
|
if (!usesPool(exec)) return pass(code, "skipped: no remote or hybrid execution", "remote");
|
|
83
89
|
if (!Array.isArray(agents)) return pass(code, "skipped: pool agents not readable", "remote");
|
|
84
|
-
const
|
|
85
|
-
if (!
|
|
90
|
+
const skewed = agents.filter((a) => a?.ok !== false && typeof a?.version === "string" && a.version !== cliVersion);
|
|
91
|
+
if (!skewed.length) return pass(code, `${agents.length} agent(s) at ${cliVersion}`, "remote");
|
|
92
|
+
const bad = skewed.filter((a) => !sameMajor(a.version, cliVersion));
|
|
93
|
+
if (!bad.length) return pass(code, skewed.map((a) => `agent ${a.name ?? "?"} runs ${a.version}, CLI is ${cliVersion} (compatible, same major)`).join("; ") + `; upgrade: ${UPGRADE_COMMAND}`, "remote");
|
|
86
94
|
return fail(code, bad.map((a) => `agent ${a.name ?? "?"} runs image version ${a.version}, CLI is ${cliVersion}`).join("; ") + `; upgrade: ${UPGRADE_COMMAND}`, "remote");
|
|
87
95
|
}
|
|
88
96
|
|
|
@@ -95,6 +103,22 @@ export function checkPathLoop({ env = {}, loops = findShimLoops }) {
|
|
|
95
103
|
return fail(code, found.map((l) => `${l.dir} wraps ${l.name} and resolves back to the heavy shim`).join("; "), "all");
|
|
96
104
|
}
|
|
97
105
|
|
|
106
|
+
/** #5806: the tools a batch's setup and lanes run; each must resolve on the batch env's PATH. */
|
|
107
|
+
export const BATCH_ENV_TOOLS = Object.freeze(["gh", "git", "node"]);
|
|
108
|
+
/**
|
|
109
|
+
* #5806: `which`-style probe (no shell) of the batch env: every tool of `tools` resolves on `env.PATH` (win32: `;` and PATHEXT).
|
|
110
|
+
* A batch whose pinned PATH lost them otherwise sits in setup with no lane and no error. @returns {{ok, missing, detail}}
|
|
111
|
+
*/
|
|
112
|
+
export function probeBatchEnv(env = {}, { tools = BATCH_ENV_TOOLS, platform = process.platform, find = which, access } = {}) {
|
|
113
|
+
const path = String(env?.PATH ?? env?.Path ?? "");
|
|
114
|
+
const pathext = env?.PATHEXT ?? (platform === process.platform ? process.env.PATHEXT : null) ?? ".COM;.EXE;.BAT;.CMD";
|
|
115
|
+
const missing = tools.filter((t) => !find(t, path, [], { platform, pathext, ...(access ? { access } : {}) }));
|
|
116
|
+
if (!missing.length) return { ok: true, missing, detail: `batch env PATH resolves ${tools.join(", ")}` };
|
|
117
|
+
const dirs = path.split(platform === "win32" ? ";" : ":").filter(Boolean);
|
|
118
|
+
const shown = dirs.slice(0, 4).join(platform === "win32" ? ";" : ":") + (dirs.length > 4 ? ` (+${dirs.length - 4} more)` : "");
|
|
119
|
+
return { ok: false, missing, detail: `${missing.join(", ")} not resolvable on the batch env PATH (${dirs.length ? `${dirs.length} entr${dirs.length === 1 ? "y" : "ies"}: ${shown}` : "empty"})` };
|
|
120
|
+
}
|
|
121
|
+
|
|
98
122
|
/** Parse the field names `gh <cmd> --json bogus` lists as available (null when the output has no list). */
|
|
99
123
|
export function availableFields(text) {
|
|
100
124
|
const m = /Available fields:\s*([\s\S]*)$/i.exec(String(text ?? ""));
|
|
@@ -6,7 +6,8 @@ import assert from "node:assert/strict";
|
|
|
6
6
|
import { mkdirSync, writeFileSync, chmodSync } from "node:fs";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
|
-
import { checkPoolAuth, checkPoolVersion, checkPathLoop, checkGhFields, availableFields, runLaneChecks, formatLaneChecks, UPGRADE_COMMAND } from "./lanecheck.mjs";
|
|
9
|
+
import { checkPoolAuth, checkPoolVersion, checkPathLoop, checkGhFields, availableFields, runLaneChecks, formatLaneChecks, UPGRADE_COMMAND, probeBatchEnv } from "./lanecheck.mjs";
|
|
10
|
+
import { which } from "./toolchain.mjs";
|
|
10
11
|
import { findShimLoops, heavyShimScript } from "./heavy.mjs";
|
|
11
12
|
import { orchestrate, deferPolicy } from "./orchestrate.mjs";
|
|
12
13
|
import { providerLanes, isCloneFailure } from "./execution.mjs";
|
|
@@ -55,11 +56,24 @@ describe("pool_auth shared resolver (#5131)", () => {
|
|
|
55
56
|
});
|
|
56
57
|
|
|
57
58
|
describe("pool_version", () => {
|
|
58
|
-
|
|
59
|
-
|
|
59
|
+
const ver = (agentVersion, cli = "1.39.0") => checkPoolVersion({ exec: pool, cliVersion: cli, agents: [{ name: "a1", ok: true, version: agentVersion }, { name: "a2", ok: true, version: cli }] });
|
|
60
|
+
it("a different major fails, naming the agent, image version, CLI version and upgrade command", () => {
|
|
61
|
+
const c = ver("0.37.0", "1.39.0");
|
|
60
62
|
assert.equal(c.ok, false); assert.equal(c.code, "preflight.pool_version");
|
|
61
|
-
assert.match(c.detail, /a1/); assert.match(c.detail, /
|
|
62
|
-
|
|
63
|
+
assert.match(c.detail, /a1/); assert.match(c.detail, /0\.37\.0/); assert.match(c.detail, /1\.39\.0/); assert.ok(c.detail.includes(UPGRADE_COMMAND)); assert.ok(!/a2/.test(c.detail));
|
|
64
|
+
});
|
|
65
|
+
it("#5745: minor and patch skew within the same major passes and notes the skew", () => {
|
|
66
|
+
for (const [agent, cli] of [["1.60.1", "1.61.1"], ["1.61.0", "1.61.1"], ["v1.61.1-rc.1", "1.61.1"]]) {
|
|
67
|
+
const c = ver(agent, cli);
|
|
68
|
+
assert.equal(c.ok, true, `${agent} vs ${cli}`); assert.equal(c.code, "preflight.pool_version"); assert.equal(c.scope, "remote");
|
|
69
|
+
assert.match(c.detail, /compatible, same major/); assert.ok(c.detail.includes(UPGRADE_COMMAND));
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
it("#5745: an unparseable differing version fails; an exact match is unchanged", () => {
|
|
73
|
+
assert.equal(ver("latest", "1.61.1").ok, false);
|
|
74
|
+
assert.equal(ver("1.61.1", "dev").ok, false);
|
|
75
|
+
const c = checkPoolVersion({ exec: pool, cliVersion: "1.39.0", agents: [{ name: "a", ok: true, version: "1.39.0" }] });
|
|
76
|
+
assert.equal(c.ok, true); assert.equal(c.detail, "1 agent(s) at 1.39.0");
|
|
63
77
|
});
|
|
64
78
|
});
|
|
65
79
|
|
|
@@ -104,6 +118,34 @@ describe("gh_fields", () => {
|
|
|
104
118
|
});
|
|
105
119
|
});
|
|
106
120
|
|
|
121
|
+
describe("#5806 batch env probe", () => {
|
|
122
|
+
const exe = (dir, name) => { mkdirSync(dir, { recursive: true }); const p = join(dir, name); writeFileSync(p, "#!/bin/sh\n"); chmodSync(p, 0o755); return p; };
|
|
123
|
+
|
|
124
|
+
it("resolves gh, git and node on the env's own PATH (no shell); a PATH reduced to one bogus entry names every missing tool", () => {
|
|
125
|
+
const d = tmpDir("envprobe-"), bin = join(d, "bin");
|
|
126
|
+
const names = process.platform === "win32" ? ["gh.exe", "git.exe", "node.cmd"] : ["gh", "git", "node"];
|
|
127
|
+
for (const n of names) exe(bin, n);
|
|
128
|
+
const ok = probeBatchEnv({ PATH: bin, PATHEXT: ".EXE;.CMD" });
|
|
129
|
+
assert.deepEqual([ok.ok, ok.missing], [true, []]);
|
|
130
|
+
const bad = probeBatchEnv({ PATH: join(d, "bogus") });
|
|
131
|
+
assert.deepEqual([bad.ok, bad.missing], [false, ["gh", "git", "node"]]);
|
|
132
|
+
assert.match(bad.detail, /^gh, git, node not resolvable on the batch env PATH \(1 entry: /);
|
|
133
|
+
assert.match(probeBatchEnv({}).detail, /\(empty\)$/);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("win32: `;`-separated PATH and PATHEXT extensions (.exe/.cmd); an extensionless file does not count", () => {
|
|
137
|
+
const files = new Set(["C:\\tools\\gh.exe", "D:\\git\\cmd\\git.cmd", "D:\\node\\node"]);
|
|
138
|
+
const access = (p) => { if (!files.has(p)) throw new Error("ENOENT"); };
|
|
139
|
+
const path = "C:\\tools;D:\\git\\cmd;D:\\node";
|
|
140
|
+
assert.equal(which("gh", path, [], { platform: "win32", pathext: ".COM;.EXE;.BAT;.CMD", access }), "C:\\tools\\gh.exe");
|
|
141
|
+
assert.equal(which("git", path, [], { platform: "win32", pathext: ".COM;.EXE;.BAT;.CMD", access }), "D:\\git\\cmd\\git.cmd");
|
|
142
|
+
const r = probeBatchEnv({ PATH: path, PATHEXT: ".EXE;.CMD" }, { platform: "win32", access });
|
|
143
|
+
assert.deepEqual(r.missing, ["node"], "D:\\node\\node has no PATHEXT extension");
|
|
144
|
+
assert.match(r.detail, /3 entries: C:\\tools;D:\\git\\cmd;D:\\node/);
|
|
145
|
+
assert.equal(probeBatchEnv({ Path: path }, { platform: "win32", access, tools: ["gh"] }).ok, true, "Windows' `Path` spelling");
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
107
149
|
describe("runLaneChecks / formatLaneChecks", () => {
|
|
108
150
|
it("returns every check and prints PASS or FAIL per line", async () => {
|
|
109
151
|
const checks = await runLaneChecks({ exec: pool, env: { PATH: "" }, cliVersion: "1.39.0", io: { router: () => ({ endpoint: "http://r", token: null }), credential: () => null } });
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Lane worktree confinement (#5825). Lane folders live under `<repo>/.claude/worktrees/`, inside the operator's checkout.
|
|
5
|
+
* A lane folder that lost its `.git` link (a partial delete on Windows, a pruned registration) is no repository of its own,
|
|
6
|
+
* so a git command run there walks up and acts on the operator's checkout (`git add -A` staged its untracked files).
|
|
7
|
+
*
|
|
8
|
+
* - `ceilingEnv(wt)`: `GIT_CEILING_DIRECTORIES` = the worktree's parent, for every lane git call and lane child process:
|
|
9
|
+
* discovery from inside the lane folder stops at the lane folder, it never reaches the checkout around it.
|
|
10
|
+
* - `verifyLaneWorktree()`: the lane folder has a `.git` link, `git rev-parse --show-toplevel` is the lane folder and
|
|
11
|
+
* `--git-common-dir` is the repository's. The engine runs it at lane start and before every git write.
|
|
12
|
+
* - `quarantineDir()`: a folder that is not a registered worktree is moved aside (never reused, never salvaged with git).
|
|
13
|
+
* Paths are compared in the platform's form: separators unified and case folded on win32, trailing separators dropped.
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, mkdirSync, realpathSync, renameSync } from "node:fs";
|
|
16
|
+
import { posix, win32 } from "node:path";
|
|
17
|
+
|
|
18
|
+
const api = (platform) => (platform === "win32" ? win32 : posix);
|
|
19
|
+
/** The separator git uses for GIT_CEILING_DIRECTORIES (its PATH_SEP): `;` on Windows, `:` elsewhere. Never path.delimiter of the host. */
|
|
20
|
+
export const ceilingSep = (platform = process.platform) => (platform === "win32" ? ";" : ":");
|
|
21
|
+
|
|
22
|
+
/** Canonical comparable form of a path on `platform`. */
|
|
23
|
+
export function normPath(p, { platform = process.platform } = {}) {
|
|
24
|
+
let s = String(p ?? "").trim();
|
|
25
|
+
if (platform === "win32") s = s.replace(/\\/g, "/").toLowerCase();
|
|
26
|
+
return s.length > 1 ? s.replace(/\/+$/, "") || "/" : s;
|
|
27
|
+
}
|
|
28
|
+
export const samePath = (a, b, o = {}) => Boolean(a) && Boolean(b) && normPath(a, o) === normPath(b, o);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* `{GIT_CEILING_DIRECTORIES}` for a lane worktree `wt`: its parent first, then any entries already in `env`. Null when the
|
|
32
|
+
* parent cannot be expressed as one entry (it contains the separator), so the caller refuses the lane instead of
|
|
33
|
+
* splitting a path into fragments.
|
|
34
|
+
*/
|
|
35
|
+
export function ceilingEnv(wt, { platform = process.platform, env = process.env } = {}) {
|
|
36
|
+
if (!wt) return null;
|
|
37
|
+
const sep = ceilingSep(platform), parent = api(platform).dirname(String(wt));
|
|
38
|
+
if (!parent || parent.includes(sep)) return null;
|
|
39
|
+
const rest = String(env?.GIT_CEILING_DIRECTORIES ?? "").split(sep).filter((d) => d && !samePath(d, parent, { platform }));
|
|
40
|
+
return { GIT_CEILING_DIRECTORIES: [parent, ...rest].join(sep) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const realOr = (p) => { try { return realpathSync.native(p); } catch { return p; } };
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Is `wt` a worktree of the repository at `cwd`? `git(args, {cwd, env})` is the injected git; `exists(p)` the fs probe.
|
|
47
|
+
* Returns {ok: true, evidence} or {ok: false, why, evidence}; never throws. Evidence: worktree, toplevel, common_dir,
|
|
48
|
+
* repo_common_dir (what git reported), for the engine-error detail.
|
|
49
|
+
*/
|
|
50
|
+
export async function verifyLaneWorktree({ git, exists, wt, cwd, platform = process.platform, real = realOr, env = process.env }) {
|
|
51
|
+
const P = api(platform), evidence = { worktree: wt };
|
|
52
|
+
const fail = (why) => ({ ok: false, why, evidence });
|
|
53
|
+
if (!(await exists(P.join(wt, ".git")))) return fail("the lane folder has no .git link (not a git worktree)");
|
|
54
|
+
const ceiling = ceilingEnv(wt, { platform, env });
|
|
55
|
+
if (!ceiling) return fail(`the worktree parent contains the ${ceilingSep(platform)} separator; git cannot be confined to it`);
|
|
56
|
+
let top, common, repoCommon;
|
|
57
|
+
try {
|
|
58
|
+
[top, common] = String(await git(["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"], { cwd: wt, env: ceiling })).trim().split(/\r?\n/).map((s) => s.trim());
|
|
59
|
+
} catch (e) { return fail(`git rev-parse failed in the lane folder: ${String(e?.stderr || e?.message || e).trim().split("\n")[0].slice(0, 200)}`); }
|
|
60
|
+
try { repoCommon = String(await git(["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd })).trim(); } catch (e) { return fail(`git rev-parse failed in the repository: ${String(e?.stderr || e?.message || e).trim().split("\n")[0].slice(0, 200)}`); }
|
|
61
|
+
Object.assign(evidence, { toplevel: top ?? null, common_dir: common ?? null, repo_common_dir: repoCommon });
|
|
62
|
+
if (!samePath(real(top), real(wt), { platform })) return fail(`git resolves the lane folder to toplevel ${top || "(none)"}, not the lane worktree`);
|
|
63
|
+
if (!samePath(real(common), real(repoCommon), { platform })) return fail(`the lane folder's git dir ${common || "(none)"} is not the repository's ${repoCommon}`);
|
|
64
|
+
return { ok: true, evidence };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** True when `git worktree list --porcelain` output lists `wt` (paths compared in the platform's form; git prints `/` on Windows). */
|
|
68
|
+
export function listedWorktree(porcelain, wt, { platform = process.platform } = {}) {
|
|
69
|
+
return String(porcelain ?? "").split(/\r?\n/).some((l) => l.startsWith("worktree ") && samePath(l.slice(9), wt, { platform }));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Move a lane folder that is not a registered worktree to `<parent>/.quarantine/<name>-<ms>` (kept for inspection, never
|
|
74
|
+
* reused). Returns the new path; throws when it cannot be moved (a locked file on Windows): the caller stops the lane.
|
|
75
|
+
*/
|
|
76
|
+
export function quarantineDir(wt, { now = Date.now, platform = process.platform, rename = renameSync, mkdir = (d) => mkdirSync(d, { recursive: true }), exists = existsSync } = {}) {
|
|
77
|
+
const P = api(platform), dir = P.join(P.dirname(wt), ".quarantine");
|
|
78
|
+
mkdir(dir);
|
|
79
|
+
let to = P.join(dir, `${P.basename(wt)}-${now()}`);
|
|
80
|
+
for (let i = 1; exists(to); i++) to = P.join(dir, `${P.basename(wt)}-${now()}-${i}`);
|
|
81
|
+
rename(wt, to);
|
|
82
|
+
return to;
|
|
83
|
+
}
|