@rightkit/release 0.6.52 → 0.6.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +6 -1
  2. package/adapter-env.mjs +16 -105
  3. package/admission-host.mjs +14 -1
  4. package/bin/darwin/rightkit-swap +0 -0
  5. package/bin/rightkit-gate.mjs +585 -404
  6. package/broker-admission.mjs +122 -2
  7. package/build-launch.mjs +52 -58
  8. package/build-release.mjs +2 -2
  9. package/cargo-ledger.mjs +24 -5
  10. package/cargo-target-shim.mjs +54 -23
  11. package/cargo-target.mjs +2 -2
  12. package/carried-adapter-run.mjs +7 -8
  13. package/carried-cargo-run.mjs +1 -1
  14. package/ci-compile-admission.mjs +1 -1
  15. package/clippy-route.mjs +65 -18
  16. package/compile-inputs.mjs +91 -15
  17. package/cross-targets.mjs +5 -3
  18. package/deps-cargo-lock.mjs +1 -1
  19. package/deterministic-scans.mjs +789 -259
  20. package/development.mjs +33 -7
  21. package/direct-receipt.mjs +3 -5
  22. package/feature-coverage.mjs +45 -9
  23. package/feature-partition.mjs +204 -0
  24. package/feature-sets.mjs +113 -0
  25. package/gate-acceptance.mjs +187 -115
  26. package/gate-seam.mjs +352 -0
  27. package/gate-serve.mjs +34 -2
  28. package/gate-stages.mjs +6 -2
  29. package/ghsa-audit.mjs +19 -4
  30. package/heavy-command.mjs +5 -4
  31. package/install-tauri-authenticode.mjs +73 -4
  32. package/ios-dev.mjs +3 -3
  33. package/ios-package-recipe.mjs +6 -6
  34. package/linux-setup.mjs +3 -2
  35. package/local-publish.mjs +113 -17
  36. package/lock-identity.mjs +24 -100
  37. package/managed-cargo.mjs +3 -3
  38. package/managed-root-guard.mjs +2 -2
  39. package/managed-roots.mjs +3 -3
  40. package/native-adapters.mjs +41 -244
  41. package/native-helpers.mjs +1 -1
  42. package/ownership-mandatory-set.json +16 -0
  43. package/pack-digest.mjs +1 -1
  44. package/package-recipe-targets.mjs +19 -11
  45. package/package.json +2 -2
  46. package/publication-gate.mjs +29 -6
  47. package/publish-cargo.mjs +4 -5
  48. package/publish-local-cargo.mjs +77 -1
  49. package/qualification-verify.mjs +76 -49
  50. package/receipt-signature.mjs +104 -0
  51. package/recipe-build.mjs +15 -2
  52. package/release-switch-registry.json +4 -0
  53. package/release-switch-scan.mjs +13 -10
  54. package/rightkit-versions.json +184 -170
  55. package/scan-digest.mjs +43 -14
  56. package/seam-broker.mjs +168 -0
  57. package/snapshot-check.mjs +4 -1
  58. package/snapshot-dependency-reuse.mjs +1 -1
  59. package/snapshot-metadata.mjs +24 -35
  60. package/snapshot.mjs +328 -49
  61. package/stage-commands.mjs +59 -5
  62. package/stage-ledger.mjs +2 -2
  63. package/{carried-cargo.mjs → stage-seam.mjs} +118 -70
  64. package/stage-sidecar.mjs +9 -7
  65. package/tauri-bundle-marker.mjs +5 -2
  66. package/tauri-locked.mjs +1 -1
  67. package/tool-build.mjs +8 -6
  68. package/unit-gate.mjs +40 -10
  69. package/broker-handshake.mjs +0 -160
  70. package/broker-wire.mjs +0 -278
  71. package/build-ownership.mjs +0 -1578
  72. package/cargo-shapes.mjs +0 -332
  73. package/cargo-width.mjs +0 -49
  74. package/carrier-census.mjs +0 -124
  75. package/clippy-equivalence.mjs +0 -202
  76. package/freshness-census.mjs +0 -405
  77. package/handle-revocation.mjs +0 -100
  78. package/handle-revocation.rust-vector.json +0 -1
  79. package/handle-revocation.vectors.json +0 -53
  80. package/legion-freeze-consumer.mjs +0 -241
  81. package/linux-qualifier.mjs +0 -83
  82. package/native-tool-planning.mjs +0 -94
  83. package/owner-process-proof.mjs +0 -14
  84. package/ownership-mark.mjs +0 -191
  85. package/ownership-recover.mjs +0 -78
  86. package/pnpm-adapter-grammar.mjs +0 -226
  87. package/provenance-verify.mjs +0 -413
  88. package/snapshot-broker.mjs +0 -808
  89. package/snapshot-request.mjs +0 -722
  90. package/unit-list-compile.mjs +0 -356
package/snapshot.mjs CHANGED
@@ -23,25 +23,26 @@
23
23
  // The gate never creates the managed root (Mac & Dell): it creates `snapshots` and `snapshots/<repo-key>` beneath one that exists,
24
24
  // and on the Mac that managed root must be a different device from `/`, so an unmounted volume can never yield a boot-volume
25
25
  // substitute (requireManagedRoot). A snapshot root is private to this user: created 0700, and an existing POSIX root that grants
26
- // group or other any access, or that another user owns, is refused (the premise under which build ownership may skip another user's
27
- // unreadable processes, build-ownership.mjs).
26
+ // group or other any access, or that another user owns, is refused.
28
27
  //
29
- // Exclusion: one sync per snapshot at a time (`<root>/<repo-key>.lock`, re-checked before every write and before the verdict).
30
- // It narrows, but cannot close, the window in which two processes both replace one stale lock; the per-repository build ownership
31
- // record held from before the sync through the stage (joint plan step 4) closes it, and the broker re-verifies the tree.
28
+ // Exclusion: the snapshot lock, the one exclusion of every route that syncs or reads a snapshot (`<root>/<repo-key>.lock`; reset plan
29
+ // section 3). The gate takes it before the sync (`takeSnapshotLock`) and holds it through every job and test of the batch; the sync
30
+ // re-checks it before every write and before the verdict, and the broker re-verifies the tree. On a broker host its body is the seam's
31
+ // `{ pid, identity, commit, token }` and a dead holder's lock is reclaimed only on the broker's proof that the snapshot is idle; on a host
32
+ // with no broker (Linux direct) it is `{ pid, host, startedAt, token }` and a holder proven gone (ESRCH, or the pid reused) is stale.
32
33
 
33
34
  import crypto from "node:crypto";
34
35
  import fs from "node:fs";
35
36
  import os from "node:os";
36
37
  import path from "node:path";
37
- import { spawnSync } from "./background-process.mjs";
38
+ import { spawn as spawnAsyncDefault, spawnSync } from "./background-process.mjs";
38
39
  import { readDiskPolicy, scratchRoots } from "./disk-policy.mjs";
39
40
  import { resolveManagedRoots } from "./managed-roots.mjs";
40
41
  import { HostConfigError, hostConfigFile, readSnapshotRootConfig } from "./snapshot-root-config.mjs";
41
42
  import { discoveryGit, discoveryRun, sealedRepoInfo, sealedRun, withSealedGit } from "./snapshot-git.mjs";
42
43
  import { SOURCE_IDENTITY_FILE, sourceIdentityBytes } from "./snapshot-identity.mjs";
43
- import { acquireBuildOwnership, migrateBirthlessRoot, OwnershipBusy, ownershipFile, recordRootBirth } from "./build-ownership.mjs";
44
- // The error class and the managed-root guard live in managed-root-guard.mjs, which build-ownership.mjs imports too (decision D4 rule 1).
44
+ import { parseIdentity, processIdentity } from "./gate-seam.mjs";
45
+ // The error class and the managed-root guard live in managed-root-guard.mjs (decision D4 rule 1).
45
46
  import { SnapshotError, requireManagedRoot } from "./managed-root-guard.mjs";
46
47
 
47
48
  export { SnapshotError, requireManagedRoot };
@@ -670,8 +671,210 @@ const statKey = (s) => `${s.size}:${s.mtimeNs}:${s.ctimeNs}:${s.ino}`;
670
671
  * progress. A reclaimer that died mid-reclaim leaves the reclaim file and every later sync is busy until it is removed (fail
671
672
  * closed); so does a dead holder whose pid was reused. `hooks` exist for the deterministic race fixture only.
672
673
  */
673
- export function acquireSnapshotLock(lockFile, hooks = {}) {
674
- const body = JSON.stringify({ pid: process.pid, host: os.hostname(), startedAt: new Date().toISOString(), token: crypto.randomUUID() });
674
+ // ---- the lock holder's own detached children (minimal process containment of the gate's own work outside the broker) -------------------------
675
+ // The gate runs test executables, right-release builds and heavy commands itself (GC-A08: tests run outside the broker), POSIX ones detached in their own
676
+ // process group so a timeout or cancel kills the whole group. A gate that crashes can leave such a group running and still reading or writing the snapshot,
677
+ // and the broker's SNAPSHOT_STATUS proof covers only broker jobs. So while this process holds a snapshot lock, every detached child it starts is recorded beside
678
+ // the lock (`<lock>.children/group-<pid>.json`, removed only once the whole group is gone), and a dead holder's lock is never reclaimed while a recorded group still answers.
679
+ // Windows children are contained by the lock holder's named job instead (below). Residual, named: a crash between the spawn returning and the record being written
680
+ // leaves that one group unrecorded.
681
+ let heldLockFile = null;
682
+ const childrenDirOf = (lockFile) => `${lockFile}.children`;
683
+ /** The variable that hands the held lock's record directory to this process's own children (right-release, heavy-command), which record their detached children there. */
684
+ export const LOCK_CHILDREN_ENV = "RIGHTKIT_SNAPSHOT_LOCK_CHILDREN";
685
+ /** Records a detached POSIX child of this process's held snapshot lock; returns the child. */
686
+ export function recordLockChild(child, { platform = process.platform, env = process.env } = {}) {
687
+ const dir = heldLockFile ? childrenDirOf(heldLockFile) : (typeof env?.[LOCK_CHILDREN_ENV] === "string" && path.isAbsolute(env[LOCK_CHILDREN_ENV]) ? env[LOCK_CHILDREN_ENV] : null);
688
+ if (!dir || platform === "win32" || !child || !Number.isInteger(child.pid) || child.pid <= 0) return child;
689
+ const file = path.join(dir, `group-${child.pid}.json`);
690
+ try { fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); fs.writeFileSync(file, JSON.stringify({ group: child.pid, by: process.pid, at: new Date().toISOString() }), { mode: 0o600 }); }
691
+ catch (error) { try { process.kill(-child.pid, "SIGKILL"); } catch { /* already gone */ } throw new SnapshotError("error", `the snapshot lock's child record ${file} cannot be written (${error.message}); the child was stopped`); }
692
+ // The root's exit does not end the group: a descendant it started (a backgrounded process with its own stdio) can outlive it in the same group.
693
+ // The record goes only on proof the whole group is gone (kill(-group, 0) is ESRCH); otherwise it stays and liveLockChildren keeps seeing the group.
694
+ const forget = () => {
695
+ try { process.kill(-child.pid, 0); return; } catch (e) { if (e?.code !== "ESRCH") return; }
696
+ try { fs.rmSync(file, { force: true }); } catch { /* left: a dead group never blocks a reclaim */ }
697
+ };
698
+ if (typeof child.once === "function") child.once("exit", forget);
699
+ return child;
700
+ }
701
+ // ---- Windows: the lock holder's process tree in a named Job Object (ported minimally from the deleted build-ownership.mjs) -------------------------
702
+ // Node keeps its Windows children in a kill-on-close job that sets SILENT_BREAKAWAY_OK, so a child's own children (a test's native helper, a build's
703
+ // background process) can leave it and outlive a crashed gate. So on Windows the lock holder puts itself in a named job `Local\RightKitSnapshotLock-<token>`
704
+ // before any work runs; its children and their descendants are created inside it. A holder process outside the job (started by `cmd /c start /b`, so it is
705
+ // cmd's child, not Node's) creates the job, assigns the gate, keeps the only handle and exits once the job is empty, writing `drained`. A self-check run as
706
+ // the gate's child asks Windows whether it is IN the job; under a Node parent whose job lets children leave silently it is OUT, and then nothing proves the
707
+ // tree gone, so the lock is refused before any work runs (fail closed).
708
+ export const WINDOWS_JOB_SCHEMA = "rightkit.snapshot-lock-job/1";
709
+ const windowsJobName = (token) => `Local\\RightKitSnapshotLock-${token}`;
710
+ // The holder's files are scoped to the lock generation (its token): a holder of an earlier lock of the same name, still alive until its own gate exits,
711
+ // writes only its own files and can never answer, or report drained, for the current one. Every report also names its job and is checked against it.
712
+ const holderNameOf = (token) => `job-holder-${crypto.createHash("sha256").update(String(token)).digest("hex").slice(0, 16)}.json`;
713
+ const HOLDER_NAME = /^job-holder-[0-9a-f]{16}\.json$/;
714
+ const jobRecordOf = (lockFile) => path.join(childrenDirOf(lockFile), "job.json");
715
+ const JOB_TYPE = `Add-Type @"
716
+ using System; using System.Runtime.InteropServices;
717
+ public static class RkJob {
718
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern IntPtr CreateJobObjectW(IntPtr a, string name);
719
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern IntPtr OpenJobObjectW(uint access, bool inherit, string name);
720
+ [DllImport("kernel32.dll", SetLastError=true)] public static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
721
+ [DllImport("kernel32.dll", SetLastError=true)] public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr proc);
722
+ [DllImport("kernel32.dll", SetLastError=true)] public static extern bool QueryInformationJobObject(IntPtr job, int cls, byte[] info, int len, IntPtr ret);
723
+ [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr h);
724
+ [DllImport("kernel32.dll", SetLastError=true)] public static extern bool IsProcessInJob(IntPtr proc, IntPtr job, out bool result);
725
+ [DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess();
726
+ public static int Active(IntPtr job) { var b = new byte[48]; if (!QueryInformationJobObject(job, 1, b, 48, IntPtr.Zero)) return -1; return BitConverter.ToInt32(b, 40); }
727
+ }
728
+ "@`;
729
+ const psString = (s) => `'${String(s).replace(/'/g, "''")}'`;
730
+ /** The holder: creates the job, puts the gate in it, keeps the only handle, answers fresh counts (`<file>.query` -> `<file>.ack`), exits at zero. */
731
+ export function windowsJobHolderScript({ name, pid, file }) {
732
+ return [
733
+ "$ErrorActionPreference = 'Stop'",
734
+ "try { Remove-Item -LiteralPath $PSCommandPath -Force } catch { }",
735
+ JOB_TYPE,
736
+ `$name = ${psString(name)}; $gate = [uint32]${Number(pid)}; $file = ${psString(file)}`,
737
+ `function Put($o) { $o.schema = '${WINDOWS_JOB_SCHEMA}'; $o.holder = $PID; $o.at = (Get-Date).ToUniversalTime().ToString('o'); $tmp = "$file.$PID.tmp"; [IO.File]::WriteAllText($tmp, ($o | ConvertTo-Json -Compress)); Move-Item -Force -LiteralPath $tmp -Destination $file }`,
738
+ "try {",
739
+ " $h = [RkJob]::CreateJobObjectW([IntPtr]::Zero, $name); $e = [Runtime.InteropServices.Marshal]::GetLastWin32Error()",
740
+ " if ($h -eq [IntPtr]::Zero) { throw \"CreateJobObject failed ($e)\" }",
741
+ " if ($e -eq 183) { throw \"job $name already exists\" }",
742
+ " $p = [RkJob]::OpenProcess(0x0101, $false, $gate); if ($p -eq [IntPtr]::Zero) { throw \"OpenProcess $gate failed ($([Runtime.InteropServices.Marshal]::GetLastWin32Error()))\" }",
743
+ " if (-not [RkJob]::AssignProcessToJobObject($h, $p)) { throw \"AssignProcessToJobObject failed ($([Runtime.InteropServices.Marshal]::GetLastWin32Error()))\" }",
744
+ " [RkJob]::CloseHandle($p) | Out-Null",
745
+ " Put @{ state = 'holding'; job = $name }",
746
+ "} catch { Put @{ state = 'failed'; job = $name; why = \"$_\" }; exit 1 }",
747
+ "$query = \"$file.query\"; $ack = \"$file.ack\"; $answered = ''",
748
+ "function Answer { try { $q = [IO.File]::ReadAllText($query) | ConvertFrom-Json; $n = [string]$q.nonce; if ($n -notmatch '^[0-9a-f]{32,128}$' -or $n -eq $script:answered) { return }; $c = [RkJob]::Active($h); $o = @{ schema = '" + WINDOWS_JOB_SCHEMA + "'; job = $name; nonce = $n; active = $c; holder = $PID; at = (Get-Date).ToUniversalTime().ToString('o') }; $tmp = \"$ack.$PID.tmp\"; [IO.File]::WriteAllText($tmp, ($o | ConvertTo-Json -Compress)); Move-Item -Force -LiteralPath $tmp -Destination $ack; $script:answered = $n } catch { } }",
749
+ "while ($true) { if ([IO.File]::Exists($query)) { Answer }; if ([RkJob]::Active($h) -eq 0) { Put @{ state = 'drained'; job = $name }; exit 0 }; Start-Sleep -Milliseconds 50 }",
750
+ ].join("\n");
751
+ }
752
+ export const windowsSelfCheckScript = (name) => [
753
+ "$ErrorActionPreference = 'Stop'", JOB_TYPE,
754
+ `$j = [RkJob]::OpenJobObjectW(0x0004, $false, ${psString(name)}); if ($j -eq [IntPtr]::Zero) { 'ERR:' + [Runtime.InteropServices.Marshal]::GetLastWin32Error(); exit 0 }`,
755
+ "$in = $false; if (-not [RkJob]::IsProcessInJob([RkJob]::GetCurrentProcess(), $j, [ref]$in)) { 'ERR:' + [Runtime.InteropServices.Marshal]::GetLastWin32Error(); exit 0 }",
756
+ "if ($in) { 'IN' } else { 'OUT' }",
757
+ ].join("\n");
758
+ const readJson = (file) => { try { return JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, "")); } catch { return null; } };
759
+ const sleepMs = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
760
+ /** The real Windows operations; tests pass their own. */
761
+ export const windowsJobOps = {
762
+ /** Starts the holder via `cmd /c start /b` (never a Node child: it must outlive the gate and stay outside Node's kill-on-close job). */
763
+ startHolder(scriptFile) { spawnDetachedViaCmd(scriptFile); },
764
+ /** `IN`, `OUT` or a throw: run as this gate's child. */
765
+ selfCheck(name) {
766
+ const r = spawnSync("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(windowsSelfCheckScript(name), "utf16le").toString("base64")], { encoding: "utf8", timeout: 60_000, windowsHide: true });
767
+ const out = String(r.stdout ?? "").trim();
768
+ if (r.error || r.status !== 0 || !/^(IN|OUT)$/m.test(out)) throw new Error(`the containment self-check gave no answer (${r.error?.message ?? out.slice(0, 120)})`);
769
+ return /^IN$/m.test(out) ? "IN" : "OUT";
770
+ },
771
+ sleep: sleepMs,
772
+ /** The host's last boot as Unix ms (the deleted build-ownership.mjs read it the same way: [DateTimeOffset] of LastBootUpTime, never local-time arithmetic). */
773
+ bootTime() {
774
+ const r = spawnSync("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from("'BOOT:' + ([DateTimeOffset](Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToUnixTimeMilliseconds()", "utf16le").toString("base64")], { encoding: "utf8", timeout: 60_000, windowsHide: true });
775
+ const m = /BOOT:(\d+)/.exec(String(r.stdout ?? ""));
776
+ if (r.error || r.status !== 0 || !m) throw new Error(`cannot read the boot time (${r.error?.message ?? String(r.stderr ?? "").trim().slice(0, 120)})`);
777
+ return Number(m[1]);
778
+ },
779
+ };
780
+ function spawnDetachedViaCmd(scriptFile) {
781
+ const child = spawnAsyncDefault("cmd.exe", ["/d", "/c", "start", "\"\"", "/b", "powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", scriptFile], { stdio: "ignore", windowsHide: true });
782
+ child.unref?.();
783
+ }
784
+ /** Puts this process (the new lock holder) in its lock's named job. Returns the record; throws when the holder cannot contain the gate. */
785
+ export function containLockHolder(lockFile, token, { ops = windowsJobOps, pid = process.pid, timeoutMs = 60_000 } = {}) {
786
+ const dir = childrenDirOf(lockFile); const holder = holderNameOf(token); const file = path.join(dir, holder); const name = windowsJobName(token);
787
+ fs.mkdirSync(dir, { recursive: true });
788
+ const script = `${file}.ps1`;
789
+ // A record left by an earlier holder of this lock name must never be read as this holder's report.
790
+ for (const f of [script, file, `${file}.query`, `${file}.ack`, jobRecordOf(lockFile)]) fs.rmSync(f, { force: true });
791
+ fs.writeFileSync(script, windowsJobHolderScript({ name, pid, file }), { flag: "wx" });
792
+ try {
793
+ ops.startHolder(script);
794
+ const until = Date.now() + timeoutMs;
795
+ for (;;) {
796
+ const state = readJson(file);
797
+ if (state?.schema === WINDOWS_JOB_SCHEMA && state.job === name && state.state === "holding") break;
798
+ if (state?.schema === WINDOWS_JOB_SCHEMA && state.job === name && state.state === "failed") throw new Error(`the job holder could not contain the gate: ${state.why}`);
799
+ if (Date.now() > until) throw new Error(`the job holder did not report within ${timeoutMs} ms`);
800
+ ops.sleep(50);
801
+ }
802
+ } finally { fs.rmSync(script, { force: true }); }
803
+ // Under a parent whose job lets children leave silently the gate's children are not in this job (self-check OUT): nothing would then prove its
804
+ // descendants gone, at its own release or after a crash, so the lock is refused before any work runs.
805
+ if (ops.selfCheck(name) !== "IN") throw new Error(`the gate is not contained by its job ${name} (self-check OUT: its parent's job lets children leave silently); refused before any work ran`);
806
+ const record = { schema: WINDOWS_JOB_SCHEMA, job: name, holder, contained: true, at: Date.now() };
807
+ fs.writeFileSync(jobRecordOf(lockFile), JSON.stringify(record));
808
+ return record;
809
+ }
810
+ /** A fresh count of the job from its holder (outside the job): `{ active }` or a throw (no answer in time is unknown, never the last count). */
811
+ export function queryJobHolder(file, { job, timeoutMs = 5000, sleep = sleepMs } = {}) {
812
+ if (typeof job !== "string" || !job) throw new Error("a fresh count needs the job it is about");
813
+ const nonce = crypto.randomBytes(16).toString("hex"); const query = `${file}.query`; const ack = `${file}.ack`;
814
+ fs.rmSync(ack, { force: true });
815
+ const tmp = `${query}.${crypto.randomUUID()}.tmp`;
816
+ fs.writeFileSync(tmp, JSON.stringify({ nonce }), { flag: "wx" });
817
+ try { fs.renameSync(tmp, query); } finally { fs.rmSync(tmp, { force: true }); }
818
+ try {
819
+ const until = Date.now() + timeoutMs;
820
+ for (;;) {
821
+ const answer = readJson(ack);
822
+ if (answer?.schema === WINDOWS_JOB_SCHEMA && answer.nonce === nonce && answer.job === job) {
823
+ if (!Number.isInteger(answer.active) || answer.active < 0) throw new Error(`the job holder's answer carries no count`);
824
+ return { active: answer.active };
825
+ }
826
+ const state = readJson(file);
827
+ if (state?.schema === WINDOWS_JOB_SCHEMA && state.job === job && state.state === "drained") return { active: 0 };
828
+ if (Date.now() > until) throw new Error(`the job holder did not answer a fresh count within ${timeoutMs} ms`);
829
+ sleep(25);
830
+ }
831
+ } finally { for (const f of [query, ack]) { try { fs.rmSync(f, { force: true }); } catch { /* the next query replaces it */ } } }
832
+ }
833
+ /**
834
+ * What still runs in `lockFile`'s job: [] when proven empty, else one descriptive entry (counts as live). `self` is how many of the job's processes are
835
+ * the asking holder itself (1 at its own release, 0 when judging a dead holder). No job record means no Windows job was ever made for this lock.
836
+ * A record that is not contained proves nothing, at the holder's own release or after it died: live (acquisition refuses a self-check OUT, so only a damaged record says so).
837
+ * A dead holder's job made before the host's last boot is gone (the reboot ended it); a holder killed without a reboot leaves the lock busy (fail closed).
838
+ */
839
+ export function windowsJobLive(lockFile, { self = 0, query = queryJobHolder, bootTime = () => windowsJobOps.bootTime() } = {}) {
840
+ let record = null;
841
+ try { record = JSON.parse(fs.readFileSync(jobRecordOf(lockFile), "utf8")); } catch (e) { if (e?.code === "ENOENT") return []; return [`job record unreadable (${e?.code ?? e?.message})`]; }
842
+ if (record?.schema !== WINDOWS_JOB_SCHEMA || typeof record.job !== "string" || typeof record.holder !== "string" || !HOLDER_NAME.test(record.holder)) return ["job record malformed"];
843
+ if (record.contained !== true) return [`job ${record.job} did not contain its holder's children: their end cannot be proven`];
844
+ // A dead holder's job made before the host's last boot: a reboot ended every process of it (and its out-of-job holder, which then never writes
845
+ // drained). Without this a reboot left the lock busy for good. An unreadable boot time proves nothing and falls through to the holder.
846
+ if (self === 0 && Number.isFinite(record.at)) {
847
+ let boot = null; try { boot = bootTime(); } catch { boot = null; }
848
+ if (Number.isFinite(boot) && boot > record.at) return [];
849
+ }
850
+ const file = path.join(childrenDirOf(lockFile), record.holder);
851
+ const state = readJson(file);
852
+ if (state?.schema === WINDOWS_JOB_SCHEMA && state.job === record.job && state.state === "drained") return [];
853
+ try { const { active } = query(file, { job: record.job }); return active - self > 0 ? [`job ${record.job} (${active - self} process(es))`] : []; }
854
+ catch (e) { return [`job ${record.job} unknown (${e.message})`]; }
855
+ }
856
+
857
+ /** The recorded process groups of `lockFile` that still answer (kill(-group, 0) is not ESRCH); a group that cannot be judged counts as alive.
858
+ * Only a missing record directory (ENOENT) means no records; any other enumeration error (EACCES, EIO, ENOTDIR) returns ["unreadable"], which every caller treats as live. */
859
+ export function liveLockChildren(lockFile, { kill = (pid, sig) => process.kill(pid, sig), readdir = (d) => fs.readdirSync(d), platform = process.platform, self = 0, windowsJob = windowsJobLive } = {}) {
860
+ if (platform === "win32") return windowsJob(lockFile, { self });
861
+ let names = [];
862
+ try { names = readdir(childrenDirOf(lockFile)).filter((n) => /^group-\d+\.json$/.test(n)); }
863
+ catch (e) { return e?.code === "ENOENT" ? [] : [`unreadable (${e?.code ?? e?.message ?? "unknown error"})`]; }
864
+ const live = [];
865
+ for (const n of names) {
866
+ const group = Number(n.slice("group-".length, -".json".length));
867
+ try { kill(-group, 0); live.push(group); } catch (e) { if (e?.code !== "ESRCH") live.push(group); }
868
+ }
869
+ return live;
870
+ }
871
+
872
+ export function acquireSnapshotLock(lockFile, hooks = {}, { body: seamBody = null, judge = null, platform = process.platform, windowsOps = windowsJobOps, identityOf = (pid) => processIdentity(pid, { platform: process.platform, spawnSync: (c, a, o) => spawnSync(c, a, o) }) } = {}) {
873
+ // The seam's lock body (reset plan section 3, gate-seam.mjs snapshotLockBody): exactly { pid, identity, commit, token }, which the broker reads at
874
+ // submission and before spawn. Without one, the legacy body { pid, host, startedAt, token } is written.
875
+ // The legacy body also names this process's birth identity (when readable), so a reused pid is told from the holder on a host with no broker proof to lean on.
876
+ let birth = null; if (!seamBody) { try { birth = identityOf(process.pid) ?? null; } catch { birth = null; } }
877
+ const body = JSON.stringify(seamBody ?? { pid: process.pid, host: os.hostname(), startedAt: new Date().toISOString(), token: crypto.randomUUID(), ...(typeof birth === "string" && birth ? { birth } : {}) });
675
878
  const held = () => { try { return fs.readFileSync(lockFile, "utf8") === body; } catch { return false; } };
676
879
  const busy = (why) => new SnapshotError("busy", why);
677
880
  const publish = (target, text) => {
@@ -684,8 +887,23 @@ export function acquireSnapshotLock(lockFile, hooks = {}) {
684
887
  const create = () => {
685
888
  if (!publish(lockFile, body)) return false;
686
889
  if (!held()) throw busy(`snapshot lock ${lockFile} was replaced by another process`);
687
- const release = () => { if (held()) fs.rmSync(lockFile, { force: true }); };
890
+ if (platform === "win32") {
891
+ try { containLockHolder(lockFile, JSON.parse(body).token, { ops: windowsOps }); }
892
+ catch (error) { try { fs.rmSync(childrenDirOf(lockFile), { recursive: true, force: true }); } catch { /* left */ } fs.rmSync(lockFile, { force: true }); throw new SnapshotError("error", `snapshot lock ${lockFile}: ${error.message}; the lock was not kept`); }
893
+ }
894
+ heldLockFile = lockFile;
895
+ process.env[LOCK_CHILDREN_ENV] = childrenDirOf(lockFile); // inherited by this process's children (they spawn with process.env or a copy made after this)
896
+ const release = () => {
897
+ if (!held()) return;
898
+ // A recorded child group still running keeps the lock: its holder is this process, so a later run sees a live holder, and after this process exits the reclaim waits for the group.
899
+ if (liveLockChildren(lockFile, { self: 1 }).length) return;
900
+ try { fs.rmSync(childrenDirOf(lockFile), { recursive: true, force: true }); } catch { /* empty records */ }
901
+ fs.rmSync(lockFile, { force: true });
902
+ if (heldLockFile === lockFile) { heldLockFile = null; delete process.env[LOCK_CHILDREN_ENV]; }
903
+ };
688
904
  release.held = held;
905
+ release.lockFile = lockFile;
906
+ release.token = JSON.parse(body).token;
689
907
  return release;
690
908
  };
691
909
  const read = () => { try { return fs.readFileSync(lockFile, "utf8"); } catch (e) { if (e.code === "ENOENT") return null; throw new SnapshotError("error", `cannot read ${lockFile}: ${e.message}`); } };
@@ -693,19 +911,49 @@ export function acquireSnapshotLock(lockFile, hooks = {}) {
693
911
  let holder = null;
694
912
  try { holder = JSON.parse(observed); } catch { holder = null; }
695
913
  // Locks appear whole, so one that cannot be parsed was not written by this protocol: never reclaimed automatically.
696
- if (!holder || !Number.isInteger(holder.pid) || holder.pid <= 0 || holder.pid > 0x7fffffff || typeof holder.host !== "string" || !holder.host) throw busy(`snapshot lock ${lockFile} cannot be read as a lock; remove it only if no sync is running`);
697
- if (holder.host !== os.hostname()) throw busy(`snapshot is held by pid ${holder.pid} on ${holder.host} since ${holder.startedAt}`);
914
+ if (!holder || !Number.isInteger(holder.pid) || holder.pid <= 0 || holder.pid > 0x7fffffff) throw busy(`snapshot lock ${lockFile} cannot be read as a lock; remove it only if no sync is running`);
915
+ const seam = typeof holder.identity === "string" ? parseIdentity(holder.identity) : null;
916
+ if (seam) {
917
+ // A seam lock: the holder's identity names its platform and pid; another platform's lock is never ours to judge.
918
+ if (seam.pid !== holder.pid || seam.platform !== process.platform) throw busy(`snapshot is held by ${holder.identity} for commit ${holder.commit}`);
919
+ } else {
920
+ if (typeof holder.host !== "string" || !holder.host) throw busy(`snapshot lock ${lockFile} cannot be read as a lock; remove it only if no sync is running`);
921
+ if (holder.host !== os.hostname()) throw busy(`snapshot is held by pid ${holder.pid} on ${holder.host} since ${holder.startedAt}`);
922
+ }
698
923
  // Only a holder proven gone (ESRCH) is stale; any other answer, EPERM included, leaves the lock alone.
699
924
  let probe = null;
700
925
  try { process.kill(holder.pid, 0); } catch (k) { probe = k.code ?? String(k); }
926
+ if (probe === null && seam) {
927
+ // The pid is alive. A seam lock carries the holder's birth identity, so a reused pid is told from the holder: another birth identity means the holder is gone (and the
928
+ // broker's proof still decides the reclaim, below); the same one means it is live; an identity that cannot be read proves nothing and leaves the lock alone.
929
+ let now = null; try { now = identityOf(holder.pid); } catch { now = null; }
930
+ if (typeof now !== "string" || !now) throw busy(`snapshot lock holder pid ${holder.pid} is alive and its birth identity cannot be read to tell it from a reused pid (${holder.identity})`);
931
+ if (now === holder.identity) throw busy(`snapshot is held by ${holder.identity} for commit ${holder.commit}`);
932
+ probe = "ESRCH"; // the pid now belongs to another process: the holder is gone
933
+ }
934
+ if (probe === null && typeof holder.birth === "string" && holder.birth) {
935
+ // A legacy lock that names its holder's birth identity: another identity at the pid means the pid was reused and the holder is gone; the same one is live; unreadable proves nothing.
936
+ let now = null; try { now = identityOf(holder.pid); } catch { now = null; }
937
+ if (typeof now === "string" && now && now !== holder.birth) probe = "ESRCH";
938
+ }
701
939
  if (probe === null) throw busy(`snapshot is held by pid ${holder.pid} since ${holder.startedAt}`);
702
940
  if (probe !== "ESRCH") throw busy(`snapshot lock holder pid ${holder.pid} cannot be proven gone (${probe})`);
941
+ // The holder is gone, but a process group it started (a test executable, a build, a heavy command) may still run against the snapshot: never reclaimed then.
942
+ const groups = (hooks.liveChildren ?? liveLockChildren)(lockFile);
943
+ if (groups.length) throw busy(`snapshot lock holder pid ${holder.pid} is gone, but process group(s) it started still run (${groups.join(", ")}); the lock is reclaimed once they end`);
944
+ // A dead seam holder may still have jobs queued, running or finalizing in the broker, or an unreaped process tree: its lock is reclaimed only when
945
+ // the caller's `judge(holder)` returns true on the broker's proof that all use of the snapshot ended. No judge, or an inconclusive one, means busy.
946
+ if (seam && (typeof judge !== "function" || judge(holder) !== true)) throw busy(`snapshot lock holder ${holder.identity} is gone, but the lock is reclaimed only on the broker's proof that every job of commit ${holder.commit} ended${typeof judge === "function" ? " (the broker gave no such proof)" : " (no broker proof is wired: GAP, reset plan section 3)"}`);
947
+ // The proof the reclaim rests on, named for the run's log line (`snapshot lock held <token> (reclaimed from <from>: <proof>)`).
948
+ return seam
949
+ ? { from: holder.identity, proof: `owner ${holder.identity} is gone and the broker showed the snapshot idle for commit ${holder.commit}` }
950
+ : { from: `pid ${holder.pid}`, proof: `owner pid ${holder.pid} on ${holder.host} is gone (no process answers to it)` };
703
951
  };
704
952
  const first = create();
705
953
  if (first) return first;
706
954
  const observed = read();
707
955
  if (observed === null) { const again = create(); if (again) return again; throw busy(`snapshot lock ${lockFile} was taken by another process`); }
708
- judgeStale(observed);
956
+ const reclaimed = judgeStale(observed);
709
957
  hooks.afterStaleRead?.();
710
958
  const reclaim = `${lockFile}.reclaim`;
711
959
  if (!publish(reclaim, body)) throw busy(`snapshot lock ${lockFile} is being reclaimed by another process (remove ${reclaim} only if no sync is running)`);
@@ -713,8 +961,10 @@ export function acquireSnapshotLock(lockFile, hooks = {}) {
713
961
  hooks.whileReclaiming?.();
714
962
  if (read() !== observed) throw busy(`snapshot lock ${lockFile} changed before it could be reclaimed`);
715
963
  fs.rmSync(lockFile, { force: true });
964
+ try { fs.rmSync(childrenDirOf(lockFile), { recursive: true, force: true }); } catch { /* only dead groups were recorded */ }
716
965
  const mine = create();
717
966
  if (!mine) throw busy(`snapshot lock ${lockFile} was taken by another process`);
967
+ mine.reclaimed = reclaimed;
718
968
  return mine;
719
969
  } finally {
720
970
  fs.rmSync(reclaim, { force: true });
@@ -793,6 +1043,41 @@ function ensureParents(dir, file) {
793
1043
  }
794
1044
  }
795
1045
 
1046
+ /**
1047
+ * Everything that must hold before the first write under the snapshot root, and where the repository's snapshot lives: the managed root exists on the
1048
+ * managed volume, the root is a private real directory (created 0700 when missing, beneath a parent that exists) and does not overlap the checkout.
1049
+ * Returns `{ dir }`, the snapshot directory. Shared by the sync and by `takeSnapshotLock`, so a lock is never the first thing written to a boot-volume
1050
+ * substitute for an unmounted managed root.
1051
+ */
1052
+ function prepareSnapshotDir({ repo, root, managedRoot, device }) {
1053
+ guardRoot(root, managedRoot, { device });
1054
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
1055
+ const rootStat = lstat(root);
1056
+ if (!rootStat?.isDirectory()) throw new SnapshotError("refused", `snapshot root ${root} is not a directory (a link is never followed)`);
1057
+ const dir = path.join(root, repo.key);
1058
+ if (inside(dir, repo.checkout) || inside(repo.checkout, dir)) throw new SnapshotError("refused", `snapshot ${dir} and checkout ${repo.checkout} overlap`);
1059
+ return { dir };
1060
+ }
1061
+
1062
+ /**
1063
+ * Takes the snapshot lock of `checkout`'s repository (`<root>/<repo-key>.lock`) and returns its release function, which also carries `held()`, `token`,
1064
+ * `lockFile` and, when a dead holder's lock was reclaimed, `reclaimed: { from, proof }`. The one exclusion of every route that syncs or reads a snapshot:
1065
+ * taken before the sync, held through every job and test of the batch, released only by the process that took it. `lock` is `{ body, judge, identityOf }`
1066
+ * as `acquireSnapshotLock` takes them (the seam's body and broker proof on a broker host; none on a host with no broker). Throws SnapshotError("busy")
1067
+ * while another process holds the snapshot.
1068
+ */
1069
+ export function takeSnapshotLock({ checkout, root = snapshotRoot(), managedRoot = hostManagedRootFor(root), device, lock = {} } = {}) {
1070
+ const repo = repositoryOf(checkout);
1071
+ const { dir } = prepareSnapshotDir({ repo, root, managedRoot, device });
1072
+ return acquireSnapshotLock(`${dir}.lock`, {}, { body: lock.body ?? null, judge: lock.judge ?? null, ...(lock.identityOf ? { identityOf: lock.identityOf } : {}) });
1073
+ }
1074
+
1075
+ /**
1076
+ * What a nested gate is handed to join the lock of the run that holds it: the token, the lock file and `held()`, and no way to release it. A nested check,
1077
+ * compile or sync passes it down and never takes a second lock; only the process that took the lock releases it.
1078
+ */
1079
+ export const lockView = (release) => ({ token: release.token, lockFile: release.lockFile, held: release.held, joined: true });
1080
+
796
1081
  /**
797
1082
  * Syncs commit `rev` of the repository at `checkout` into its snapshot directory and verifies the result is exactly the commit's
798
1083
  * tree. Returns `{ schema, path, repoKey, commit, tree, written, removed, modesFixed, unchanged, linksRemoved, hardLinksReplaced, ms }`.
@@ -802,25 +1087,23 @@ function ensureParents(dir, file) {
802
1087
  * filesystem fails. `managedRoot` (default: the host's, when `root` is or lies under the host's snapshot root) is the managed root
803
1088
  * that must already exist; `device` reads a path's device (tests inject it).
804
1089
  */
805
- export function syncSnapshot({ checkout, rev = "HEAD", root = snapshotRoot(), managedRoot = hostManagedRootFor(root), device, now = () => Date.now() } = {}) {
1090
+ // `lock`: the snapshot lock of this sync (reset plan section 3). `held` is a lock the caller already took with `takeSnapshotLock` for this same snapshot: the sync
1091
+ // uses it, re-checks it before every write and never releases it (the caller holds it through the batch). Without `held` the sync takes the lock itself, for the sync
1092
+ // alone: `body` is the seam's lock body the broker reads (gate-seam.mjs snapshotLockBody) and `judge` decides a dead holder's reclaim on the broker's proof.
1093
+ export function syncSnapshot({ checkout, rev = "HEAD", root = snapshotRoot(), managedRoot = hostManagedRootFor(root), device, now = () => Date.now(), lock = {} } = {}) {
806
1094
  const started = now();
807
1095
  const repo = repositoryOf(checkout);
808
1096
  const { commit, tree } = resolveCommit(repo.checkout, rev);
809
1097
  const entries = treeEntries(repo.checkout, commit);
810
1098
  refuseCaseCollisions(entries, commit);
811
1099
  // Before the first write: the managed root exists on the managed volume, and an existing root is private to this user.
812
- guardRoot(root, managedRoot, { device });
813
- // mkdir returns the first directory it created: a root that did not exist is born now, and build ownership keeps that birth (and
814
- // the boot it happened in) as the baseline for processes it cannot read.
815
- // A root made before birth records existed is emptied and born anew, only under this process's own free-host ownership, before
816
- // this sync's first write (build-ownership.mjs migrateBirthlessRoot).
817
- migrateBirthlessRoot(root);
818
- if (fs.mkdirSync(root, { recursive: true, mode: 0o700 }) !== undefined) recordRootBirth(root);
819
- const rootStat = lstat(root);
820
- if (!rootStat?.isDirectory()) throw new SnapshotError("refused", `snapshot root ${root} is not a directory (a link is never followed)`);
821
- const dir = path.join(root, repo.key);
822
- if (inside(dir, repo.checkout) || inside(repo.checkout, dir)) throw new SnapshotError("refused", `snapshot ${dir} and checkout ${repo.checkout} overlap`);
823
- const release = acquireSnapshotLock(`${dir}.lock`);
1100
+ const { dir } = prepareSnapshotDir({ repo, root, managedRoot, device });
1101
+ const joined = lock.held ?? null;
1102
+ if (joined) {
1103
+ if (typeof joined.held !== "function" || joined.lockFile !== `${dir}.lock`) throw new SnapshotError("error", `the snapshot lock ${joined.lockFile ?? "(none)"} is not the lock of ${dir}`);
1104
+ if (!joined.held()) throw new SnapshotError("busy", `snapshot lock ${dir}.lock is not held by this process`);
1105
+ }
1106
+ const release = joined ?? acquireSnapshotLock(`${dir}.lock`, {}, { body: lock.body ?? null, judge: lock.judge ?? null, ...(lock.identityOf ? { identityOf: lock.identityOf } : {}) });
824
1107
  const assertLockHeld = () => { if (!release.held()) throw new SnapshotError("busy", `snapshot lock ${dir}.lock is no longer held by this sync`); };
825
1108
  try {
826
1109
  const existing = lstat(dir);
@@ -1001,7 +1284,8 @@ export function syncSnapshot({ checkout, rev = "HEAD", root = snapshotRoot(), ma
1001
1284
  writeState(stateFile, { schema: STATE_SCHEMA, repo: repo.checkout, repoKey: repo.key, commit, tree, paths: [...wanted.keys()], stat: nextStat, syncedAt: new Date(now()).toISOString() });
1002
1285
  return { schema: SNAPSHOT_SCHEMA, path: dir, repoKey: repo.key, commit, tree, written, removed, modesFixed, unchanged, linksRemoved, hardLinksReplaced, casesFixed, identity, ms: now() - started };
1003
1286
  } finally {
1004
- release();
1287
+ // A lock the caller took is the caller's to release; a lock this sync took ends with it.
1288
+ if (!joined) release();
1005
1289
  }
1006
1290
  }
1007
1291
 
@@ -1049,9 +1333,11 @@ export function verifySnapshot({ checkout, rev = "HEAD", root = snapshotRoot(),
1049
1333
  * `rightkit-gate snapshot [--commit <rev>] [--verify [--env <sha256>]] [--json]`: sync (or with --verify only check) the commit's
1050
1334
  * snapshot. `--env <sha256>` (verify only) also requires the installed dependency environment to still be the recorded
1051
1335
  * `rightkit-gate env-digest --snapshot` digest; the gate supplies `deps.environmentDigest({ checkout, dir, commit, tree })`.
1052
- * Exit 0 the snapshot is the commit's tree and the build ownership taken for it was released, 1 mismatch / refused (unknown
1053
- * revision, a missing managed root, an open-mode root, a gitlink ...) / busy or the ownership record was kept (a survivor may still
1054
- * read the snapshot), 2 could not run. `o.home`, `o.configFile`, `o.managedRoot`, `o.device` are test injections.
1336
+ * Exit 0 the snapshot is the commit's tree and its lock was released, 1 mismatch / refused (unknown
1337
+ * revision, a missing managed root, an open-mode root, a gitlink ...) / busy (another process holds the snapshot lock), 2 could not run.
1338
+ * A sync runs under the snapshot lock only, taken before the first write: `deps.lockFor({ checkout, commit, root })` (the gate's seam lock on a broker host)
1339
+ * returns `{ lock }` (the lock arguments of `acquireSnapshotLock`) or `{ refusal }`; without it the legacy lock is taken. The lock covers the sync alone: this
1340
+ * command submits no job. `o.home`, `o.configFile`, `o.managedRoot`, `o.device` are test injections.
1055
1341
  */
1056
1342
  export function snapshotCommand(o, args, deps = {}) {
1057
1343
  const allowed = new Set(["--commit", "--verify", "--json", "--env"]);
@@ -1066,37 +1352,30 @@ export function snapshotCommand(o, args, deps = {}) {
1066
1352
  if (envAt >= 0 && typeof deps.environmentDigest !== "function") { o.err("rightkit-gate: snapshot --env cannot compute the environment digest in this process"); return 2; }
1067
1353
  const i = args.indexOf("--commit");
1068
1354
  const rev = i >= 0 ? args[i + 1] : "HEAD";
1069
- let ownership = null;
1070
1355
  let code = 2;
1071
1356
  try {
1072
1357
  const platform = o.platform ?? process.platform;
1073
1358
  const root = o.snapshotRoot ?? snapshotRoot({ platform, env: o.env, ...(o.home ? { home: o.home } : {}), ...(o.configFile ? { configFile: o.configFile } : {}) });
1074
1359
  const managedRoot = o.managedRoot !== undefined ? o.managedRoot : hostManagedRootFor(root, { platform });
1075
- // The managed root exists (the gate never creates it) and the root is private, BEFORE build ownership is taken: taking it
1076
- // creates directories of its own, and must never be what brings a missing managed root into being.
1360
+ // The managed root exists (the gate never creates it) and the root is private, BEFORE the lock is taken: taking it
1361
+ // writes into the root, and must never be what brings a missing managed root into being.
1077
1362
  guardRoot(root, managedRoot, { device: o.device });
1078
- // A sync replaces snapshot bytes, so it runs only under the repository's build ownership, taken before the first write (joined when
1079
- // this gate already holds it); a verify only reads.
1080
- if (!verify) {
1081
- const repo = repositoryOf(o.cwd);
1082
- ownership = (o.acquireOwnership ?? acquireBuildOwnership)({ file: ownershipFile({ platform: o.platform, beside: o.snapshotRoot, repository: repo.key }), stage: "snapshot", snapshot: path.join(root, repo.key), commit: resolveCommit(repo.checkout, rev).commit, platform: o.platform, env: o.env });
1363
+ let lock = {};
1364
+ if (!verify && typeof deps.lockFor === "function") {
1365
+ const taken = deps.lockFor({ checkout: o.cwd, commit: resolveCommit(repositoryOf(o.cwd).checkout, rev).commit, root });
1366
+ if (taken?.refusal) { o.err(taken.refusal); return 1; }
1367
+ lock = taken?.lock ?? {};
1083
1368
  }
1369
+ // A sync replaces snapshot bytes, so it runs only under the snapshot lock, taken before the first write and released when the sync ends (this
1370
+ // command submits no job); a verify only reads.
1084
1371
  const r = verify ? verifySnapshot({ checkout: o.cwd, rev, root, managedRoot, device: o.device, ...(envAt >= 0 ? { environment: { expected: args[envAt + 1], compute: deps.environmentDigest } } : {}) })
1085
- : syncSnapshot({ checkout: o.cwd, rev, root, managedRoot, device: o.device });
1086
- if (ownership) r.ownership = { handle: ownership.handle, joined: ownership.joined, reclaimed: ownership.reclaimed };
1372
+ : syncSnapshot({ checkout: o.cwd, rev, root, managedRoot, device: o.device, lock: { body: lock.body ?? null, judge: lock.judge ?? null, ...(lock.identityOf ? { identityOf: lock.identityOf } : {}) } });
1087
1373
  if (args.includes("--json")) o.out(JSON.stringify(r));
1088
1374
  else o.out(`rightkit-gate: snapshot ${r.path} commit=${r.commit} tree=${r.tree}${"written" in r ? ` written=${r.written} removed=${r.removed} modes=${r.modesFixed} links=${r.linksRemoved} unchanged=${r.unchanged} ms=${r.ms}` : " verified"}`);
1089
1375
  code = 0;
1090
1376
  } catch (e) {
1091
1377
  o.err(`rightkit-gate: snapshot ${e.code ?? "error"}${e.reason ? ` (${e.reason})` : ""}: ${e.message}`);
1092
- code = (e instanceof SnapshotError && e.code !== "error") || e instanceof OwnershipBusy ? 1 : 2;
1093
- } finally {
1094
- const r = ownership?.release();
1095
- // A kept record means a survivor may still read the snapshot (or the host is not released): never a clean exit for a caller to script on.
1096
- if (r?.released === false && !ownership.joined) {
1097
- o.err(`rightkit-gate: snapshot failed: build ownership ${ownership.handle} kept: ${r.why}`);
1098
- if (code === 0) code = 1;
1099
- }
1378
+ code = e instanceof SnapshotError && e.code !== "error" ? 1 : 2;
1100
1379
  }
1101
1380
  return code;
1102
1381
  }
@@ -6,14 +6,68 @@ import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { CARGO_METADATA_ARGS, cargoPackageArgs, localTestPlan, npmPackArgs, qualifyFmtArgs } from "./local-publish.mjs";
8
8
  import { SWAP_HELPER_CARGO_ARGS, SWAP_HELPER_METADATA_ARGS, SWAP_HELPER_PACKAGE } from "./swap-helper-bundle.mjs";
9
- import { carriedRequestOf, lockedArgv, splitCarriedArgs } from "./snapshot-request.mjs";
10
- import { directCargoShape } from "./cargo-target-shim.mjs";
9
+ import { splitStageArgs } from "./stage-seam.mjs";
10
+ import { cargoCommandIndex, directCargoShape, expandCargoAliases } from "./cargo-target-shim.mjs";
11
+
12
+ // ---- the argv a stage child's cargo call sends (moved here from snapshot-request.mjs, deleted at plan step 5) ----
13
+ /** cargo-ndk's own options that take a value (outer grammar): `cargo ndk [-t <abi>] [-p|--platform <api>] [-o <dir>] ... <cargo subcommand> [cargo args]`. */
14
+ const NDK_VALUE_OPTIONS = new Set(["-t", "--target", "-o", "--output-dir", "-p", "--platform"]);
15
+ const NDK_INNER_LOCKED = new Set(["build", "b", "check", "c", "test", "t", "bench", "clippy", "doc", "rustc", "rustdoc", "run", "r"]);
16
+
17
+ /**
18
+ * GB-62: `cargo ndk <outer options> build <cargo args>` is two grammars. The immutable-dependency flag belongs to the INNER Cargo command, so it is
19
+ * inserted right after that inner subcommand (never after `ndk`, where cargo-ndk would read it as its own option, and never before it). Returns the argv
20
+ * unchanged when the inner command is not a locked-class command, already carries `--locked`/`--frozen` before `--`, or cannot be found.
21
+ */
22
+ function lockedNdkArgv(words) {
23
+ const end = words.indexOf("--");
24
+ const own = end < 0 ? words : words.slice(0, end);
25
+ let i = words.findIndex((w) => w === "ndk");
26
+ if (i < 0) return words;
27
+ for (i += 1; i < own.length; i += 1) {
28
+ const w = own[i];
29
+ if (NDK_VALUE_OPTIONS.has(w)) { i += 1; continue; }
30
+ if (w.startsWith("-")) continue;
31
+ break;
32
+ }
33
+ if (i >= own.length || !NDK_INNER_LOCKED.has(own[i])) return words;
34
+ if (own.slice(i + 1).some((w) => w === "--locked" || w === "--frozen")) return words;
35
+ return [...words.slice(0, i + 1), "--locked", ...words.slice(i + 1)];
36
+ }
37
+
38
+ /** The cargo commands the gate sends with `--locked`: the ones that compile (`package` always: an observation already carries `--locked`, so adding it changes nothing). The broker alone classifies a call. */
39
+ const LOCKED_COMMANDS = new Set(["build", "check", "test", "bench", "clippy", "doc", "run", "rustc", "rustdoc", "fix", "publish", "package", "nextest"]);
40
+
41
+ function lockedArgv(argv) {
42
+ // GB-01: the standard aliases are expanded BEFORE locking and hashing, so what the gate sends, signs and digests is what the broker classifies
43
+ // (a committed `.cargo/config.toml` [alias] can never redefine it). Only the subcommand token changes.
44
+ const words = expandCargoAliases(argv);
45
+ const i = cargoCommandIndex(words);
46
+ if (i === null) return words;
47
+ if (words[i] === "ndk") return lockedNdkArgv(words);
48
+ if (!LOCKED_COMMANDS.has(words[i])) return words;
49
+ const end = words.indexOf("--");
50
+ if ((end < 0 ? words : words.slice(0, end)).some((w) => w === "--locked" || w === "--frozen")) return words;
51
+ return [...words.slice(0, i + 1), "--locked", ...words.slice(i + 1)];
52
+ }
53
+
54
+ /**
55
+ * What a stage child's cargo call sends the broker (the seam, stage-seam.mjs runStageCargo) for `args` run from `cwd` (a posix path relative to the workspace root, "." for the root): the
56
+ * argv as signed (`requestedArgv`: no --manifest-path, `--locked` added to a build or run) and the directory it runs in (`cwd` joined
57
+ * with the manifest's directory). Returns `{ argv, cwd }` or null when the call would be refused.
58
+ */
59
+ export function carriedRequestOf(args, cwd = ".") {
60
+ const split = splitStageArgs(args);
61
+ if (split.refusal) return null;
62
+ const dir = split.manifestPath === null ? cwd : path.posix.normalize(path.posix.join(cwd, path.posix.dirname(split.manifestPath.replaceAll("\\", "/"))));
63
+ return { argv: lockedArgv(split.words), cwd: dir === "" ? "." : dir };
64
+ }
11
65
 
12
66
  /** Stands for the one argument that is a fresh absolute scratch path (`pnpm pack --pack-destination <mkdtemp>`). */
13
67
  export const ANY_ABSOLUTE_PATH = Object.freeze({ anyAbsolutePath: true });
14
68
  const PNPM = (...argvs) => ({ kind: "adapter", adapter: "rightkit-pnpm", argvs });
15
69
  /**
16
- * A cargo command as a broker host receives it. Every Cargo call of a snapshot stage is carried (carried-cargo.mjs): `--manifest-path` is
70
+ * A cargo command as a broker host receives it. Every Cargo call of a snapshot stage goes through the seam (stage-seam.mjs): `--manifest-path` is
17
71
  * not sent (the call runs from the manifest's directory) and a build or run is sent with `--locked`, so the signed `requestedArgv` is
18
72
  * that argv and the signed `workspace` is that directory of the checkout, never the spelling the stage's code wrote. `cwd` is the
19
73
  * directory the stage runs the command from, relative to the repository root; the row keeps the directory the call runs in.
@@ -21,7 +75,7 @@ const PNPM = (...argvs) => ({ kind: "adapter", adapter: "rightkit-pnpm", argvs }
21
75
  const CARGO = (cwd, ...argvs) => {
22
76
  const carried = argvs.map((argv) => carriedRequestOf(argv, cwd) ?? { argv, cwd });
23
77
  if (new Set(carried.map((c) => c.cwd)).size !== 1) throw new Error(`the spellings of one cargo command run in different directories: ${argvs.map((a) => a.join(" ")).join(" | ")}`);
24
- // GC-A11: a command of the direct shape (directCargoShape, the one list carried-cargo.mjs runs by) compiles nothing and runs directly,
78
+ // GC-A11: a command of the direct shape (directCargoShape, the one list stage-seam.mjs runs by) compiles nothing and runs directly,
25
79
  // so it makes no broker job and no signed receipt: the row is `direct`, the stage owes its recorded direct ledger entry instead.
26
80
  const direct = carried.every((c) => directCargoShape(c.argv));
27
81
  return { kind: "cargo", argvs: carried.map((c) => c.argv), cwd: carried[0].cwd, ...(direct ? { direct: true } : {}) };
@@ -119,7 +173,7 @@ export function directRowsNotRun(rows, entries) {
119
173
  const problems = [];
120
174
  for (const row of rows.filter((r) => r.direct === true)) {
121
175
  const matching = pool.filter((e) => {
122
- const split = splitCarriedArgs(Array.isArray(e.argv) ? e.argv : []);
176
+ const split = splitStageArgs(Array.isArray(e.argv) ? e.argv : []);
123
177
  if (split.refusal) return false;
124
178
  const dir = posixOf(split.manifestPath === null ? e.cwd : path.resolve(String(e.cwd), path.dirname(split.manifestPath)));
125
179
  const words = lockedArgv(split.words);
package/stage-ledger.mjs CHANGED
@@ -191,8 +191,8 @@ export function reportedPaths(result) {
191
191
 
192
192
  /**
193
193
  * The cross-check with `.rightkit/compile-inputs.json` (decision 2, Q1): for each declared input that covers ledger entries, the digest
194
- * the compile receipt names must equal the gate's own digest of those bytes (compile-inputs.mjs judgeCompileInputs, the broker's
195
- * algorithm). Returns problems; `judge` is judgeCompileInputs.
194
+ * the compile receipt names must equal the gate's own digest of those bytes (compile-inputs.mjs judgeCompileInputs: per file its
195
+ * name, NUL, bytes, NUL, the digest the direct receipt records). Returns problems; `judge` is judgeCompileInputs.
196
196
  */
197
197
  export function declaredInputProblems({ snapshot, entries, receiptDigests, judge }) {
198
198
  const judged = judge(snapshot);