@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.
- package/README.md +6 -1
- package/adapter-env.mjs +16 -105
- package/admission-host.mjs +14 -1
- package/bin/darwin/rightkit-swap +0 -0
- package/bin/rightkit-gate.mjs +585 -404
- package/broker-admission.mjs +122 -2
- package/build-launch.mjs +52 -58
- package/build-release.mjs +2 -2
- package/cargo-ledger.mjs +24 -5
- package/cargo-target-shim.mjs +54 -23
- package/cargo-target.mjs +2 -2
- package/carried-adapter-run.mjs +7 -8
- package/carried-cargo-run.mjs +1 -1
- package/ci-compile-admission.mjs +1 -1
- package/clippy-route.mjs +65 -18
- package/compile-inputs.mjs +91 -15
- package/cross-targets.mjs +5 -3
- package/deps-cargo-lock.mjs +1 -1
- package/deterministic-scans.mjs +789 -259
- package/development.mjs +33 -7
- package/direct-receipt.mjs +3 -5
- package/feature-coverage.mjs +45 -9
- package/feature-partition.mjs +204 -0
- package/feature-sets.mjs +113 -0
- package/gate-acceptance.mjs +187 -115
- package/gate-seam.mjs +352 -0
- package/gate-serve.mjs +34 -2
- package/gate-stages.mjs +6 -2
- package/ghsa-audit.mjs +19 -4
- package/heavy-command.mjs +5 -4
- package/install-tauri-authenticode.mjs +73 -4
- package/ios-dev.mjs +3 -3
- package/ios-package-recipe.mjs +6 -6
- package/linux-setup.mjs +3 -2
- package/local-publish.mjs +113 -17
- package/lock-identity.mjs +24 -100
- package/managed-cargo.mjs +3 -3
- package/managed-root-guard.mjs +2 -2
- package/managed-roots.mjs +3 -3
- package/native-adapters.mjs +41 -244
- package/native-helpers.mjs +1 -1
- package/ownership-mandatory-set.json +16 -0
- package/pack-digest.mjs +1 -1
- package/package-recipe-targets.mjs +19 -11
- package/package.json +2 -2
- package/publication-gate.mjs +29 -6
- package/publish-cargo.mjs +4 -5
- package/publish-local-cargo.mjs +77 -1
- package/qualification-verify.mjs +76 -49
- package/receipt-signature.mjs +104 -0
- package/recipe-build.mjs +15 -2
- package/release-switch-registry.json +4 -0
- package/release-switch-scan.mjs +13 -10
- package/rightkit-versions.json +184 -170
- package/scan-digest.mjs +43 -14
- package/seam-broker.mjs +168 -0
- package/snapshot-check.mjs +4 -1
- package/snapshot-dependency-reuse.mjs +1 -1
- package/snapshot-metadata.mjs +24 -35
- package/snapshot.mjs +328 -49
- package/stage-commands.mjs +59 -5
- package/stage-ledger.mjs +2 -2
- package/{carried-cargo.mjs → stage-seam.mjs} +118 -70
- package/stage-sidecar.mjs +9 -7
- package/tauri-bundle-marker.mjs +5 -2
- package/tauri-locked.mjs +1 -1
- package/tool-build.mjs +8 -6
- package/unit-gate.mjs +40 -10
- package/broker-handshake.mjs +0 -160
- package/broker-wire.mjs +0 -278
- package/build-ownership.mjs +0 -1578
- package/cargo-shapes.mjs +0 -332
- package/cargo-width.mjs +0 -49
- package/carrier-census.mjs +0 -124
- package/clippy-equivalence.mjs +0 -202
- package/freshness-census.mjs +0 -405
- package/handle-revocation.mjs +0 -100
- package/handle-revocation.rust-vector.json +0 -1
- package/handle-revocation.vectors.json +0 -53
- package/legion-freeze-consumer.mjs +0 -241
- package/linux-qualifier.mjs +0 -83
- package/native-tool-planning.mjs +0 -94
- package/owner-process-proof.mjs +0 -14
- package/ownership-mark.mjs +0 -191
- package/ownership-recover.mjs +0 -78
- package/pnpm-adapter-grammar.mjs +0 -226
- package/provenance-verify.mjs +0 -413
- package/snapshot-broker.mjs +0 -808
- package/snapshot-request.mjs +0 -722
- package/unit-list-compile.mjs +0 -356
package/build-ownership.mjs
DELETED
|
@@ -1,1578 +0,0 @@
|
|
|
1
|
-
// Per-repository build ownership (docs/GATE-CONTRACT.md §1 "Commit-only build", "Broker lease"; joint plan step 4, G1; rightkit#1367).
|
|
2
|
-
//
|
|
3
|
-
// The gate acquires the build ownership of the repository it is building BEFORE it syncs that repository's snapshot and holds it
|
|
4
|
-
// until the stage completes, so no other request can replace that snapshot while anything reads it. One owner per repository, at
|
|
5
|
-
// one fixed location per repository (`ownershipFile`: `<managed root>/build-ownership/<repository key>/owner.json` on Mac & Dell,
|
|
6
|
-
// `~/.local/state/rightkit/build-ownership/<repository key>/owner.json` on Linux), where the key is the snapshot directory's own
|
|
7
|
-
// key (`snapshot.repositoryOf(root).key`); never derived from the snapshot root or from an environment variable. Two repositories
|
|
8
|
-
// never contend: how many builds run, and in what order, is the broker's alone. The snapshot's own sync lock only covers the sync
|
|
9
|
-
// itself. `build-ownership/` and each repository directory are mode 0700 and refused when group- or other-accessible (`ensureOwnershipDir`).
|
|
10
|
-
//
|
|
11
|
-
// The owner record is written whole (create-exclusive) and names a fresh handle (the `ownership.handle` a broker request carries),
|
|
12
|
-
// the gate's pid & start identity, the stage, snapshot & commit, how the gate's children are contained, and whether a broker
|
|
13
|
-
// request may have been submitted under this handle. The handle exists before any sync or submit.
|
|
14
|
-
//
|
|
15
|
-
// A dead gate PID is NOT enough to take ownership over: compilers and Class A children can outlive a crashed gate and still read
|
|
16
|
-
// the snapshot. A record is reclaimed only on positive proof that everything it covers is gone:
|
|
17
|
-
// - the owner process is gone (not running, or its pid now runs a process with another start identity), and
|
|
18
|
-
// - its covered children are gone:
|
|
19
|
-
// Windows: the gate runs inside its own named Job Object (every descendant joins it, detached ones and those Node nests in
|
|
20
|
-
// its own job included; measured on the Dell, D:\scratch\rk-step4\dell-jobexp.log). A holder process outside the gate's
|
|
21
|
-
// jobs keeps the job's only handle and records `drained` once the job has no active process. Proof: the job opens with 0
|
|
22
|
-
// active, or it is gone and its holder recorded `drained` (or `failed` before the gate ever ran inside it). A gate whose
|
|
23
|
-
// launcher's job lets children leave silently (a Node parent) cannot hold its children in the job; a self-check at
|
|
24
|
-
// acquisition records that (`contained: false`), and such a gate's crash is never cleared except by a reboot.
|
|
25
|
-
// POSIX, four nets, all of which must be clear: (1) the gate's process group, counting members started after the
|
|
26
|
-
// ownership whose ancestry leads to the owner, to an orphan (re-parented to pid 1) or to ANY other process that predates
|
|
27
|
-
// the ownership (an orphan adopted by a subreaper such as systemd --user or WSL's init reads that way; only the owner's
|
|
28
|
-
// recorded parent, or a process that shares the member's group, is a peer that is not the gate's child); (2) no process
|
|
29
|
-
// whose environment carries the handle (RIGHTKIT_BUILD_OWNERSHIP=<handle>), which catches a descendant that started its
|
|
30
|
-
// own session (Linux /proc/<pid>/environ; macOS `ps eww`, which hides the environment of Apple platform binaries only);
|
|
31
|
-
// (3) no process that uses the snapshot directory in any way that survives a new session, a scrubbed environment and a
|
|
32
|
-
// working directory elsewhere: its working or root directory, executable, an open file descriptor or a mapped file
|
|
33
|
-
// inside it (Linux /proc/<pid>/{cwd,root,exe,fd,maps}; macOS `lsof`, platform binaries included), or an argument naming
|
|
34
|
-
// it (/proc/<pid>/cmdline; macOS `ps -ww`); (4) every process group a gate under this ownership started detached
|
|
35
|
-
// (spawnUnderOwnership records it before the child runs; class A scans, right-release builds and heavy-command start
|
|
36
|
-
// their children that way) is empty, and no such spawn was left half-recorded.
|
|
37
|
-
// Unknown is held: on Linux a /proc entry of this user's that cannot be read (EACCES/EPERM, e.g. a non-dumpable process)
|
|
38
|
-
// never counts as "not a reader" by default. It is skipped only when it vanished (ENOENT/ESRCH), belongs to another user
|
|
39
|
-
// (/proc/<pid>/status, world-readable), or the INVARIANT below holds: such a process is out of this ownership's reach only
|
|
40
|
-
// when it started before this ownership's baseline (/proc/<pid>/stat field 22 against the boot time, less START_SLACK_MS
|
|
41
|
-
// of reading error): the later of the acquisition of the previous owner whose release proved zero readers (a durable marker,
|
|
42
|
-
// `last-clean-release.json` beside the record, written only by a clean release; a record carries it as `cleanBefore`) and
|
|
43
|
-
// the snapshot root's birth in this boot, capped at acquisition; with neither, this record's own acquisition. A process
|
|
44
|
-
// that predates THIS ownership but started after the previous acquisition may be the previous owner's leftover, so it
|
|
45
|
-
// stays held when a baseline from a clean release or a birth exists (it is only dropped when it predates that baseline). An
|
|
46
|
-
// unreadable stat: the process is held. Residual on POSIX, stated plainly: a descendant that started a
|
|
47
|
-
// new session, dropped the variable, runs outside the snapshot directory, names it in no argument AND holds no file in it
|
|
48
|
-
// open or mapped at the instant the nets sample it (it reads between samples) is invisible; a sampled net cannot prove
|
|
49
|
-
// such a process will not read next. (On macOS a hidden-environment process is attributed by no start time: it is reported in
|
|
50
|
-
// the output and never held; rightkit#1313.) Another user's unreadable processes are
|
|
51
|
-
// skipped on the premise that they cannot read this user's managed root.
|
|
52
|
-
// Any host: a reboot after the record was written ends every process it covered.
|
|
53
|
-
// - if a carried (snapshot-bound) request was sent under the handle (`broker.submitted`, set only just before such a send; an uncarried
|
|
54
|
-
// probe or an installed carrier map never sets it), `rustright snapshot-lease status` reports REAPED for that snapshot & handle.
|
|
55
|
-
// Any other answer (alive, a probe that fails or is unsupported, ACTIVE, UNKNOWN, a record or holder state that cannot be read)
|
|
56
|
-
// is busy: never a reclaim. The same rules decide a normal release: the record is removed only when nothing but the gate itself
|
|
57
|
-
// is left; otherwise it stays, and the next gate reclaims it once the survivors are gone.
|
|
58
|
-
//
|
|
59
|
-
// Children inherit the ownership through RIGHTKIT_BUILD_OWNERSHIP=<handle>: a nested gate (the door running `check`) whose
|
|
60
|
-
// variable names the current record joins it instead of waiting on itself, and never releases it.
|
|
61
|
-
|
|
62
|
-
import crypto from "node:crypto";
|
|
63
|
-
import fs from "node:fs";
|
|
64
|
-
import os from "node:os";
|
|
65
|
-
import path from "node:path";
|
|
66
|
-
import { spawn as spawnDetachedDefault, spawnSync } from "./background-process.mjs";
|
|
67
|
-
import { managedRuntimeClient } from "./managed-cargo.mjs";
|
|
68
|
-
import { resolveManagedRoots } from "./managed-roots.mjs";
|
|
69
|
-
import { requireManagedRoot } from "./managed-root-guard.mjs";
|
|
70
|
-
import { readEnrolledPins } from "./broker-pins.mjs";
|
|
71
|
-
import { isRevocationEnvelope, readRevocation, revocationFile, verifyRevocation } from "./handle-revocation.mjs";
|
|
72
|
-
import { OWNERSHIP_ENV, OWNERSHIP_FILE_ENV, OwnershipBusy, holds, markBrokerSubmit, markBrokerUnsent, isMarkLockText, markCarriedSend, markLockFile, withMarkLock } from "./ownership-mark.mjs";
|
|
73
|
-
|
|
74
|
-
// The mark itself lives in a leaf module (ownership-mark.mjs): snapshot-broker.mjs records carried sends through it, and importing this
|
|
75
|
-
// file from there would close a cycle (this file -> managed-cargo -> cargo-target-shim -> snapshot-broker).
|
|
76
|
-
export { OWNERSHIP_ENV, OWNERSHIP_FILE_ENV, OwnershipBusy, markCarriedSend, markLockFile };
|
|
77
|
-
|
|
78
|
-
export const OWNERSHIP_SCHEMA = "rightkit.build-ownership/1";
|
|
79
|
-
export const HOLDER_SCHEMA = "rightkit.build-ownership-holder/1";
|
|
80
|
-
/** The owner record's path, exported beside the handle so every process under the ownership records detached children there. */
|
|
81
|
-
/** GB-85: how long a successful stage's release waits for every submission under its handle to be durably complete (the broker's own bounded `--wait-ms`, never a poll of the build). */
|
|
82
|
-
export const RELEASE_LEASE_WAIT_MS = 15_000;
|
|
83
|
-
export const LEASE_STATUS_SCHEMA = "rustright.snapshot-lease-status.v1";
|
|
84
|
-
const LEASE_STATES = new Set(["ACTIVE", "REAPED", "UNKNOWN"]);
|
|
85
|
-
// A start time read from `ps` (or /proc/<pid>/stat) is never late, only early: ps prints whole seconds (up to 1 s early), and on
|
|
86
|
-
// Linux the figure is btime (whole seconds, so the boot is up to 1 s early) plus the process's ticks: measured on WSL2, a process
|
|
87
|
-
// 98 ms old read as 788 ms old. So a start can read up to about 2 s before the process really began; this slack (with margin) is
|
|
88
|
-
// how much earlier than an instant a reading may be and still be "not before" it. A member started right after the gate took
|
|
89
|
-
// ownership counts as the gate's however its start reads.
|
|
90
|
-
const START_SLACK_MS = 3000;
|
|
91
|
-
// Two start identities of one pid are the same process when they agree to within this (ps prints seconds; this gate's own start
|
|
92
|
-
// is read from its time origin on Windows, a few hundred ms after the OS creation time at most).
|
|
93
|
-
const SAME_START_MS = 3000;
|
|
94
|
-
const sameStart = (a, b) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= SAME_START_MS;
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
/** The directory beside the host's snapshots (or beside any injected root) that holds the owner record. */
|
|
98
|
-
export const OWNERSHIP_DIRNAME = "build-ownership";
|
|
99
|
-
|
|
100
|
-
/** A repository key is one path segment: the snapshot directory's name (a hex digest), never a path. */
|
|
101
|
-
const REPOSITORY_KEY = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Where a repository's owner record lives (GC:24 "the repository's build ownership"; item 5 row 5.17): ONE fixed location per
|
|
105
|
-
* repository, independent of the snapshot root and of every environment variable. Two gates for the same repository whose
|
|
106
|
-
* environments choose different snapshot roots (XDG_STATE_HOME, a configured root) must still contend for one record, so nothing
|
|
107
|
-
* here reads `process.env`, and nothing derives from where snapshots live. The only input besides the platform is `repository`,
|
|
108
|
-
* the repository key the snapshot directory uses (`snapshot.repositoryOf(root).key`); it is required.
|
|
109
|
-
* Mac & Dell: `<managed root>/build-ownership/<repository key>/owner.json` (the host's fixed managed root,
|
|
110
|
-
* `/Volumes/D/.rightkit-managed`, `D:\.rightkit-managed`).
|
|
111
|
-
* Linux (WSL2 included): `<account home>/.local/state/rightkit/build-ownership/<repository key>/owner.json`, the account home
|
|
112
|
-
* taken from the passwd database (`os.userInfo()`), never from $HOME.
|
|
113
|
-
* `home` replaces the Linux account home and `beside` replaces the whole location (`<dirname(beside)>/build-ownership/<key>/owner.json`);
|
|
114
|
-
* both are injection points for fixtures and tests only. A production caller passes neither: the root a caller derived from the
|
|
115
|
-
* environment must never be passed as `beside`, because that is the defect this row removes.
|
|
116
|
-
*/
|
|
117
|
-
export function ownershipFile({ platform = process.platform, home, beside, repository } = {}) {
|
|
118
|
-
if (typeof repository !== "string" || !REPOSITORY_KEY.test(repository)) throw new TypeError(`ownershipFile: repository must be the repository key (one path segment), not ${JSON.stringify(repository)}`);
|
|
119
|
-
const paths = platform === "win32" ? path.win32 : path.posix;
|
|
120
|
-
if (beside !== undefined) {
|
|
121
|
-
if (typeof beside !== "string" || beside === "") throw new TypeError(`ownershipFile: beside must be a path (${JSON.stringify(beside)})`);
|
|
122
|
-
return paths.join(paths.dirname(beside), OWNERSHIP_DIRNAME, repository, "owner.json");
|
|
123
|
-
}
|
|
124
|
-
if (platform === "darwin" || platform === "win32") return paths.join(resolveManagedRoots({ env: {}, platform, home: "" }).gateRoot, OWNERSHIP_DIRNAME, repository, "owner.json");
|
|
125
|
-
let base = home;
|
|
126
|
-
if (base === undefined) {
|
|
127
|
-
try { base = os.userInfo().homedir; } catch (e) { throw new OwnershipBusy(`build ownership: this account's home directory cannot be read (${e.message}), so the repository's owner record has no location`); }
|
|
128
|
-
}
|
|
129
|
-
return paths.join(base, ".local", "state", "rightkit", OWNERSHIP_DIRNAME, repository, "owner.json");
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* The managed-root guard, FIRST in `acquireBuildOwnership` (decision D4, rows 5.15 and 5.17): on Mac & Dell, when the record is at
|
|
134
|
-
* the host's own location (inside the host's managed root, or inside the `managedRoot` a fixture injects), the managed root must
|
|
135
|
-
* already exist, be a plain directory and, on the Mac, live on another device than `/`. Taking ownership creates `build-ownership/`,
|
|
136
|
-
* and must never be what brings a missing managed root (or a boot-volume substitute for an unmounted one) into being. Throws the
|
|
137
|
-
* guard's named refusal (`code: "refused"`, `reason`), before anything is read or written. Linux has no managed root.
|
|
138
|
-
*/
|
|
139
|
-
function guardManagedRoot(file, { platform, managedRoot, device }) {
|
|
140
|
-
if (platform !== "darwin" && platform !== "win32") return;
|
|
141
|
-
const root = managedRoot ?? resolveManagedRoots({ env: {}, platform, home: "" }).gateRoot;
|
|
142
|
-
if (managedRoot === undefined) {
|
|
143
|
-
const paths = platform === "win32" ? path.win32 : path.posix;
|
|
144
|
-
const fold = (x) => paths.resolve(x).toLowerCase(); // both volumes are case-insensitive by default
|
|
145
|
-
const rel = paths.relative(fold(root), fold(file));
|
|
146
|
-
if (rel === "" || rel === ".." || rel.startsWith(`..${paths.sep}`) || paths.isAbsolute(rel)) return; // a record elsewhere (a fixture's): not the host's
|
|
147
|
-
}
|
|
148
|
-
requireManagedRoot(root, { platform, device });
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Creates the ownership directory mode 0700 (one level per directory on Mac & Dell) and refuses an existing POSIX one that grants group or other access (item 5 row 5.22):
|
|
153
|
-
* another user's unreadable process is skipped by the nets on the premise that it cannot read this user's managed root, and a
|
|
154
|
-
* directory other users could write would let them forge or remove the record. Windows has no mode bits; its directory ACL is the
|
|
155
|
-
* same trust the record itself has.
|
|
156
|
-
*/
|
|
157
|
-
export function ensureOwnershipDir(dir, { platform = process.platform } = {}) {
|
|
158
|
-
// A repository directory sits inside `build-ownership/`, which gets the same mode rules (created first, then checked).
|
|
159
|
-
if (path.basename(path.dirname(dir)) === OWNERSHIP_DIRNAME) ensureOwnershipDir(path.dirname(dir), { platform });
|
|
160
|
-
// Mac & Dell: exactly ONE level per call, `build-ownership/` (then `<key>/`) inside a managed root that already exists (decision D4: the gate never
|
|
161
|
-
// creates the managed root, and a recursive creation here would). Linux: the durable state directory under the account home is
|
|
162
|
-
// created whole (GC:63).
|
|
163
|
-
if (platform === "linux") fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
164
|
-
else { try { fs.mkdirSync(dir, { mode: 0o700 }); } catch (e) { if (e.code !== "EEXIST") throw e; } }
|
|
165
|
-
if (platform === "win32" || process.platform === "win32") return;
|
|
166
|
-
const st = fs.statSync(dir);
|
|
167
|
-
if (!st.isDirectory()) throw new OwnershipBusy(`build ownership directory ${dir} is not a directory`);
|
|
168
|
-
if ((st.mode & 0o077) !== 0) throw new OwnershipBusy(`build ownership directory ${dir} is mode ${(st.mode & 0o777).toString(8).padStart(3, "0")}: group or other users can reach it, so the premise that another user's processes cannot read this user's managed root does not hold; chmod 700 ${dir} (nothing ran)`, { dir, mode: st.mode & 0o777 });
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export const jobName = (handle) => `Local\\RightKitBuildOwnership-${handle}`;
|
|
172
|
-
/** Where the process groups of children a gate under this ownership started detached (POSIX) are recorded. */
|
|
173
|
-
export const childrenDir = (file, handle) => path.join(path.dirname(file), `children-${handle}`);
|
|
174
|
-
export const holderFile = (file, handle) => path.join(path.dirname(file), `holder-${handle}.json`);
|
|
175
|
-
|
|
176
|
-
const run = (spawn, command, args, env = {}) => spawn(command, args, { encoding: "utf8", env: { ...process.env, ...env }, timeout: 60_000, maxBuffer: 1 << 26 });
|
|
177
|
-
|
|
178
|
-
// One C# type for every Windows probe: create, open, assign and count a named job.
|
|
179
|
-
const JOB_TYPE = `Add-Type @"
|
|
180
|
-
using System; using System.Runtime.InteropServices;
|
|
181
|
-
public static class RkJob {
|
|
182
|
-
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern IntPtr CreateJobObjectW(IntPtr a, string name);
|
|
183
|
-
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern IntPtr OpenJobObjectW(uint access, bool inherit, string name);
|
|
184
|
-
[DllImport("kernel32.dll", SetLastError=true)] public static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
|
|
185
|
-
[DllImport("kernel32.dll", SetLastError=true)] public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr proc);
|
|
186
|
-
[DllImport("kernel32.dll", SetLastError=true)] public static extern bool QueryInformationJobObject(IntPtr job, int cls, byte[] info, int len, IntPtr ret);
|
|
187
|
-
[DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr h);
|
|
188
|
-
[DllImport("kernel32.dll", SetLastError=true)] public static extern bool IsProcessInJob(IntPtr proc, IntPtr job, out bool result);
|
|
189
|
-
[DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess();
|
|
190
|
-
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); }
|
|
191
|
-
}
|
|
192
|
-
"@`;
|
|
193
|
-
const psString = (s) => `'${String(s).replace(/'/g, "''")}'`;
|
|
194
|
-
const encoded = (script) => Buffer.from(script, "utf16le").toString("base64");
|
|
195
|
-
|
|
196
|
-
/** Where the holder's script is written for PowerShell -File (beside the holder record). */
|
|
197
|
-
export const holderScriptFile = (file) => `${file}.ps1`;
|
|
198
|
-
/** cmd.exe's longest command line; the holder's launch must stay under it. */
|
|
199
|
-
export const CMD_LINE_LIMIT = 8191;
|
|
200
|
-
/** The holder's launch: `cmd /d /c start "" /b powershell -File <script>` (see contain). */
|
|
201
|
-
export const holderLaunchArgs = (script) => ["/d", "/c", "start", "\"\"", "/b", "powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", script];
|
|
202
|
-
|
|
203
|
-
/** The holder: creates the gate's job, puts the gate in it, then keeps the only handle until the job is empty. */
|
|
204
|
-
export function holderScript({ name, pid, file, selfDelete = false }) {
|
|
205
|
-
return [
|
|
206
|
-
"$ErrorActionPreference = 'Stop'",
|
|
207
|
-
...(selfDelete ? ["try { Remove-Item -LiteralPath $PSCommandPath -Force } catch { }"] : []),
|
|
208
|
-
JOB_TYPE,
|
|
209
|
-
`$name = ${psString(name)}; $gate = [uint32]${Number(pid)}; $file = ${psString(file)}`,
|
|
210
|
-
`function Put($o) { $o.schema = '${HOLDER_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 }`,
|
|
211
|
-
"try {",
|
|
212
|
-
" $h = [RkJob]::CreateJobObjectW([IntPtr]::Zero, $name); $e = [Runtime.InteropServices.Marshal]::GetLastWin32Error()",
|
|
213
|
-
" if ($h -eq [IntPtr]::Zero) { throw \"CreateJobObject failed ($e)\" }",
|
|
214
|
-
" if ($e -eq 183) { throw \"job $name already exists\" }",
|
|
215
|
-
" $p = [RkJob]::OpenProcess(0x0101, $false, $gate); if ($p -eq [IntPtr]::Zero) { throw \"OpenProcess $gate failed ($([Runtime.InteropServices.Marshal]::GetLastWin32Error()))\" }",
|
|
216
|
-
" if (-not [RkJob]::AssignProcessToJobObject($h, $p)) { throw \"AssignProcessToJobObject failed ($([Runtime.InteropServices.Marshal]::GetLastWin32Error()))\" }",
|
|
217
|
-
" [RkJob]::CloseHandle($p) | Out-Null",
|
|
218
|
-
" Put @{ state = 'holding'; job = $name }",
|
|
219
|
-
"} catch { Put @{ state = 'failed'; why = \"$_\" }; exit 1 }",
|
|
220
|
-
// Reports the live count whenever it changes, drained at zero. A release asks for a fresh count by writing `<file>.query`
|
|
221
|
-
// ({nonce}); the holder counts the job after reading it and answers in `<file>.ack` with that nonce (queryHolder).
|
|
222
|
-
"$last = -1; $query = \"$file.query\"; $ack = \"$file.ack\"; $answered = ''",
|
|
223
|
-
// Each nonce is answered once (rewriting the ack would contend with the reader removing it).
|
|
224
|
-
"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 = '" + HOLDER_SCHEMA + "'; 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 { } }",
|
|
225
|
-
"while ($true) { if ([IO.File]::Exists($query)) { Answer }; $a = [RkJob]::Active($h); if ($a -eq 0) { Put @{ state = 'drained'; job = $name }; exit 0 }; if ($a -gt 0 -and $a -ne $last) { Put @{ state = 'holding'; job = $name; active = $a }; $last = $a }; Start-Sleep -Milliseconds 50 }",
|
|
226
|
-
].join("\n");
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
/**
|
|
230
|
-
* A fresh count of the gate's job from its holder (outside the job): writes `<holder file>.query` with a new nonce and waits for
|
|
231
|
-
* `<holder file>.ack` carrying that nonce, which the holder writes after counting the job anew. Returns `{ active, holder, at, nonce }`
|
|
232
|
-
* or throws: no answer within `timeoutMs` (a dead or hung holder) is unknown, never the last count it wrote.
|
|
233
|
-
*/
|
|
234
|
-
export function queryHolder(file, { timeoutMs = 5000, nonce = crypto.randomBytes(16).toString("hex"), sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) } = {}) {
|
|
235
|
-
const query = `${file}.query`; const ack = `${file}.ack`;
|
|
236
|
-
fs.rmSync(ack, { force: true });
|
|
237
|
-
const tmp = `${query}.${crypto.randomUUID()}.tmp`;
|
|
238
|
-
fs.writeFileSync(tmp, JSON.stringify({ nonce }), { flag: "wx", mode: 0o600 });
|
|
239
|
-
try { fs.renameSync(tmp, query); } finally { fs.rmSync(tmp, { force: true }); }
|
|
240
|
-
try {
|
|
241
|
-
const until = Date.now() + timeoutMs;
|
|
242
|
-
for (;;) {
|
|
243
|
-
let answer = null;
|
|
244
|
-
try { answer = JSON.parse(fs.readFileSync(ack, "utf8").replace(/^\uFEFF/, "")); } catch { answer = null; }
|
|
245
|
-
if (answer?.schema === HOLDER_SCHEMA && answer.nonce === nonce) {
|
|
246
|
-
if (!Number.isInteger(answer.active)) throw new Error(`the holder's answer to ${nonce} carries no count`);
|
|
247
|
-
return { active: answer.active, holder: answer.holder, at: answer.at, nonce };
|
|
248
|
-
}
|
|
249
|
-
if (Date.now() > until) throw new Error(`the job holder did not answer a fresh count within ${timeoutMs} ms`);
|
|
250
|
-
sleep(25);
|
|
251
|
-
}
|
|
252
|
-
} finally {
|
|
253
|
-
// The holder may hold either file open for a moment (Windows refuses the removal then); a leftover is harmless: the next
|
|
254
|
-
// query replaces the query and removes the ack before it waits, and only an answer with its own nonce counts.
|
|
255
|
-
for (const f of [query, ack]) { try { fs.rmSync(f, { force: true }); } catch { /* left for the next query */ } }
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/** Run as a child of the gate (as its work runs): `IN` when this process is in job `name`, `OUT` when not, `ERR:<n>` otherwise. */
|
|
260
|
-
export function selfCheckScript(name) {
|
|
261
|
-
return [
|
|
262
|
-
"$ErrorActionPreference = 'Stop'",
|
|
263
|
-
JOB_TYPE,
|
|
264
|
-
`$j = [RkJob]::OpenJobObjectW(0x0004, $false, ${psString(name)}); if ($j -eq [IntPtr]::Zero) { 'ERR:' + [Runtime.InteropServices.Marshal]::GetLastWin32Error(); exit 0 }`,
|
|
265
|
-
"$in = $false; if (-not [RkJob]::IsProcessInJob([RkJob]::GetCurrentProcess(), $j, [ref]$in)) { 'ERR:' + [Runtime.InteropServices.Marshal]::GetLastWin32Error(); exit 0 }",
|
|
266
|
-
"if ($in) { 'IN' } else { 'OUT' }",
|
|
267
|
-
].join("\n");
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/** Probe of a named job: `JOB:<active>` (opened), `GONE` (no such object), `ERR:<n>` otherwise; plus `BOOT:<ms>`. */
|
|
271
|
-
function jobProbeScript(name) {
|
|
272
|
-
return [
|
|
273
|
-
"$ErrorActionPreference = 'Stop'",
|
|
274
|
-
JOB_TYPE,
|
|
275
|
-
`$j = [RkJob]::OpenJobObjectW(0x0004, $false, ${psString(name)}); $e = [Runtime.InteropServices.Marshal]::GetLastWin32Error()`,
|
|
276
|
-
"if ($j -ne [IntPtr]::Zero) { 'JOB:' + [RkJob]::Active($j); [RkJob]::CloseHandle($j) | Out-Null } elseif ($e -eq 2) { 'GONE' } else { 'ERR:' + $e }",
|
|
277
|
-
].join("\n");
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
const PATH_CHAR = /[A-Za-z0-9._@+~-]/;
|
|
281
|
-
/** Whether `text` (an argument list) names the directory `dir`: `dir` itself or a path under it, not a longer sibling name. */
|
|
282
|
-
export function namesDir(text, dir) {
|
|
283
|
-
const d = dir.length > 1 ? dir.replace(/\/+$/, "") : dir;
|
|
284
|
-
if (!d) return false;
|
|
285
|
-
for (let i = text.indexOf(d); i !== -1; i = text.indexOf(d, i + 1)) {
|
|
286
|
-
const before = i === 0 ? "" : text[i - 1]; const after = text[i + d.length] ?? "";
|
|
287
|
-
if ((before === "" || !PATH_CHAR.test(before)) && (after === "" || after === "/" || !PATH_CHAR.test(after))) return true;
|
|
288
|
-
}
|
|
289
|
-
return false;
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/** The most parent links `classifyHiddenProcesses` follows from one process before it holds it (a cycle or an absurdly deep chain is unknown). */
|
|
293
|
-
export const HIDDEN_WALK_LIMIT = 1024;
|
|
294
|
-
/** What `launchctl blame <pid>` prints (exit 3) for a process launchd does not manage, or that no longer exists. */
|
|
295
|
-
export const NOT_MANAGED_LINE = "Process is not managed by launchd or does not exist.";
|
|
296
|
-
/** `launchctl blame` answer -> `managed` (a launchd job: exit 0 with a reason), `unmanaged` (exit 3, the line above) or `unknown` (anything else). */
|
|
297
|
-
export function blameKind(answer) {
|
|
298
|
-
const line = String(answer?.line ?? "").trim();
|
|
299
|
-
if (answer?.rc === 3 && line === NOT_MANAGED_LINE) return "unmanaged";
|
|
300
|
-
if (answer?.rc === 0 && line !== "" && line !== NOT_MANAGED_LINE) return "managed";
|
|
301
|
-
return "unknown";
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
/**
|
|
305
|
-
* macOS (item 5 row 5.24a, rule 5.24a' of signed/item5-sage-decisions-2.md D1 with D2; item186-decision.md:47-71 with the gate's
|
|
306
|
-
* anchor in place of the broker's root start). `ps eww` prints no environment for an Apple platform binary (/bin/*, /usr/bin/*,
|
|
307
|
-
* system daemons), so the token net cannot tell such a process from one that never carried the handle, and the snapshot-use net
|
|
308
|
-
* samples only the instant it runs. A gate descendant that is a platform binary, started its own session and touches nothing in the
|
|
309
|
-
* snapshot at that instant would escape both. So: hidden means held after the anchor, cleared only by lineage proof.
|
|
310
|
-
*
|
|
311
|
-
* `procs` are the live processes as `{ pid, ppid, group, startedMs, uid, state, hidden, uninspected, command }` (`startedMs` has
|
|
312
|
-
* `ps lstart`'s one-second resolution; `state` is `ps stat`, whose `X` means traced; `hidden`: `ps eww` shows no environment, an
|
|
313
|
-
* empty environment included; `uninspected`: `lsof` listed nothing for it). `anchorMs` is the baseline (the later of the last clean
|
|
314
|
-
* release and the snapshot root's birth in this boot, capped at acquisition); with none, the anchor is the record's own acquisition
|
|
315
|
-
* (`owner.acquiredAt`), never "no anchor": a process that started before this ownership began is no unproven work of any owner,
|
|
316
|
-
* because every record is published on a free host after a release that proved zero readers, or by a reclaim that proved the
|
|
317
|
-
* previous work gone. `owner` is the record; `recorded` the detached children the gate recorded, `[{ group, command }]` (a child
|
|
318
|
-
* leads the group named by its own pid). `blame(pid) -> { rc, line }` is `launchctl blame`; `reread(pids) -> Map(pid -> { ppid,
|
|
319
|
-
* startedMs })` re-lists pids (the binding against pid reuse).
|
|
320
|
-
*
|
|
321
|
-
* A candidate is a same-user, live (not a zombie) process the gate did not itself start for this probe, that is hidden or that
|
|
322
|
-
* `lsof` could not inspect. Each is judged in this order:
|
|
323
|
-
* (t) it, or a process on its walk, is traced (a ptrace attach reparents to the tracer) -> HELD.
|
|
324
|
-
* (a) it started before the anchor second -> drop. The anchor second itself counts as after: `lstart` is whole seconds.
|
|
325
|
-
* (b) it is in a recorded detached group -> HELD. It is in the owner's group -> HELD unless its parent is one of the owner's
|
|
326
|
-
* recorded ancestors, matched by pid and start identity (`gate | tee`: that ancestor's other child), when it goes to (c).
|
|
327
|
-
* The owner's own recorded ancestors are never its children and are not candidates.
|
|
328
|
-
* (c) walk up from it; for each parent, in order:
|
|
329
|
-
* the parent is the owner or a recorded child; the parent cannot be read; the parent started after its child (pid reuse);
|
|
330
|
-
* or the walk passes HIDDEN_WALK_LIMIT steps or loops -> HELD.
|
|
331
|
-
* The parent is launchd (pid 1): the child X on the walk started at or after the anchor; `launchctl blame X` decides. A
|
|
332
|
-
* launchd job (exit 0 and a reason) means the chain was born under launchd and never passed through the gate -> drop,
|
|
333
|
-
* once the re-read after the blame calls confirms X (still a child of pid 1, same start). Not managed (exit 3) is a reparented
|
|
334
|
-
* orphan, or a vanished one -> HELD. Anything else (another exit code, no output, a spawn error, a timeout) -> HELD.
|
|
335
|
-
* The parent provably started before the anchor, and is not launchd -> drop (a terminal opened after the anchor under a
|
|
336
|
-
* Terminal that predates it).
|
|
337
|
-
* Otherwise move to the parent and repeat. A recorded ancestor is walked like any other process: the exemption in (b) is never
|
|
338
|
-
* an immediate drop.
|
|
339
|
-
* Residual R1 (trusted per-user model, AR:273-276): a gate descendant can ask launchd to spawn a process (`launchctl submit`, `open`, an
|
|
340
|
-
* XPC service, a LaunchAgent). That process is launchd-born, so it is dropped. macOS has no subreaper, so nothing else reparents a
|
|
341
|
-
* descendant to a process that predates the anchor.
|
|
342
|
-
* Returns `[{ pid, why }]`, every process held, each reason naming the pid.
|
|
343
|
-
*/
|
|
344
|
-
export function classifyHiddenProcesses({ procs, own = new Set(), uid, owner, recorded = [], anchorMs, alive = () => true, blame = null, reread = null }) {
|
|
345
|
-
const byPid = new Map(procs.map((p) => [p.pid, p]));
|
|
346
|
-
const anchor = Number.isFinite(anchorMs) ? anchorMs : Date.parse(owner?.acquiredAt ?? "");
|
|
347
|
-
const anchorSecond = Number.isFinite(anchor) ? Math.floor(anchor / 1000) * 1000 : NaN;
|
|
348
|
-
const ownerGroup = Number.isInteger(owner?.containment?.group) ? owner.containment.group : null;
|
|
349
|
-
const recordedGroups = new Set(recorded.map((r) => r.group));
|
|
350
|
-
const recordedChild = (p) => recordedGroups.has(p.pid);
|
|
351
|
-
const isOwner = (p) => p.pid === owner?.pid && sameStart(p.startedMs, owner?.startedMs);
|
|
352
|
-
const ancestors = Array.isArray(owner?.ancestors) ? owner.ancestors : [];
|
|
353
|
-
const isAncestor = (p) => ancestors.some((a) => a?.pid === p.pid && sameStart(a.startedMs, p.startedMs));
|
|
354
|
-
const traced = (p) => /X/.test(String(p.state));
|
|
355
|
-
const before = (p) => p.startedMs < anchorSecond;
|
|
356
|
-
const held = [];
|
|
357
|
-
const cleared = []; // [{ p, top, hold }]: dropped by a launchd-job top, pending the re-read
|
|
358
|
-
const blamed = new Map(); // one answer per pid within this sample
|
|
359
|
-
const blameOf = (pid) => {
|
|
360
|
-
if (!blamed.has(pid)) { let a; try { a = typeof blame === "function" ? blame(pid) : null; } catch { a = null; } blamed.set(pid, a); }
|
|
361
|
-
return blamed.get(pid);
|
|
362
|
-
};
|
|
363
|
-
const name = (p) => `pid ${p.pid} (${String(p.command ?? "?").slice(0, 80)}), started ${Number.isFinite(p.startedMs) ? new Date(p.startedMs).toISOString() : "at a time that cannot be read"}`;
|
|
364
|
-
for (const p of procs) {
|
|
365
|
-
if (own.has(p.pid) || p.uid !== uid || /^Z/.test(String(p.state)) || !(p.hidden || p.uninspected)) continue;
|
|
366
|
-
const what = p.hidden ? "its environment is hidden (`ps eww` shows none)" : "`lsof` cannot inspect it";
|
|
367
|
-
const hold = (why) => { if (alive(p.pid)) held.push({ pid: p.pid, why: `${name(p)}: ${what}, and ${why}` }); };
|
|
368
|
-
if (isOwner(p) || isAncestor(p)) continue; // the owner, or one of its parents: never its child
|
|
369
|
-
if (!Number.isFinite(anchorSecond)) { hold("this ownership has no anchor and its record has no readable acquisition time, so nothing hidden can be cleared"); continue; }
|
|
370
|
-
if (traced(p)) { hold("it is traced (a ptrace attach reparents it to the tracer), so its lineage proves nothing"); continue; } // (t)
|
|
371
|
-
if (!Number.isFinite(p.startedMs)) { hold("its start time cannot be read"); continue; }
|
|
372
|
-
if (before(p)) continue; // (a)
|
|
373
|
-
const parentRow = byPid.get(p.ppid);
|
|
374
|
-
const peer = !!parentRow && isAncestor(parentRow) && !traced(parentRow);
|
|
375
|
-
if (recordedGroups.has(p.group)) { hold(`it is in process group ${p.group}, a detached group this gate recorded`); continue; } // (b)
|
|
376
|
-
if (p.group === ownerGroup && !peer) { hold(`it is in process group ${p.group}, the owner's group`); continue; }
|
|
377
|
-
// (c)
|
|
378
|
-
let x = p; let verdict = null; let top = null; const seen = new Set([p.pid]);
|
|
379
|
-
for (let steps = 0; verdict === null; steps++) {
|
|
380
|
-
if (steps >= HIDDEN_WALK_LIMIT) { verdict = `the ancestry walk passed ${HIDDEN_WALK_LIMIT} steps`; break; }
|
|
381
|
-
const parent = byPid.get(x.ppid);
|
|
382
|
-
if (!parent) { verdict = `the parent of pid ${x.pid} (pid ${x.ppid}) cannot be read`; break; }
|
|
383
|
-
if (isOwner(parent)) { verdict = `its ancestry reaches the owner (pid ${parent.pid}) through pid ${x.pid}`; break; }
|
|
384
|
-
if (recordedChild(parent)) { verdict = `its ancestry reaches a child this gate recorded (pid ${parent.pid}) through pid ${x.pid}`; break; }
|
|
385
|
-
if (traced(parent)) { verdict = `pid ${parent.pid} on its walk is traced, so its lineage proves nothing`; break; }
|
|
386
|
-
if (parent.pid === 1) {
|
|
387
|
-
const answer = blameOf(x.pid);
|
|
388
|
-
const kind = blameKind(answer);
|
|
389
|
-
if (kind === "managed") { verdict = false; top = x; break; }
|
|
390
|
-
verdict = kind === "unmanaged" ? `pid ${x.pid} is an orphan: its parent is launchd, it started at or after the anchor, and launchctl blame says it is not managed by launchd (a reparented orphan, or one that vanished)`
|
|
391
|
-
: `pid ${x.pid}'s parent is launchd and launchctl blame gave no usable answer (${answer ? `exit ${answer.rc}, ${JSON.stringify(String(answer.line ?? "").slice(0, 80))}` : "it could not run"}), so it is unknown`;
|
|
392
|
-
break;
|
|
393
|
-
}
|
|
394
|
-
if (!Number.isFinite(parent.startedMs) || parent.startedMs > x.startedMs) { verdict = `pid ${parent.pid} started after its child pid ${x.pid} (pid reuse), so the lineage cannot be trusted`; break; }
|
|
395
|
-
if (before(parent)) { verdict = false; break; } // a parent that provably predates the anchor, and is not launchd
|
|
396
|
-
if (seen.has(parent.pid)) { verdict = `the ancestry of pid ${p.pid} loops at pid ${parent.pid}`; break; }
|
|
397
|
-
seen.add(parent.pid); x = parent;
|
|
398
|
-
}
|
|
399
|
-
if (verdict) hold(verdict);
|
|
400
|
-
else if (top) cleared.push({ p, top, hold });
|
|
401
|
-
}
|
|
402
|
-
// Binding against pid reuse: a top cleared as a launchd job is re-listed after the blame calls; one that is no longer a child of
|
|
403
|
-
// launchd, started at another time, or is gone, was another process when it was judged.
|
|
404
|
-
if (cleared.length) {
|
|
405
|
-
const tops = [...new Set(cleared.map((c) => c.top.pid))];
|
|
406
|
-
let fresh = null; try { fresh = typeof reread === "function" ? reread(tops) : null; } catch { fresh = null; }
|
|
407
|
-
for (const c of cleared) {
|
|
408
|
-
const f = fresh?.get(c.top.pid);
|
|
409
|
-
if (!f) c.hold(fresh ? `pid ${c.top.pid}, the launchd job it descends from, is gone on the re-read, so its lineage changed during the sample` : `pid ${c.top.pid}, the launchd job it descends from, could not be re-read, so the answer cannot be bound to it`);
|
|
410
|
-
else if (f.ppid !== 1 || f.startedMs !== c.top.startedMs) c.hold(`pid ${c.top.pid}, the launchd job it descends from, is not the same process on the re-read (parent ${f.ppid}, started ${Number.isFinite(f.startedMs) ? new Date(f.startedMs).toISOString() : "?"}; it was parent 1, started ${new Date(c.top.startedMs).toISOString()}): pid reuse`);
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
return held;
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
/**
|
|
417
|
-
* The host's process facts the ownership rules rely on. Each answer is a fact or a throw; a throw means "unknown" and the
|
|
418
|
-
* caller treats it as busy.
|
|
419
|
-
*/
|
|
420
|
-
export function processProbe({ platform = process.platform, spawn = spawnSync, spawnHolder = spawnDetachedDefault, kill = process.kill.bind(process), readFile = fs.readFileSync, readdir = fs.readdirSync, readlink = fs.readlinkSync, exists: procExists = fs.existsSync, proc = "/proc", uid = process.getuid?.(), sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) } = {}) {
|
|
421
|
-
const exists = (pid) => {
|
|
422
|
-
try { kill(pid, 0); return true; } catch (e) { if (e.code === "ESRCH") return false; if (e.code === "EPERM") return true; throw e; }
|
|
423
|
-
};
|
|
424
|
-
if (platform === "win32") {
|
|
425
|
-
const ps = (script) => {
|
|
426
|
-
const r = run(spawn, "powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded(script)]);
|
|
427
|
-
if (r.error || r.status !== 0) throw new Error(`powershell: ${r.error?.message ?? (String(r.stderr ?? "").trim().split(/\r?\n/).pop() || `exit ${r.status}`)}`);
|
|
428
|
-
return String(r.stdout ?? "").trim();
|
|
429
|
-
};
|
|
430
|
-
return {
|
|
431
|
-
platform,
|
|
432
|
-
/**
|
|
433
|
-
* `{ alive, startedMs }`. This gate's own start comes from its time origin (no process launch). Another process's start is
|
|
434
|
-
* a Unix time in ms from `[DateTimeOffset]`: `[datetime]'1970-01-01Z'` parses as LOCAL time, so subtracting it was off by the
|
|
435
|
-
* zone's offset (5.5 h on the Dell, 2026-10-29), which made a live owner read as another process and, west of UTC, a reboot
|
|
436
|
-
* appear to have happened.
|
|
437
|
-
*/
|
|
438
|
-
identity(pid) {
|
|
439
|
-
if (pid === process.pid) return { alive: true, startedMs: Math.round(performance.timeOrigin), group: null };
|
|
440
|
-
if (!exists(pid)) return { alive: false, startedMs: null, group: null };
|
|
441
|
-
const out = ps(`$p = Get-Process -Id ${Number(pid)} -ErrorAction SilentlyContinue; if ($p) { 'START:' + ([DateTimeOffset]$p.StartTime).ToUnixTimeMilliseconds() } else { 'GONE' }`);
|
|
442
|
-
if (out === "GONE") return { alive: false, startedMs: null, group: null };
|
|
443
|
-
const m = /START:(\d+)/.exec(out);
|
|
444
|
-
if (!m) throw new Error(`cannot read the start time of pid ${pid}`);
|
|
445
|
-
return { alive: true, startedMs: Number(m[1]), group: null };
|
|
446
|
-
},
|
|
447
|
-
bootTime() {
|
|
448
|
-
const m = /BOOT:(\d+)/.exec(ps("'BOOT:' + ([DateTimeOffset](Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToUnixTimeMilliseconds()"));
|
|
449
|
-
if (!m) throw new Error("cannot read the boot time");
|
|
450
|
-
return Number(m[1]);
|
|
451
|
-
},
|
|
452
|
-
/** A fresh count from the job's holder (see queryHolder): asked at release, when a probe this gate spawned would sit in the job. */
|
|
453
|
-
queryHolder: (file, options) => queryHolder(file, options),
|
|
454
|
-
/** `{ open: true, active }`, `{ open: false }` (no such job), or a throw. */
|
|
455
|
-
jobState(name) {
|
|
456
|
-
const out = ps(jobProbeScript(name));
|
|
457
|
-
const job = /JOB:(-?\d+)/.exec(out);
|
|
458
|
-
if (job) { const active = Number(job[1]); if (active < 0) throw new Error(`cannot count the processes of ${name}`); return { open: true, active }; }
|
|
459
|
-
if (/^GONE$/m.test(out)) return { open: false };
|
|
460
|
-
throw new Error(`cannot open ${name}: ${out}`);
|
|
461
|
-
},
|
|
462
|
-
/**
|
|
463
|
-
* Starts the holder that puts `pid` in job `name`; returns once it reports holding (or throws). The holder must outlive
|
|
464
|
-
* this gate: it is started by `cmd /c start /b`, so it is cmd's child, not Node's, and silently leaves the kill-on-close
|
|
465
|
-
* job Node keeps for its own children (libuv sets SILENT_BREAKAWAY_OK); cmd exits at once. A DETACHED_PROCESS PowerShell
|
|
466
|
-
* never starts in a console-less session (measured on the Dell over ssh, 2026-10-29), so `detached` is not used.
|
|
467
|
-
*/
|
|
468
|
-
contain({ name, pid, file, timeoutMs = 60_000, sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) }) {
|
|
469
|
-
// The script goes in a file beside the holder record (mode 0600 means nothing on NTFS: the file has the ownership directory's
|
|
470
|
-
// ACL, the same trust the record itself has), never on the command line: cmd.exe cuts a command line at
|
|
471
|
-
// 8191 characters, and the encoded holder passed that once it answered fresh queries (the holder never started; Dell
|
|
472
|
-
// 2026-10-29, D:\scratch\rk-step4\dell-ev7-build-ownership.log). The holder deletes the file once PowerShell has read it.
|
|
473
|
-
const script = holderScriptFile(file);
|
|
474
|
-
fs.rmSync(script, { force: true });
|
|
475
|
-
fs.writeFileSync(script, holderScript({ name, pid, file, selfDelete: true }), { flag: "wx", mode: 0o600 });
|
|
476
|
-
const holding = (() => {
|
|
477
|
-
try {
|
|
478
|
-
const child = spawnHolder("cmd.exe", holderLaunchArgs(script), { stdio: "ignore" });
|
|
479
|
-
child.unref?.();
|
|
480
|
-
const until = Date.now() + timeoutMs;
|
|
481
|
-
for (;;) {
|
|
482
|
-
const state = readHolder(file);
|
|
483
|
-
if (state?.state === "holding") return state;
|
|
484
|
-
if (state?.state === "failed") throw new Error(`the job holder could not contain the gate: ${state.why}`);
|
|
485
|
-
if (Date.now() > until) throw new Error(`the job holder did not report within ${timeoutMs} ms`);
|
|
486
|
-
sleep(50);
|
|
487
|
-
}
|
|
488
|
-
} finally { fs.rmSync(script, { force: true }); }
|
|
489
|
-
})();
|
|
490
|
-
// Self-check: a child of this gate, started as its work is started, asks Windows whether it is in the job. Under a launcher
|
|
491
|
-
// whose own job lets children leave silently (a Node parent: libuv's job sets SILENT_BREAKAWAY_OK, and a job nested under
|
|
492
|
-
// it loses them too) it is not, and nothing then proves this gate's work gone after a crash: the record says so and a dead
|
|
493
|
-
// owner stays busy. (Counting the job's processes cannot tell: a console child's host process lands in it either way.)
|
|
494
|
-
const answer = ps(selfCheckScript(name));
|
|
495
|
-
if (!/^(IN|OUT)$/m.test(answer)) throw new Error(`the containment self-check gave no answer (${answer.slice(0, 120)})`);
|
|
496
|
-
return { ...holding, contained: /^IN$/m.test(answer) };
|
|
497
|
-
},
|
|
498
|
-
};
|
|
499
|
-
}
|
|
500
|
-
// Every process with its parent, group and start, plus the pids that are this gate's own (itself, its ancestors and the `ps`
|
|
501
|
-
// that listed them), which are never another owner's children even when they share its group.
|
|
502
|
-
const psList = () => {
|
|
503
|
-
const r = run(spawn, "ps", ["-A", "-o", "pid=", "-o", "ppid=", "-o", "pgid=", "-o", "lstart="], { LC_ALL: "C", LANG: "C" });
|
|
504
|
-
if (r.error || r.status !== 0) throw new Error(`ps: ${r.error?.message ?? (String(r.stderr ?? "").trim() || `exit ${r.status}`)}`);
|
|
505
|
-
const rows = String(r.stdout ?? "").split(/\r?\n/).map((l) => /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(l)).filter(Boolean)
|
|
506
|
-
.map((m) => ({ pid: Number(m[1]), ppid: Number(m[2]), group: Number(m[3]), startedMs: Date.parse(m[4].replace(/\s+/g, " ")) }));
|
|
507
|
-
const byPid = new Map(rows.map((row) => [row.pid, row]));
|
|
508
|
-
const own = new Set(Number.isInteger(r.pid) ? [r.pid] : []);
|
|
509
|
-
for (let pid = process.pid; pid > 1 && !own.has(pid); pid = byPid.get(pid)?.ppid ?? 0) own.add(pid);
|
|
510
|
-
return { rows, own, byPid };
|
|
511
|
-
};
|
|
512
|
-
// Linux /proc. An entry this gate cannot read is a fact to decide, never a silent skip: gone (ENOENT/ESRCH) is not a reader;
|
|
513
|
-
// another user's process is skipped (it cannot read this user's managed root; its uid comes from /proc/<pid>/status, readable
|
|
514
|
-
// by everyone); anything else, including a process of this user (EACCES/EPERM: non-dumpable, hidepid) is UNKNOWN and throws, so
|
|
515
|
-
// the caller stays busy.
|
|
516
|
-
const GONE = new Set(["ENOENT", "ESRCH"]);
|
|
517
|
-
// A real Linux host always has /proc, so its absence there is unknown (throws below); a Linux platform simulated on another host
|
|
518
|
-
// (gate-contract's linux cases on a Mac) has nothing real to read and falls through to "no net".
|
|
519
|
-
const procAvailable = () => platform === "linux" && (process.platform === "linux" || procExists(proc));
|
|
520
|
-
const procPids = () => {
|
|
521
|
-
if (!procExists(proc)) throw new Error(`no ${proc} on this linux host`);
|
|
522
|
-
return readdir(proc).filter((name) => /^\d+$/.test(name) && Number(name) !== process.pid).map(Number);
|
|
523
|
-
};
|
|
524
|
-
const bootMs = () => {
|
|
525
|
-
const m = /^btime (\d+)$/m.exec(String(readFile(`${proc}/stat`, "utf8")));
|
|
526
|
-
if (!m) throw new Error(`no btime in ${proc}/stat`);
|
|
527
|
-
return Number(m[1]) * 1000;
|
|
528
|
-
};
|
|
529
|
-
// When pid started, from /proc/<pid>/stat field 22 (clock ticks since boot, USER_HZ = 100 on Linux) and the boot time. stat and
|
|
530
|
-
// status stay readable for non-dumpable processes. btime has one-second resolution, so the figure can be up to a second early.
|
|
531
|
-
const TICKS_PER_SECOND = 100;
|
|
532
|
-
const startedAt = (pid, boot) => {
|
|
533
|
-
const text = String(readFile(`${proc}/${pid}/stat`, "utf8"));
|
|
534
|
-
const fields = text.slice(text.lastIndexOf(")") + 2).split(" "); // from field 3 (state) on; comm may hold spaces and parens
|
|
535
|
-
const ticks = Number(fields[19]);
|
|
536
|
-
if (!Number.isInteger(ticks)) throw new Error(`cannot read the start time in ${proc}/${pid}/stat`);
|
|
537
|
-
return boot + Math.round((ticks * 1000) / TICKS_PER_SECOND);
|
|
538
|
-
};
|
|
539
|
-
// THE INVARIANT behind skipping an unreadable (EACCES/EPERM) process of this user, which could be reading the snapshot unseen:
|
|
540
|
-
// it is skipped only if it started before `skipBefore` (less START_SLACK_MS of reading error), the BASELINE of this ownership,
|
|
541
|
-
// which is the later of
|
|
542
|
-
// (1) the acquisition of the previous owner whose release proved zero readers (the record's `cleanBefore`, from the durable
|
|
543
|
-
// marker of that release): the process predates that owner too, so it is no leftover of any owner whose work is unresolved;
|
|
544
|
-
// (2) the birth of the snapshot root in this boot (the root's birth record), capped at this ownership's acquisition: a process
|
|
545
|
-
// that started before the root existed cannot have held it open from before, and one that started before this ownership
|
|
546
|
-
// is not the gate's own.
|
|
547
|
-
// With neither (a previous release that ended held, unknown or reclaimed leaves no marker; a missing, malformed or other-boot
|
|
548
|
-
// birth record) the baseline is this ownership's own acquisition (decision D1, 5.23 amended): nothing that started before this
|
|
549
|
-
// record was published is the unproven work of any owner, because every record is published on a free host after a release that
|
|
550
|
-
// proved zero readers, or by a reclaim that proved the previous work gone. A process that started at or after that, when its
|
|
551
|
-
// start time cannot be read, or when its stat is unreadable, stays held.
|
|
552
|
-
const unreadable = (pid, e, skipBefore) => {
|
|
553
|
-
if (GONE.has(e.code)) return;
|
|
554
|
-
if (!["EACCES", "EPERM"].includes(e.code)) throw e;
|
|
555
|
-
let status;
|
|
556
|
-
try { status = String(readFile(`${proc}/${pid}/status`, "utf8")); } catch (e2) { if (GONE.has(e2.code)) return; throw new Error(`${proc}/${pid} is unreadable (${e.code}) and so is its owner (${e2.code ?? e2.message}), so what it reads is unknown`); }
|
|
557
|
-
// A zombie (Z) or dead (X) process has no memory, descriptors or working directory, and its /proc entries refuse reads: it reads nothing.
|
|
558
|
-
if (/^State:\s*[ZXx]/m.test(status)) return;
|
|
559
|
-
const m = /^Uid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/m.exec(status);
|
|
560
|
-
if (!m) throw new Error(`${proc}/${pid} is unreadable (${e.code}) and its owner cannot be read, so what it reads is unknown`);
|
|
561
|
-
if (Number.isInteger(uid) && ![1, 2, 3, 4].some((i) => Number(m[i]) === uid)) return;
|
|
562
|
-
const what = `${/^Name:\s*(.*)$/m.exec(status)?.[1] ?? "?"}, ${/^State:\s*(\S+)/m.exec(status)?.[1] ?? "?"}`;
|
|
563
|
-
const unknown = (why) => new Error(`${proc}/${pid} (a process of this user: ${what}) is unreadable (${e.code}) and ${why}, so what it reads is unknown`);
|
|
564
|
-
if (!Number.isFinite(skipBefore)) throw unknown("there is no baseline for this ownership (no clean previous release is recorded, and no birth record of the snapshot root in this boot)");
|
|
565
|
-
let startMs;
|
|
566
|
-
try { startMs = startedAt(pid, bootMs()); } catch (e3) { if (GONE.has(e3.code)) return; throw unknown(`its start time cannot be read (${e3.code ?? e3.message})`); }
|
|
567
|
-
if (startMs + START_SLACK_MS < skipBefore) return;
|
|
568
|
-
throw unknown(`it started at ${new Date(startMs).toISOString()}, not before the baseline ${new Date(skipBefore).toISOString()} (the later of the last clean release's acquisition and the snapshot root's birth, else this ownership's own acquisition)`);
|
|
569
|
-
};
|
|
570
|
-
// A process in the middle of execve is briefly non-dumpable (its new address space has no dumpable flag until the exec commits), so
|
|
571
|
-
// /proc/<pid>/{environ,cwd,fd,...} answer EACCES for a few milliseconds while its comm is still the parent's (`node-MainThread`)
|
|
572
|
-
// and its start is the fork's. Under concurrent test shards or any busy host, a scan meets such a process: it is no reader and not
|
|
573
|
-
// unknown, only not yet readable. So a read that would HOLD (a young, unreadable, live process of this user) is retried, bounded
|
|
574
|
-
// (SETTLE_TRIES x SETTLE_MS), before the hold stands; a process that stays unreadable (really non-dumpable) is held exactly as
|
|
575
|
-
// before, and a process that is old, gone, a zombie or another user's is judged at once, with no wait.
|
|
576
|
-
const SETTLE_TRIES = 20; const SETTLE_MS = 25;
|
|
577
|
-
/** `{ value }` of `op`, or `{ skipped: true }` when its failure is a process no reader (`unreadable` returned); throws what `unreadable` throws once the retries are spent. */
|
|
578
|
-
const settled = (pid, skipBefore, op) => {
|
|
579
|
-
for (let attempt = 0; ; attempt++) {
|
|
580
|
-
try { return { value: op() }; }
|
|
581
|
-
catch (e) {
|
|
582
|
-
if (!GONE.has(e.code) && !["EACCES", "EPERM"].includes(e.code)) throw e;
|
|
583
|
-
try { unreadable(pid, e, skipBefore); return { skipped: true }; }
|
|
584
|
-
catch (held) { if (attempt >= SETTLE_TRIES) throw held; sleep(SETTLE_MS); }
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
};
|
|
588
|
-
return {
|
|
589
|
-
platform,
|
|
590
|
-
/** `{ alive, startedMs, group }` from `ps` (C locale). */
|
|
591
|
-
identity(pid) {
|
|
592
|
-
if (!exists(pid)) return { alive: false, startedMs: null, group: null };
|
|
593
|
-
const row = psList().rows.find((p) => p.pid === pid);
|
|
594
|
-
if (!row) return { alive: false, startedMs: null, group: null };
|
|
595
|
-
if (!Number.isFinite(row.startedMs)) throw new Error(`cannot read the start time of pid ${pid}`);
|
|
596
|
-
return { alive: true, startedMs: row.startedMs, group: row.group };
|
|
597
|
-
},
|
|
598
|
-
/** This boot's identity for a snapshot root's birth record (null when unknown). */
|
|
599
|
-
bootId() { return platform === "linux" ? hostBootId({ platform, readFile, bootIdFile: `${proc}/sys/kernel/random/boot_id` }) : hostBootId({ platform, spawn }); },
|
|
600
|
-
bootTime() {
|
|
601
|
-
if (platform === "linux") {
|
|
602
|
-
return bootMs();
|
|
603
|
-
}
|
|
604
|
-
const r = run(spawn, "sysctl", ["-n", "kern.boottime"]);
|
|
605
|
-
const m = /sec = (\d+)/.exec(String(r.stdout ?? ""));
|
|
606
|
-
if (r.error || r.status !== 0 || !m) throw new Error("cannot read kern.boottime");
|
|
607
|
-
return Number(m[1]) * 1000;
|
|
608
|
-
},
|
|
609
|
-
/**
|
|
610
|
-
* Process group `group` now: `members` (this gate, its ancestors and its own `ps` left out), every process by pid (for
|
|
611
|
-
* ancestry) and the set of this gate's own pids.
|
|
612
|
-
*/
|
|
613
|
-
groupSnapshot(group) {
|
|
614
|
-
if (!Number.isInteger(group) || group <= 1) throw new Error(`no usable process group (${group})`);
|
|
615
|
-
const { rows, own } = psList();
|
|
616
|
-
const members = rows.filter((p) => p.group === group && !own.has(p.pid));
|
|
617
|
-
for (const p of members) if (!Number.isFinite(p.startedMs)) throw new Error(`cannot read the start time of pid ${p.pid}`);
|
|
618
|
-
return { members, byPid: new Map(rows.map((row) => [row.pid, row])), own };
|
|
619
|
-
},
|
|
620
|
-
/** One fresh process table for every recorded group in this release; never retained across releases. */
|
|
621
|
-
groupSnapshots(groups) {
|
|
622
|
-
for (const group of groups) if (!Number.isInteger(group) || group <= 1) throw new Error(`no usable process group (${group})`);
|
|
623
|
-
const { rows, own } = psList();
|
|
624
|
-
const byPid = new Map(rows.map((row) => [row.pid, row]));
|
|
625
|
-
const snapshots = new Map([...new Set(groups)].map((group) => [group, { members: [], byPid, own }]));
|
|
626
|
-
for (const p of rows) {
|
|
627
|
-
const snapshot = snapshots.get(p.group);
|
|
628
|
-
if (!snapshot || own.has(p.pid)) continue;
|
|
629
|
-
if (!Number.isFinite(p.startedMs)) throw new Error(`cannot read the start time of pid ${p.pid}`);
|
|
630
|
-
snapshot.members.push(p);
|
|
631
|
-
}
|
|
632
|
-
return snapshots;
|
|
633
|
-
},
|
|
634
|
-
/**
|
|
635
|
-
* Pids of processes whose environment carries `<OWNERSHIP_ENV>=<handle>` (this gate's own chain left out). Linux reads
|
|
636
|
-
* /proc/<pid>/environ (an unreadable entry of this user's throws: unknown); macOS reads `ps eww`, which shows the environment
|
|
637
|
-
* of every process the user may inspect except Apple platform binaries (/bin/*, /usr/bin/*), which `hiddenHolders` judges by
|
|
638
|
-
* lineage and the snapshot-use net covers. null where neither exists.
|
|
639
|
-
*/
|
|
640
|
-
tokenHolders(handle, skipBefore) {
|
|
641
|
-
const token = `${OWNERSHIP_ENV}=${handle}`;
|
|
642
|
-
if (procAvailable()) {
|
|
643
|
-
const needle = Buffer.from(`${token}\0`);
|
|
644
|
-
const found = [];
|
|
645
|
-
for (const pid of procPids()) {
|
|
646
|
-
const got = settled(pid, skipBefore, () => readFile(`${proc}/${pid}/environ`));
|
|
647
|
-
if (got.skipped) continue;
|
|
648
|
-
const environ = got.value;
|
|
649
|
-
if (Buffer.concat([environ, Buffer.from("\0")]).includes(needle)) found.push(pid);
|
|
650
|
-
}
|
|
651
|
-
return found;
|
|
652
|
-
}
|
|
653
|
-
if (platform !== "darwin") return null;
|
|
654
|
-
const { own } = psList();
|
|
655
|
-
const r = run(spawn, "ps", ["eww", "-A", "-o", "pid=", "-o", "command="], { LC_ALL: "C", LANG: "C" });
|
|
656
|
-
if (r.error || r.status !== 0) throw new Error(`ps eww: ${r.error?.message ?? (String(r.stderr ?? "").trim() || `exit ${r.status}`)}`);
|
|
657
|
-
const pattern = new RegExp(`(^|\\s)${token.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&")}(\\s|$)`);
|
|
658
|
-
return String(r.stdout ?? "").split(/\r?\n/).map((l) => /^\s*(\d+)\s(.*)$/.exec(l)).filter((m) => m && !own.has(Number(m[1])) && Number(m[1]) !== r.pid && pattern.test(m[2])).map((m) => Number(m[1]));
|
|
659
|
-
},
|
|
660
|
-
/**
|
|
661
|
-
* macOS only (null elsewhere: Linux reads /proc/<pid>/environ under the unreadable rule, Windows uses job containment). The
|
|
662
|
-
* live same-user processes the token net cannot judge because `ps eww` shows no environment for them (hidden: an Apple
|
|
663
|
-
* platform binary, or a truly empty environment), plus any `lsof` cannot inspect, classified by `classifyHiddenProcesses`
|
|
664
|
-
* with this gate's anchor. `{ owner, anchorMs, recorded }` as there. Returns `[{ pid, why }]` (held), or throws: a listing
|
|
665
|
-
* that did not finish cleanly is unknown, and the caller stays busy.
|
|
666
|
-
*/
|
|
667
|
-
hiddenHolders({ owner, anchorMs, recorded = [], timing = null } = {}) {
|
|
668
|
-
if (platform !== "darwin") return null;
|
|
669
|
-
// Without this process's own user id nothing could be told from another user's (which is skipped): unknown, never "none".
|
|
670
|
-
if (!Number.isInteger(uid)) throw new Error("this process's user id is unknown");
|
|
671
|
-
const C = { LC_ALL: "C", LANG: "C" };
|
|
672
|
-
const own = new Set();
|
|
673
|
-
const listing = (what, r) => { if (Number.isInteger(r.pid)) own.add(r.pid); if (r.error || r.status !== 0) throw new Error(`${what}: ${r.error?.message ?? (String(r.stderr ?? "").trim().split(/\r?\n/).pop() || `exit ${r.status}`)}`); return String(r.stdout ?? ""); };
|
|
674
|
-
const table = listing("ps", run(spawn, "ps", ["-A", "-ww", "-o", "pid=", "-o", "ppid=", "-o", "pgid=", "-o", "uid=", "-o", "stat=", "-o", "lstart=", "-o", "command="], C));
|
|
675
|
-
const withEnv = listing("ps eww", run(spawn, "ps", ["eww", "-A", "-o", "pid=", "-o", "command="], C));
|
|
676
|
-
const lsofOut = listing("lsof", run(spawn, "lsof", ["-n", "-P", "-a", "-u", String(uid), "-Fp"]));
|
|
677
|
-
const procs = [];
|
|
678
|
-
for (const line of table.split(/\r?\n/)) {
|
|
679
|
-
const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\w{3} \w{3}\s+\d+ \d\d:\d\d:\d\d \d{4})\s+(.*)$/.exec(line);
|
|
680
|
-
if (m) procs.push({ pid: Number(m[1]), ppid: Number(m[2]), group: Number(m[3]), uid: Number(m[4]), state: m[5], startedMs: Date.parse(m[6].replace(/\s+/g, " ")), command: m[7].trim() });
|
|
681
|
-
}
|
|
682
|
-
if (!procs.length) throw new Error("ps listed no process");
|
|
683
|
-
// This gate's own chain (itself and its ancestors) and the listings it just ran are never another owner's children.
|
|
684
|
-
const byPid = new Map(procs.map((p) => [p.pid, p]));
|
|
685
|
-
for (let pid = process.pid; pid > 1 && !own.has(pid); pid = byPid.get(pid)?.ppid ?? 0) own.add(pid);
|
|
686
|
-
const env = new Map();
|
|
687
|
-
for (const line of withEnv.split(/\r?\n/)) { const m = /^\s*(\d+)\s+(.*)$/.exec(line); if (m) env.set(Number(m[1]), m[2].trim()); }
|
|
688
|
-
const inspected = new Set(lsofOut.split(/\r?\n/).filter((l) => l.startsWith("p")).map((l) => Number(l.slice(1))));
|
|
689
|
-
for (const p of procs) {
|
|
690
|
-
// A process shows its environment when its `ps eww` line is its command line followed by more; anything else (no line, the
|
|
691
|
-
// same line, another command line) is hidden. An empty environment prints no more than the command, so it is hidden too.
|
|
692
|
-
const shown = env.get(p.pid);
|
|
693
|
-
p.hidden = !(shown !== undefined && shown.length > p.command.length && shown.startsWith(`${p.command} `));
|
|
694
|
-
p.uninspected = !inspected.has(p.pid);
|
|
695
|
-
}
|
|
696
|
-
// `launchctl blame <pid>` (LC_ALL=C, 5 s): exit 0 and a reason is a launchd job; exit 3 and the "not managed" line is a process
|
|
697
|
-
// launchd does not manage (a reparented orphan) or one that is gone; anything else is unknown (rc null: it could not run).
|
|
698
|
-
const blame = (pid) => {
|
|
699
|
-
const started = performance.now();
|
|
700
|
-
let r;
|
|
701
|
-
try { r = spawn("launchctl", ["blame", String(pid)], { encoding: "utf8", env: { ...process.env, LC_ALL: "C", LANG: "C" }, timeout: 5000, maxBuffer: 1 << 16 }); }
|
|
702
|
-
finally { if (timing) { timing.blameCount = (timing.blameCount ?? 0) + 1; timing.blameMs = (timing.blameMs ?? 0) + performance.now() - started; } }
|
|
703
|
-
if (r.error) return { rc: null, line: String(r.error.message ?? r.error) };
|
|
704
|
-
const text = `${String(r.stdout ?? "")}${String(r.stderr ?? "")}`.split(/\r?\n/).find((l) => l.trim() !== "") ?? "";
|
|
705
|
-
return { rc: r.status, line: text.trim() };
|
|
706
|
-
};
|
|
707
|
-
// Re-lists pids after the blame calls (the binding against pid reuse): `Map(pid -> { ppid, startedMs })`; a pid that is gone is absent.
|
|
708
|
-
const reread = (pids) => {
|
|
709
|
-
const r = run(spawn, "ps", ["-o", "pid=", "-o", "ppid=", "-o", "lstart=", "-p", pids.join(",")], C);
|
|
710
|
-
if (r.error || (r.status !== 0 && String(r.stdout ?? "").trim() !== "")) throw new Error(`ps -p: ${r.error?.message ?? `exit ${r.status}`}`);
|
|
711
|
-
const out = new Map();
|
|
712
|
-
for (const line of String(r.stdout ?? "").split(/\r?\n/)) {
|
|
713
|
-
const m = /^\s*(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ \d\d:\d\d:\d\d \d{4})\s*$/.exec(line);
|
|
714
|
-
if (m) out.set(Number(m[1]), { ppid: Number(m[2]), startedMs: Date.parse(m[3].replace(/\s+/g, " ")) });
|
|
715
|
-
}
|
|
716
|
-
return out;
|
|
717
|
-
};
|
|
718
|
-
return classifyHiddenProcesses({ procs, own, uid, owner, recorded, anchorMs, alive: exists, blame, reread });
|
|
719
|
-
},
|
|
720
|
-
/**
|
|
721
|
-
* Processes using the snapshot `dir` in a way a new session, a scrubbed environment and a working directory elsewhere do not
|
|
722
|
-
* hide, as `[{ pid, how }]` (this gate's own chain left out): its working or root directory, its executable, an open file
|
|
723
|
-
* descriptor or a mapped file inside `dir`, or an argument naming `dir`. Linux: /proc/<pid>/{cwd,root,exe,fd,maps,cmdline}
|
|
724
|
-
* (an unreadable entry of this user's throws: unknown). macOS: `lsof` for this user (cwd, txt, mem and every descriptor) and
|
|
725
|
-
* `ps -ww` arguments. null where neither exists.
|
|
726
|
-
*/
|
|
727
|
-
snapshotUsers(dir, skipBefore) {
|
|
728
|
-
// Only POSIX hosts have these nets; the paths they see are POSIX paths on every host (injected tables run on Windows too).
|
|
729
|
-
const posix = path.posix;
|
|
730
|
-
const roots = [posix.resolve(dir)];
|
|
731
|
-
try { const real = fs.realpathSync(dir); if (!roots.includes(real)) roots.push(real); } catch { /* the directory is gone: only its recorded spelling can be named */ }
|
|
732
|
-
// Outside is exactly `..`, `../x` or an absolute relative path: a directory named `..x` inside the snapshot is inside it.
|
|
733
|
-
const inside = (p) => posix.isAbsolute(p) && roots.some((root) => { const rel = posix.relative(root, p); return !(rel === ".." || rel.startsWith("../") || posix.isAbsolute(rel)); });
|
|
734
|
-
const named = (text) => roots.some((root) => namesDir(text, root));
|
|
735
|
-
if (!procAvailable() && platform !== "darwin") return null;
|
|
736
|
-
const { own } = psList();
|
|
737
|
-
const found = []; const seen = new Set();
|
|
738
|
-
const add = (pid, how) => { if (own.has(pid) || seen.has(pid)) return; seen.add(pid); found.push({ pid, how }); };
|
|
739
|
-
if (procAvailable()) {
|
|
740
|
-
// /proc/<pid>/fd and maps list the files a process holds open or mapped right now; cmdline survives its other changes.
|
|
741
|
-
const targetOf = (file) => { try { return readlink(file); } catch (e) { if (GONE.has(e.code)) return null; throw e; } };
|
|
742
|
-
for (const pid of procPids()) {
|
|
743
|
-
if (own.has(pid)) continue;
|
|
744
|
-
settled(pid, skipBefore, () => {
|
|
745
|
-
for (const [link, how] of [["cwd", "working directory"], ["root", "root directory"], ["exe", "executable"]]) {
|
|
746
|
-
const target = targetOf(`${proc}/${pid}/${link}`);
|
|
747
|
-
if (target !== null && inside(target)) { add(pid, how); break; }
|
|
748
|
-
}
|
|
749
|
-
if (!seen.has(pid)) {
|
|
750
|
-
let fds = []; try { fds = readdir(`${proc}/${pid}/fd`); } catch (e) { if (!GONE.has(e.code)) throw e; }
|
|
751
|
-
for (const fd of fds) { const target = targetOf(`${proc}/${pid}/fd/${fd}`); if (target !== null && inside(target)) { add(pid, `open file ${target}`); break; } }
|
|
752
|
-
}
|
|
753
|
-
if (!seen.has(pid)) {
|
|
754
|
-
let maps = ""; try { maps = String(readFile(`${proc}/${pid}/maps`, "utf8")); } catch (e) { if (!GONE.has(e.code)) throw e; }
|
|
755
|
-
for (const line of maps.split("\n")) { const m = /^\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\/.*?)(?: \(deleted\))?$/.exec(line); if (m && inside(m[1])) { add(pid, `mapped file ${m[1]}`); break; } }
|
|
756
|
-
}
|
|
757
|
-
if (!seen.has(pid)) {
|
|
758
|
-
let cmdline = ""; try { cmdline = String(readFile(`${proc}/${pid}/cmdline`, "utf8")); } catch (e) { if (!GONE.has(e.code)) throw e; }
|
|
759
|
-
if (named(cmdline)) add(pid, "argument");
|
|
760
|
-
}
|
|
761
|
-
});
|
|
762
|
-
}
|
|
763
|
-
return found;
|
|
764
|
-
}
|
|
765
|
-
const r = run(spawn, "lsof", ["-n", "-P", "-a", "-u", String(uid), "-Fpfn"]);
|
|
766
|
-
// Only a clean exit is a complete listing: any other status (even with output) is unknown, so the caller stays busy.
|
|
767
|
-
if (r.error || r.status !== 0) throw new Error(`lsof: ${r.error?.message ?? (String(r.stderr ?? "").trim().split(/\r?\n/).pop() || `exit ${r.status}`)}`);
|
|
768
|
-
if (Number.isInteger(r.pid)) own.add(r.pid);
|
|
769
|
-
let pid = null; let fd = "";
|
|
770
|
-
for (const line of String(r.stdout ?? "").split(/\r?\n/)) {
|
|
771
|
-
if (line.startsWith("p")) { pid = Number(line.slice(1)); fd = ""; }
|
|
772
|
-
else if (line.startsWith("f")) fd = line.slice(1);
|
|
773
|
-
else if (line.startsWith("n") && pid && inside(line.slice(1))) add(pid, fd === "cwd" ? "working directory" : fd === "rtd" ? "root directory" : fd === "txt" ? "executable or text file" : fd === "mem" ? `mapped file ${line.slice(1)}` : `open file ${line.slice(1)}`);
|
|
774
|
-
}
|
|
775
|
-
const a = run(spawn, "ps", ["-A", "-ww", "-o", "pid=", "-o", "command="], { LC_ALL: "C", LANG: "C" });
|
|
776
|
-
if (a.error || a.status !== 0) throw new Error(`ps arguments: ${a.error?.message ?? (String(a.stderr ?? "").trim() || `exit ${a.status}`)}`);
|
|
777
|
-
if (Number.isInteger(a.pid)) own.add(a.pid);
|
|
778
|
-
for (const line of String(a.stdout ?? "").split(/\r?\n/)) { const m = /^\s*(\d+)\s(.*)$/.exec(line); if (m && named(m[2])) add(Number(m[1]), "argument"); }
|
|
779
|
-
return found;
|
|
780
|
-
},
|
|
781
|
-
/** This gate's ancestors, nearest first, as `[{ pid, startedMs }]` (pid 1 and the gate itself left out). */
|
|
782
|
-
ancestors() {
|
|
783
|
-
const { byPid } = psList();
|
|
784
|
-
const chain = [];
|
|
785
|
-
for (let row = byPid.get(process.pid); row && row.ppid > 1 && chain.length < 64; ) {
|
|
786
|
-
row = byPid.get(row.ppid);
|
|
787
|
-
if (row) chain.push({ pid: row.pid, startedMs: Number.isFinite(row.startedMs) ? row.startedMs : null });
|
|
788
|
-
}
|
|
789
|
-
return chain;
|
|
790
|
-
},
|
|
791
|
-
};
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
/**
|
|
795
|
-
* Spawns through `spawn`. A call that detaches the child (POSIX: a new session and process group, which the gate's own group no
|
|
796
|
-
* longer covers) while a build ownership is held records it first: an intent file before the spawn, then the child's group (its
|
|
797
|
-
* pid) once it exists, so a crashed gate's record is kept until that group is empty; a crash between the two leaves the intent,
|
|
798
|
-
* which keeps the record (unknown group). Windows children stay in the gate's job, so nothing is recorded there. Every detached
|
|
799
|
-
* launch on a gate path goes through here (scans, right-release builds, heavy-command).
|
|
800
|
-
*/
|
|
801
|
-
export function spawnUnderOwnership(spawn, command, args, options = {}, { env = process.env, platform = process.platform } = {}) {
|
|
802
|
-
const handle = env[OWNERSHIP_ENV] ?? options?.env?.[OWNERSHIP_ENV];
|
|
803
|
-
if (!options?.detached || platform === "win32" || !handle) return spawn(command, args, options);
|
|
804
|
-
const merged = { ...(options.env ?? {}), ...env };
|
|
805
|
-
// The handle names a per-repository record: its file variable is required, and there is no host-wide default to fall back to.
|
|
806
|
-
const ownedFile = merged[OWNERSHIP_FILE_ENV];
|
|
807
|
-
if (!ownedFile) throw new OwnershipBusy(`build ownership: ${OWNERSHIP_ENV} is set but ${OWNERSHIP_FILE_ENV} is not, so the repository's ownership record is unknown and the detached child is not started`);
|
|
808
|
-
const dir = childrenDir(ownedFile, handle);
|
|
809
|
-
try { fs.mkdirSync(dir, { mode: 0o700 }); } catch (e) { if (e.code !== "EEXIST") throw e; } // the ownership directory exists while this gate holds it
|
|
810
|
-
const intent = path.join(dir, `intent-${process.pid}-${crypto.randomUUID()}.json`);
|
|
811
|
-
// The child's start lower bound is taken BEFORE it is created, so however long this process pauses before recording the
|
|
812
|
-
// group, every member of it started at or after the bound (a later bound would read a live group as pid reuse).
|
|
813
|
-
const notBefore = Date.now() - START_SLACK_MS;
|
|
814
|
-
fs.writeFileSync(intent, JSON.stringify({ by: process.pid, at: new Date().toISOString(), notBefore, command: String(command) }), { flag: "wx", mode: 0o600 });
|
|
815
|
-
let child;
|
|
816
|
-
try { child = spawn(command, args, options); } catch (e) { fs.rmSync(intent, { force: true }); throw e; }
|
|
817
|
-
if (child?.pid) fs.writeFileSync(path.join(dir, `group-${child.pid}.json`), JSON.stringify({ group: child.pid, startedMs: notBefore, command: String(command) }), { mode: 0o600 });
|
|
818
|
-
fs.rmSync(intent, { force: true });
|
|
819
|
-
return child;
|
|
820
|
-
}
|
|
821
|
-
|
|
822
|
-
export const CLEAN_SCHEMA = "rightkit.build-ownership-clean/1";
|
|
823
|
-
/** Beside the owner record: the acquisition time of the last owner whose release proved zero readers. */
|
|
824
|
-
export const cleanMarkerFile = (file) => path.join(path.dirname(file), "last-clean-release.json");
|
|
825
|
-
/** The marker's acquisition time (ISO), or null when absent, unreadable or malformed (no clean release is then known). */
|
|
826
|
-
export function readCleanMarker(file) {
|
|
827
|
-
try {
|
|
828
|
-
const m = JSON.parse(fs.readFileSync(cleanMarkerFile(file), "utf8"));
|
|
829
|
-
return m?.schema === CLEAN_SCHEMA && Number.isFinite(Date.parse(m.acquiredAt)) ? m.acquiredAt : null;
|
|
830
|
-
} catch { return null; }
|
|
831
|
-
}
|
|
832
|
-
function writeCleanMarker(file, owner) {
|
|
833
|
-
const target = cleanMarkerFile(file); const tmp = `${target}.${crypto.randomUUID()}.tmp`;
|
|
834
|
-
try {
|
|
835
|
-
fs.writeFileSync(tmp, JSON.stringify({ schema: CLEAN_SCHEMA, acquiredAt: owner.acquiredAt, releasedAt: new Date().toISOString(), handle: owner.handle }), { flag: "wx", mode: 0o600 });
|
|
836
|
-
fs.renameSync(tmp, target);
|
|
837
|
-
} catch { /* no marker: nothing is skipped, which only holds more */ } finally { fs.rmSync(tmp, { force: true }); }
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
export const ROOT_BIRTH_SCHEMA = "rightkit.snapshot-root-birth/1";
|
|
841
|
-
/** Inside a snapshot root: when this root came into being, and in which boot of the host. */
|
|
842
|
-
export const rootBirthFile = (root) => path.join(root, ".rightkit-root-birth.json");
|
|
843
|
-
/** This boot's identity: Linux boot_id, macOS kern.bootsessionuuid; null where it cannot be read (Windows, a failure): no baseline then. */
|
|
844
|
-
export function hostBootId({ platform = process.platform, readFile = fs.readFileSync, spawn = spawnSync, bootIdFile = "/proc/sys/kernel/random/boot_id" } = {}) {
|
|
845
|
-
try {
|
|
846
|
-
if (platform === "linux") { const id = String(readFile(bootIdFile, "utf8")).trim(); return /^[0-9a-f-]{16,}$/i.test(id) ? id : null; }
|
|
847
|
-
if (platform === "darwin") {
|
|
848
|
-
// kern.bootsessionuuid: one UUID per boot, stable for the whole boot (kern.boottime moves when the wall clock is stepped).
|
|
849
|
-
const r = run(spawn, "sysctl", ["-n", "kern.bootsessionuuid"]);
|
|
850
|
-
const id = String(r.stdout ?? "").trim();
|
|
851
|
-
return !r.error && r.status === 0 && /^[0-9a-f-]{16,}$/i.test(id) ? id : null;
|
|
852
|
-
}
|
|
853
|
-
} catch { /* unknown */ }
|
|
854
|
-
return null;
|
|
855
|
-
}
|
|
856
|
-
/**
|
|
857
|
-
* Writes the birth record of a snapshot root that was just created (never over an existing one). Best effort: without it the
|
|
858
|
-
* root has no baseline and build ownership applies its strict rule. Returns whether it wrote.
|
|
859
|
-
*/
|
|
860
|
-
export function recordRootBirth(root, { now = Date.now, bootId = hostBootId() } = {}) {
|
|
861
|
-
try {
|
|
862
|
-
fs.writeFileSync(rootBirthFile(root), JSON.stringify({ schema: ROOT_BIRTH_SCHEMA, createdAt: new Date(now()).toISOString(), bootId }), { flag: "wx", mode: 0o600 });
|
|
863
|
-
return true;
|
|
864
|
-
} catch { return false; }
|
|
865
|
-
}
|
|
866
|
-
/** When `root` was born (epoch ms), or null when there is no readable birth record of THIS boot (missing, malformed, another boot). */
|
|
867
|
-
export function readRootBirth(root, bootId) {
|
|
868
|
-
if (typeof bootId !== "string" || !bootId) return null;
|
|
869
|
-
try {
|
|
870
|
-
const b = JSON.parse(fs.readFileSync(rootBirthFile(root), "utf8"));
|
|
871
|
-
const at = Date.parse(b?.createdAt);
|
|
872
|
-
return b?.schema === ROOT_BIRTH_SCHEMA && b.bootId === bootId && Number.isFinite(at) ? at : null;
|
|
873
|
-
} catch { return null; }
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
/**
|
|
877
|
-
* Migration for a snapshot root with no usable baseline: it predates birth records (an older gate made it), or its birth record
|
|
878
|
-
* names another boot (a reboot happened since). On Linux, one non-dumpable agent of this user (ssh-agent) would otherwise hold
|
|
879
|
-
* every release. A root is a cache, so under THIS process's own ownership, taken on a free host (no owner record existed; never a
|
|
880
|
-
* reclaim, never a nested gate), before this sync's first write, its snapshots are deleted and the root is born anew, with this
|
|
881
|
-
* boot's identity. Why that is sound: after a reboot no process of the old boot is alive, so the old root has no live readers; a
|
|
882
|
-
* free host proves there is no current owner; and the fresh birth makes the strict rule apply only to processes that started after
|
|
883
|
-
* it. Only this repository's own entries are deleted (see the body). Refused (the root stays as it was, strict) when: this process does not hold the only record, or the record is not a free-host
|
|
884
|
-
* acquisition; this boot's identity cannot be read; the root is missing or is a link (a missing root is born by the sync); its birth
|
|
885
|
-
* record is unreadable, or names THIS boot; or anything in the root is not a snapshot artifact (`<16 hex>`, `<16 hex>.lock`,
|
|
886
|
-
* `.state.json`, `.staging`, or the birth record), because a root that is some other directory is never emptied.
|
|
887
|
-
* Returns `{ migrated, why }`.
|
|
888
|
-
*/
|
|
889
|
-
export function migrateBirthlessRoot(root, { env = process.env, file = env[OWNERSHIP_FILE_ENV], bootId = hostBootId(), hooks = {} } = {}) {
|
|
890
|
-
const no = (why) => ({ migrated: false, why });
|
|
891
|
-
const handle = env[OWNERSHIP_ENV];
|
|
892
|
-
if (!handle || !file) return no("this process holds no build ownership");
|
|
893
|
-
let record = null; try { record = JSON.parse(fs.readFileSync(file, "utf8")); } catch { record = null; }
|
|
894
|
-
if (record?.handle !== handle || record.pid !== process.pid) return no("this process does not hold the owner record");
|
|
895
|
-
if (record.freeHost !== true) return no("the ownership was not taken on a free host");
|
|
896
|
-
if (typeof bootId !== "string" || !bootId) return no("this boot's identity cannot be read");
|
|
897
|
-
let st = null; try { st = fs.lstatSync(root); } catch { st = null; }
|
|
898
|
-
if (!st?.isDirectory()) return no("the root is missing or is not a plain directory");
|
|
899
|
-
let reason = "the root had no birth record";
|
|
900
|
-
if (fs.existsSync(rootBirthFile(root))) {
|
|
901
|
-
let birth = null; try { birth = JSON.parse(fs.readFileSync(rootBirthFile(root), "utf8")); } catch { birth = null; }
|
|
902
|
-
if (birth?.schema !== ROOT_BIRTH_SCHEMA) return no("the root's birth record cannot be read");
|
|
903
|
-
if (birth.bootId === bootId) return no("the root already has a birth record of this boot");
|
|
904
|
-
reason = `the root's birth record names another boot (${JSON.stringify(birth.bootId)}, not ${JSON.stringify(bootId)})`;
|
|
905
|
-
}
|
|
906
|
-
let entries; try { entries = fs.readdirSync(root); } catch (e) { return no(`the root cannot be listed (${e.code ?? e.message})`); }
|
|
907
|
-
const birthName = path.basename(rootBirthFile(root));
|
|
908
|
-
const stranger = entries.find((n) => n !== birthName && !/^[0-9a-f]{16}(\.[A-Za-z0-9._-]+)?$/.test(n));
|
|
909
|
-
if (stranger !== undefined) return no(`${JSON.stringify(stranger)} in the root is not a snapshot artifact`);
|
|
910
|
-
// The root is shared by every repository, and a free host for THIS repository says nothing about another one. So this
|
|
911
|
-
// migration removes only THIS repository's own entries (`<key>` and `<key>.*`: the lock, the state file, the staging directory)
|
|
912
|
-
// and never another repository's, under any condition: a second repository can take its snapshot between any check made here
|
|
913
|
-
// and any delete, so no check can make a cross-repository delete safe. The root's birth is written only while no other
|
|
914
|
-
// repository holds or reclaims ownership (a decision, checked again right before the write); otherwise the root stays without a
|
|
915
|
-
// baseline and strict. Another repository's snapshots in the root are left to that repository's own migration.
|
|
916
|
-
const mine = path.basename(path.dirname(file));
|
|
917
|
-
const others = otherHolder(file);
|
|
918
|
-
if (others) return no(others);
|
|
919
|
-
hooks.afterHolderCheck?.();
|
|
920
|
-
const own = entries.filter((n) => n === mine || n.startsWith(`${mine}.`));
|
|
921
|
-
try { for (const n of own) fs.rmSync(path.join(root, n), { recursive: true, force: true }); }
|
|
922
|
-
catch (e) { return no(`this repository's snapshot could not be removed (${e.code ?? e.message}); the root stays without a baseline`); }
|
|
923
|
-
const late = otherHolder(file);
|
|
924
|
-
if (late) return no(`${late}; this repository's snapshot entries were removed and the root's birth was not written`);
|
|
925
|
-
if (fs.existsSync(rootBirthFile(root))) { try { fs.rmSync(rootBirthFile(root), { force: true }); } catch (e) { return no(`the old birth record could not be replaced (${e.code ?? e.message})`); } }
|
|
926
|
-
return recordRootBirth(root, { bootId }) ? { migrated: true, why: `${reason}; this repository's snapshot (${own.length} entr${own.length === 1 ? "y" : "ies"}) was deleted and the root was born anew in this boot` } : no("the new birth could not be recorded");
|
|
927
|
-
}
|
|
928
|
-
|
|
929
|
-
/**
|
|
930
|
-
* Whether anything other than the repository owning `file` holds build ownership or is reclaiming it: another repository's owner
|
|
931
|
-
* record or standing reclaim claim, or an older gate's host-wide `build-ownership/owner.json` (which holds EVERY repository, live or
|
|
932
|
-
* not). Returns the reason, or null. A listing or read failure is a reason (fail closed).
|
|
933
|
-
*/
|
|
934
|
-
function otherHolder(file) {
|
|
935
|
-
try {
|
|
936
|
-
const parent = path.dirname(path.dirname(file)); const mine = path.basename(path.dirname(file));
|
|
937
|
-
for (const d of fs.readdirSync(parent, { withFileTypes: true })) {
|
|
938
|
-
if (!d.isDirectory()) {
|
|
939
|
-
if (d.name === "owner.json" || d.name.startsWith("owner.json.")) return `an older gate's host-wide record (${path.join(parent, d.name)}) stands`;
|
|
940
|
-
if (d.name.endsWith(".reclaim")) return "a reclaim claim stands under the ownership directory";
|
|
941
|
-
continue;
|
|
942
|
-
}
|
|
943
|
-
const names = fs.readdirSync(path.join(parent, d.name));
|
|
944
|
-
if (names.some((n) => n.endsWith(".reclaim"))) return `a reclaim claim stands for repository ${d.name}`;
|
|
945
|
-
if (d.name !== mine && names.includes("owner.json")) return `another repository (${d.name}) holds build ownership`;
|
|
946
|
-
}
|
|
947
|
-
} catch (e) { return `other repositories' ownership cannot be listed (${e.code ?? e.message})`; }
|
|
948
|
-
return null;
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
/** The holder's last report, or null when absent or unreadable. */
|
|
952
|
-
export function readHolder(file) {
|
|
953
|
-
try { const h = JSON.parse(fs.readFileSync(file, "utf8")); return h?.schema === HOLDER_SCHEMA ? h : null; } catch { return null; }
|
|
954
|
-
}
|
|
955
|
-
|
|
956
|
-
/**
|
|
957
|
-
* RustRight's lease state for a snapshot & ownership handle (`rustright snapshot-lease status`). Anything but a well-formed
|
|
958
|
-
* answer is UNKNOWN: a missing client, a failed or unknown command, a schema or state the gate does not know.
|
|
959
|
-
*
|
|
960
|
-
* The answer is read exactly as the broker writes it (BROKER-CONTRACT section 16, GB-23 and GB-85): `{ type, schema, state, snapshot, ownership, members, waitedMs, waitTimedOut }`.
|
|
961
|
-
* `members` is one row per submission under the handle and `state` is only their aggregate (ACTIVE while any is held, REAPED only with at least one member and every member REAPED, else
|
|
962
|
-
* UNKNOWN); a state that is not the aggregate of its own rows is a contradiction, never a result. A wait was asked with `--wait-ms` (clamped to 30000): the answer then always carries
|
|
963
|
-
* `waitedMs` (a count) and `waitTimedOut` (a boolean, true exactly when the state is not REAPED at the bound). A timeout is UNKNOWN with the reason; the gate never polls and never resubmits.
|
|
964
|
-
* The result carries `members`, `waitedMs` and `waitTimedOut` for the callers that account by name.
|
|
965
|
-
*/
|
|
966
|
-
export function brokerLeaseState({ snapshot, handle, env = process.env, platform = process.platform, spawn = spawnSync, client = managedRuntimeClient(env, platform), waitMs = 0 }) {
|
|
967
|
-
if (!client) return { state: "UNKNOWN", why: "no RustRight client on this host" };
|
|
968
|
-
// GB-85: `--wait-ms N` makes the broker answer as soon as every submission under the handle is durably complete (REAPED), or at the bound with the state it has
|
|
969
|
-
// (waitTimedOut: true). A client that predates the option answers with a usage error: the plain query is then made, never a guess.
|
|
970
|
-
const clamp = (wait) => Math.min(Math.trunc(wait), 30_000);
|
|
971
|
-
const ask = (wait) => run(spawn, client, ["snapshot-lease", "status", "--snapshot", snapshot, "--ownership", handle, ...(wait > 0 ? ["--wait-ms", String(clamp(wait))] : [])], env);
|
|
972
|
-
let waited = Number.isFinite(waitMs) && waitMs > 0 ? waitMs : 0;
|
|
973
|
-
let r = ask(waited);
|
|
974
|
-
if (waited > 0 && r.status !== 0 && !r.error && /wait-ms|unknown|unexpected|unrecognized|usage/i.test(String(r.stderr ?? ""))) { waited = 0; r = ask(0); }
|
|
975
|
-
if (r.error || r.status !== 0) return { state: "UNKNOWN", why: `rustright snapshot-lease status: ${r.error?.message ?? (String(r.stderr ?? "").trim().split(/\r?\n/).pop() || `exit ${r.status}`)}` };
|
|
976
|
-
let answer = null;
|
|
977
|
-
try { answer = JSON.parse(String(r.stdout ?? "").trim().split(/\r?\n/).pop()); } catch { answer = null; }
|
|
978
|
-
if (answer?.schema !== LEASE_STATUS_SCHEMA || !LEASE_STATES.has(answer.state)) return { state: "UNKNOWN", why: `unrecognised lease status ${JSON.stringify(String(r.stdout ?? "").trim().slice(0, 200))}` };
|
|
979
|
-
// The answer must echo what was asked (RustRight echoes `snapshot` as received and `ownership` as the handle): another pair's answer,
|
|
980
|
-
// or no echo at all, binds nothing to this owner, so it is UNKNOWN and the record is held.
|
|
981
|
-
if (answer.snapshot !== snapshot || answer.ownership !== handle) return { state: "UNKNOWN", why: `the lease status does not echo the queried snapshot and ownership handle (${JSON.stringify(answer.snapshot ?? null)}, ${JSON.stringify(answer.ownership ?? null)})` };
|
|
982
|
-
const unknown = (why) => ({ state: "UNKNOWN", why: `rustright snapshot-lease status: ${why}`, ...(Array.isArray(answer.members) ? { members: answer.members } : {}) });
|
|
983
|
-
// GB-23: `members` is one row per submission the broker knows under the handle ({handle, state, spawned, refused?, job?}); the answer's own state is only the aggregate.
|
|
984
|
-
const covers = (h) => h === handle || String(h).startsWith(`${handle}#`);
|
|
985
|
-
if (!Array.isArray(answer.members)) return unknown("the answer carries no members list (one row per submission under the handle), so no submission can be accounted for by name");
|
|
986
|
-
if (answer.members.some((m) => !m || typeof m.handle !== "string" || !covers(m.handle) || !LEASE_STATES.has(m.state))) return { state: "UNKNOWN", why: `the lease status carries members that are not submissions under ${handle}` };
|
|
987
|
-
const rows = answer.members;
|
|
988
|
-
const aggregate = rows.some((m) => m.state === "ACTIVE") ? "ACTIVE" : rows.length > 0 && rows.every((m) => m.state === "REAPED") ? "REAPED" : "UNKNOWN";
|
|
989
|
-
if (answer.state !== aggregate) return unknown(`the answer says ${answer.state} but its ${rows.length} member row(s) aggregate to ${aggregate} (REAPED needs at least one member and every member REAPED): it contradicts itself, so it is not read`);
|
|
990
|
-
// GB-85: waitedMs is a count and waitTimedOut a boolean; both are always sent by a broker that takes a wait, and are required once a wait was asked.
|
|
991
|
-
const hasWaited = answer.waitedMs !== undefined; const hasTimedOut = answer.waitTimedOut !== undefined;
|
|
992
|
-
if (hasWaited && !(Number.isInteger(answer.waitedMs) && answer.waitedMs >= 0)) return unknown(`waitedMs is not a non-negative integer (${JSON.stringify(answer.waitedMs)})`);
|
|
993
|
-
if (hasTimedOut && typeof answer.waitTimedOut !== "boolean") return unknown(`waitTimedOut is not a boolean (${JSON.stringify(answer.waitTimedOut)})`);
|
|
994
|
-
if (waited > 0 && (!hasWaited || !hasTimedOut)) return unknown(`a wait of ${clamp(waited)} ms was asked but the answer carries no ${!hasWaited ? "waitedMs" : "waitTimedOut"}`);
|
|
995
|
-
const timedOut = answer.waitTimedOut === true;
|
|
996
|
-
if (timedOut && (waited <= 0 || answer.state === "REAPED")) return unknown(`waitTimedOut is true although ${waited <= 0 ? "no wait was asked" : "the state is REAPED"}: it contradicts itself`);
|
|
997
|
-
if (waited > 0 && answer.state !== "REAPED" && !timedOut) return unknown(`the state is ${answer.state} after a wait without waitTimedOut: it contradicts itself`);
|
|
998
|
-
const timing = { ...(hasWaited ? { waitedMs: answer.waitedMs } : {}), ...(hasTimedOut ? { waitTimedOut: answer.waitTimedOut } : {}) };
|
|
999
|
-
if (timedOut) return { state: "UNKNOWN", why: `rustright snapshot-lease status: still ${answer.state} after waiting ${answer.waitedMs} ms (waitTimedOut); ownership stays UNKNOWN`, members: rows, ...timing };
|
|
1000
|
-
return { state: answer.state, why: `rustright snapshot-lease status: ${answer.state}`, members: rows, ...timing };
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1003
|
-
function publish(target, text) {
|
|
1004
|
-
if (process.platform === "win32") {
|
|
1005
|
-
// Windows: no second name. Linking a temp file and deleting its name left owner.json a file that could not be replaced for
|
|
1006
|
-
// seconds (measured on the Dell, rename EPERM with no open handle on it; a plain exclusive create has no such state). The
|
|
1007
|
-
// record is created exclusively and written at once; a reader that catches it half-written cannot parse it and stays busy
|
|
1008
|
-
// (fail closed), and a failed write removes it.
|
|
1009
|
-
let fd;
|
|
1010
|
-
try { fd = fs.openSync(target, "wx", 0o600); } catch (e) { if (e.code === "EEXIST") return false; throw e; }
|
|
1011
|
-
try { fs.writeSync(fd, text); } catch (e) { try { fs.closeSync(fd); } catch { /* closed below */ } fs.rmSync(target, { force: true }); throw e; }
|
|
1012
|
-
fs.closeSync(fd);
|
|
1013
|
-
return true;
|
|
1014
|
-
}
|
|
1015
|
-
const tmp = `${target}.${crypto.randomUUID()}.tmp`;
|
|
1016
|
-
fs.writeFileSync(tmp, text, { flag: "wx", mode: 0o600 });
|
|
1017
|
-
try { fs.linkSync(tmp, target); return true; } catch (e) { if (e.code === "EEXIST") return false; throw e; } finally { fs.rmSync(tmp, { force: true }); }
|
|
1018
|
-
}
|
|
1019
|
-
const readText = (file) => { try { return fs.readFileSync(file, "utf8"); } catch (e) { if (e.code === "ENOENT") return null; throw e; } };
|
|
1020
|
-
|
|
1021
|
-
/**
|
|
1022
|
-
* Whether group member `m` is work the owner covers. Ancestors and peers share a group without being the gate's children (the
|
|
1023
|
-
* shell that started it, `| tee`, a later gate started by the same script), so a member counts only when it started after the
|
|
1024
|
-
* ownership began AND its ancestry does not end at a proven peer. The walk covers the member at the owner, at pid 1 (an orphan),
|
|
1025
|
-
* at an unknown parent, and at ANY process that predates the ownership except a peer parent: an orphan adopted by a subreaper
|
|
1026
|
-
* (systemd --user, WSL's init) has that subreaper as its parent now, and a subreaper is an ancestor of the gate as often as not,
|
|
1027
|
-
* so "a pre-existing parent" proves nothing about being the gate's work. A peer parent is the owner's recorded nearest
|
|
1028
|
-
* ancestor (the shell that ran `gate | tee`) or a process that shares the member's own process group (a script shell without job
|
|
1029
|
-
* control); a descendant of the asking gate is its own. Everything else is covered: a peer under another parent is held only
|
|
1030
|
-
* until it exits, never cleared by guesswork.
|
|
1031
|
-
*/
|
|
1032
|
-
function coveredMember(m, owner, { byPid, own }) {
|
|
1033
|
-
const since = Date.parse(owner.acquiredAt) - START_SLACK_MS;
|
|
1034
|
-
const before = (p) => !Number.isFinite(p.startedMs) || p.startedMs < since;
|
|
1035
|
-
if (own.has(m.pid) || before(m)) return false;
|
|
1036
|
-
// The owner's own ancestors (recorded at acquisition) are never its children, however recently they started.
|
|
1037
|
-
if (Array.isArray(owner.ancestors) && owner.ancestors.some((a) => a?.pid === m.pid && sameStart(a.startedMs, m.startedMs))) return false;
|
|
1038
|
-
const parent = Array.isArray(owner.ancestors) ? owner.ancestors[0] : null;
|
|
1039
|
-
const peerParent = (p) => (Number.isInteger(p.group) && p.group === m.group) || (!!parent && p.pid === parent.pid && sameStart(p.startedMs, parent.startedMs));
|
|
1040
|
-
const seen = new Set([m.pid]);
|
|
1041
|
-
for (let p = byPid.get(m.ppid); p; p = byPid.get(p.ppid)) {
|
|
1042
|
-
if (p.pid === owner.pid && sameStart(p.startedMs, owner.startedMs)) return true;
|
|
1043
|
-
if (p.pid <= 1 || seen.has(p.pid)) return true;
|
|
1044
|
-
seen.add(p.pid);
|
|
1045
|
-
if (p.pid === process.pid) return false;
|
|
1046
|
-
if (before(p) || own.has(p.pid)) return !peerParent(p);
|
|
1047
|
-
}
|
|
1048
|
-
return true;
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
/**
|
|
1052
|
-
* Whether the work `owner` covers, other than the process `self` (the live gate at release, null at reclaim), is proven gone.
|
|
1053
|
-
* Returns the proofs, or throws a reason that is busy.
|
|
1054
|
-
*/
|
|
1055
|
-
function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0, timing = null, revoked = null, processOnly = false, broker = null }) {
|
|
1056
|
-
const measure = (name, fn) => { const start = performance.now(); try { return fn(); } finally { if (timing) timing[name] = (timing[name] ?? 0) + performance.now() - start; } };
|
|
1057
|
-
const proofs = [];
|
|
1058
|
-
let rebooted = false;
|
|
1059
|
-
// A reboot is only a question for a dead owner; a live gate releasing its own record has not outlived one.
|
|
1060
|
-
if (selfPid === null) { try { rebooted = probe.bootTime() > Date.parse(owner.acquiredAt); } catch { rebooted = false; } }
|
|
1061
|
-
if (rebooted) proofs.push("the host rebooted after the record was written");
|
|
1062
|
-
const c = owner.containment ?? {};
|
|
1063
|
-
if (!rebooted && c.kind === "job" && c.contained === false && selfPid === null) {
|
|
1064
|
-
throw new Error(`job ${c.name} never held its gate's children (the gate's launcher lets children leave its job silently, so they left this one too), so their exit cannot be proven; it stays held until the host reboots`);
|
|
1065
|
-
}
|
|
1066
|
-
if (!rebooted && c.kind === "job" && selfPid !== null) {
|
|
1067
|
-
// A live release is fenced exactly like a crash: work that was never proven inside the job cannot be proven gone by it.
|
|
1068
|
-
if (c.contained !== true) throw new Error(`job ${c.name} was never proven to hold this gate's children (contained: ${c.contained}), so their exit cannot be proven; it stays held until the host reboots`);
|
|
1069
|
-
// Anything this gate spawned to look at the job would sit in the job itself, so the count comes from the holder (outside the
|
|
1070
|
-
// job), asked afresh now (a nonce it must echo after counting), never its last report. Children that just exited get a moment.
|
|
1071
|
-
const until = Date.now() + 3000;
|
|
1072
|
-
let answer;
|
|
1073
|
-
for (;;) {
|
|
1074
|
-
try { answer = probe.queryHolder(holderFile(file, owner.handle)); } catch (e) { throw new Error(`job ${c.name}'s holder gave no fresh count (${e.message})`); }
|
|
1075
|
-
if (!Number.isInteger(answer?.active) || answer.active < 1) throw new Error(`job ${c.name}'s holder counted ${answer?.active} process(es), but this live gate is one of them`);
|
|
1076
|
-
if (answer.active === 1 || Date.now() >= until) break;
|
|
1077
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
1078
|
-
}
|
|
1079
|
-
if (answer.active > 1) throw new Error(`job ${c.name} still holds ${answer.active} process(es) (this gate is one)`);
|
|
1080
|
-
proofs.push(`job ${c.name} holds only this gate (holder ${answer.holder} counted it at ${answer.at} for query ${answer.nonce})`);
|
|
1081
|
-
} else if (!rebooted && c.kind === "job") {
|
|
1082
|
-
let state;
|
|
1083
|
-
try { state = probe.jobState(c.name); } catch (e) { throw new Error(`job ${c.name} cannot be read (${e.message})`); }
|
|
1084
|
-
if (state.open) {
|
|
1085
|
-
const allowed = selfPid === null ? 0 : 1;
|
|
1086
|
-
if (state.active > allowed) throw new Error(`job ${c.name} still holds ${state.active} process(es)${selfPid === null ? "" : " (this gate is one)"}`);
|
|
1087
|
-
proofs.push(`job ${c.name} holds ${state.active === 0 ? "no process" : "only this gate"}`);
|
|
1088
|
-
} else {
|
|
1089
|
-
// Windows destroys a job object only after its last handle closed AND every process in it exited: a job that no longer exists holds no
|
|
1090
|
-
// process, whatever its holder managed to record (a holder torn down with its session never writes "drained"; Dell compile-6, 2026-11-06).
|
|
1091
|
-
const holder = readHolder(holderFile(file, owner.handle));
|
|
1092
|
-
if (holder?.state === "drained") proofs.push(`job ${c.name} drained (holder pid ${holder.holder} at ${holder.at})`);
|
|
1093
|
-
else if (holder?.state === "failed") proofs.push(`the gate never ran inside job ${c.name} (holder failed: ${holder.why})`);
|
|
1094
|
-
else proofs.push(`job ${c.name} no longer exists, so no process remains in it (holder recorded ${holder?.state ?? "nothing"})`);
|
|
1095
|
-
}
|
|
1096
|
-
} else if (!rebooted && c.kind === "group") {
|
|
1097
|
-
let snap;
|
|
1098
|
-
try { snap = measure("groupMs", () => probe.groupSnapshot(c.group)); } catch (e) { throw new Error(`process group ${c.group} cannot be listed (${e.message})`); }
|
|
1099
|
-
const children = snap.members.filter((m) => m.pid !== selfPid && coveredMember(m, owner, snap)).map((m) => m.pid);
|
|
1100
|
-
if (children.length) throw new Error(`process group ${c.group} still has ${children.length} member(s) started under this ownership: ${children.join(", ")}`);
|
|
1101
|
-
proofs.push(`process group ${c.group} has no member started under this ownership`);
|
|
1102
|
-
// Children the gate started detached lead groups of their own: each recorded group must be empty too.
|
|
1103
|
-
const registry = childrenDir(file, owner.handle);
|
|
1104
|
-
let entries = [];
|
|
1105
|
-
try { entries = fs.readdirSync(registry); } catch (e) { if (e.code !== "ENOENT") throw new Error(`the detached-child record ${registry} cannot be read (${e.message})`); }
|
|
1106
|
-
const intents = entries.filter((n) => n.startsWith("intent-"));
|
|
1107
|
-
if (intents.length) throw new Error(`a detached spawn was in flight when its gate stopped (${intents[0]}), so its process group is unknown`);
|
|
1108
|
-
const groups = entries.filter((n) => /^group-\d+\.json$/.test(n));
|
|
1109
|
-
if (timing) timing.detachedGroups = groups.length;
|
|
1110
|
-
const recorded = [];
|
|
1111
|
-
const groupRecords = [];
|
|
1112
|
-
for (const name of groups) {
|
|
1113
|
-
let entry, bytes, writtenMs;
|
|
1114
|
-
try {
|
|
1115
|
-
const entryFile = path.join(registry, name);
|
|
1116
|
-
bytes = fs.readFileSync(entryFile, "utf8");
|
|
1117
|
-
entry = JSON.parse(bytes);
|
|
1118
|
-
writtenMs = fs.statSync(entryFile).mtimeMs;
|
|
1119
|
-
} catch { throw new Error(`the detached-child entry ${name} cannot be read`); }
|
|
1120
|
-
if (!Number.isInteger(entry?.group) || !Number.isFinite(entry?.startedMs)) throw new Error(`the detached-child entry ${name} cannot be read`);
|
|
1121
|
-
recorded.push({ group: entry.group, command: entry.command });
|
|
1122
|
-
groupRecords.push({ name, entry, bytes, writtenMs });
|
|
1123
|
-
}
|
|
1124
|
-
let snapshots = null;
|
|
1125
|
-
if (groups.length && typeof probe.groupSnapshots === "function") {
|
|
1126
|
-
try { snapshots = measure("detachedGroupsMs", () => probe.groupSnapshots(groupRecords.map(({ entry }) => entry.group))); }
|
|
1127
|
-
catch (e) { throw new Error(`detached process groups cannot be listed (${e.message})`); }
|
|
1128
|
-
if (!(snapshots instanceof Map)) throw new Error("detached process groups cannot be listed (invalid bulk process table)");
|
|
1129
|
-
}
|
|
1130
|
-
for (const { entry, writtenMs } of groupRecords) {
|
|
1131
|
-
let snapshot;
|
|
1132
|
-
try { snapshot = snapshots ? snapshots.get(entry.group) : measure("detachedGroupsMs", () => probe.groupSnapshot(entry.group)); }
|
|
1133
|
-
catch (e) { throw new Error(`detached process group ${entry.group} cannot be listed (${e.message})`); }
|
|
1134
|
-
if (!snapshot || !Array.isArray(snapshot.members)) throw new Error(`detached process group ${entry.group} cannot be listed (missing process table)`);
|
|
1135
|
-
// A later leader is a reused group ID; otherwise any member at or after the recorded lower bound holds the release.
|
|
1136
|
-
const leader = snapshot.members.find((m) => m.pid === entry.group);
|
|
1137
|
-
if (leader && Number.isFinite(writtenMs) && leader.startedMs > writtenMs + START_SLACK_MS) continue;
|
|
1138
|
-
const live = snapshot.members.filter((m) => m.pid !== selfPid && m.startedMs >= entry.startedMs - START_SLACK_MS).map((m) => m.pid);
|
|
1139
|
-
if (live.length) throw new Error(`detached process group ${entry.group} (${entry.command}) still has ${live.length} member(s): ${live.join(", ")}`);
|
|
1140
|
-
}
|
|
1141
|
-
// Catch changes during this sample. As with the old per-group checks, this is not an atomic spawn/release fence.
|
|
1142
|
-
let after;
|
|
1143
|
-
try { after = fs.readdirSync(registry); } catch (e) { if (e.code === "ENOENT" && !groups.length) after = []; else throw new Error(`the detached-child record ${registry} cannot be re-read (${e.message})`); }
|
|
1144
|
-
const relevant = (names) => names.filter((n) => n.startsWith("intent-") || /^group-\d+\.json$/.test(n)).sort();
|
|
1145
|
-
if (JSON.stringify(relevant(entries)) !== JSON.stringify(relevant(after))) throw new Error("the detached-child registry changed during the process sample");
|
|
1146
|
-
for (const { name, bytes, writtenMs } of groupRecords) {
|
|
1147
|
-
try {
|
|
1148
|
-
const entryFile = path.join(registry, name);
|
|
1149
|
-
if (fs.readFileSync(entryFile, "utf8") !== bytes || fs.statSync(entryFile).mtimeMs !== writtenMs) throw new Error("changed");
|
|
1150
|
-
} catch { throw new Error(`the detached-child entry ${name} changed during the process sample`); }
|
|
1151
|
-
}
|
|
1152
|
-
if (groups.length) proofs.push(`the ${groups.length} detached process group(s) it started are empty`);
|
|
1153
|
-
// See `unreadable` in processProbe. The baseline is the later of (1) the acquisition of the last owner whose release proved zero
|
|
1154
|
-
// readers and (2) the snapshot root's birth in this boot, capped at this ownership's own acquisition (a process the gate
|
|
1155
|
-
// may have started is never baseline). NaN (neither) skips nothing.
|
|
1156
|
-
let birth = NaN;
|
|
1157
|
-
if (owner.snapshot) {
|
|
1158
|
-
try { const b = readRootBirth(path.dirname(owner.snapshot), probe.bootId?.()); if (b !== null) birth = Math.min(b, Date.parse(owner.acquiredAt)); } catch { birth = NaN; }
|
|
1159
|
-
}
|
|
1160
|
-
const baselines = [Date.parse(owner.cleanBefore ?? ""), birth].filter(Number.isFinite);
|
|
1161
|
-
// With no baseline (no clean previous release, no birth of the root in this boot, an unreadable boot id) the anchor is this record's
|
|
1162
|
-
// own acquisition: nothing that started before this ownership began is the unproven work of any owner (every record is published
|
|
1163
|
-
// on a free host after a release that proved zero readers, or by a reclaim that proved the previous work gone). Never "no anchor".
|
|
1164
|
-
const skipBefore = baselines.length ? Math.max(...baselines) : Date.parse(owner.acquiredAt);
|
|
1165
|
-
let carriers;
|
|
1166
|
-
try { carriers = measure("tokenHoldersMs", () => probe.tokenHolders(owner.handle, skipBefore)); } catch (e) { throw new Error(`processes carrying ${OWNERSHIP_ENV} cannot be listed (${e.message})`); }
|
|
1167
|
-
if (carriers) {
|
|
1168
|
-
const others = carriers.filter((pid) => pid !== selfPid);
|
|
1169
|
-
if (others.length) throw new Error(`process(es) ${others.join(", ")} still carry ${OWNERSHIP_ENV}=${owner.handle}`);
|
|
1170
|
-
proofs.push(`no process carries ${OWNERSHIP_ENV}=${owner.handle}`);
|
|
1171
|
-
}
|
|
1172
|
-
if (owner.snapshot) {
|
|
1173
|
-
let users;
|
|
1174
|
-
try { users = measure("snapshotUsersMs", () => probe.snapshotUsers(owner.snapshot, skipBefore)); } catch (e) { throw new Error(`processes using the snapshot cannot be listed (${e.message})`); }
|
|
1175
|
-
if (users) {
|
|
1176
|
-
const others = users.filter((u) => u.pid !== selfPid);
|
|
1177
|
-
if (others.length) throw new Error(`process(es) ${others.map((u) => `${u.pid} (${u.how})`).join(", ")} still use the snapshot ${owner.snapshot}`);
|
|
1178
|
-
proofs.push(`no process has a working directory, executable, open or mapped file or argument inside or naming ${owner.snapshot}`);
|
|
1179
|
-
}
|
|
1180
|
-
}
|
|
1181
|
-
// macOS: a process whose environment `ps eww` does not show cannot be attributed to this ownership by the token net. Start time plus a
|
|
1182
|
-
// hidden environment is no attribution (rightkit#1313: an unrelated same-user process started during the run held every later gate), so
|
|
1183
|
-
// such a process is REPORTED here and never held. Only lineage the gate recorded (tracked child groups and intents above), the exact
|
|
1184
|
-
// ownership token, an actual snapshot user, and the broker lease hold a release.
|
|
1185
|
-
if (typeof probe.hiddenHolders === "function") {
|
|
1186
|
-
let hidden;
|
|
1187
|
-
try { hidden = measure("hiddenHoldersMs", () => probe.hiddenHolders({ owner, anchorMs: skipBefore, recorded, timing })); } catch { hidden = null; }
|
|
1188
|
-
const others = (hidden ?? []).filter((h) => h.pid !== selfPid);
|
|
1189
|
-
if (others.length) {
|
|
1190
|
-
const shown = others.slice(0, 8);
|
|
1191
|
-
proofs.push(`reported, not held: ${others.length} unattributed process(es) of this user with a hidden environment started after the anchor (no recorded lineage, token or snapshot use): ${shown.map((h) => `${h.pid}: ${h.why}`).join("; ")}${others.length > shown.length ? `; and ${others.length - shown.length} more (pids ${others.slice(shown.length).map((h) => h.pid).join(", ")})` : ""}`);
|
|
1192
|
-
}
|
|
1193
|
-
}
|
|
1194
|
-
} else if (!rebooted) {
|
|
1195
|
-
throw new Error(`the record names no containment (${JSON.stringify(c)})`);
|
|
1196
|
-
}
|
|
1197
|
-
if (processOnly) {
|
|
1198
|
-
proofs.push("broker work NOT judged: a process-only proof (rightkit#1511) says nothing about broker leases");
|
|
1199
|
-
} else if (owner.broker?.submitted) {
|
|
1200
|
-
// Every submission under this handle must be accounted for by NAME, never by the bare handle (GB-21, GB-23, GB-85). The bare handle answers REAPED when at least one
|
|
1201
|
-
// member completed and none is held (rustright snapshot.rs `status`), so it proves only that no lease is held now: a completed sibling never stands in for an
|
|
1202
|
-
// unknown submission. Each recorded sub-handle (broker.handles, recorded before its send) is asked by its exact name and must be one of
|
|
1203
|
-
// - REAPED, as a member of that answer (a durable completion; `spawned: false` for a refusal that ran nothing), or
|
|
1204
|
-
// - UNSENT: the gate itself proved, under the record's lock, that its client never started (broker.unsent), AND the broker holds nothing under it (UNKNOWN, no members).
|
|
1205
|
-
// An UNKNOWN or ACTIVE one, an ambiguous send, a start that may have run, keeps the record; nothing is counted complete on the absence of a completion.
|
|
1206
|
-
const handles = [...new Set(Array.isArray(owner.broker.handles) ? owner.broker.handles : [])];
|
|
1207
|
-
const unsent = owner.broker.unsent && typeof owner.broker.unsent === "object" ? owner.broker.unsent : {};
|
|
1208
|
-
const waitOptions = waitMs > 0 ? { waitMs } : {};
|
|
1209
|
-
const settled = (sub) => unsent[sub] && typeof unsent[sub].reason === "string";
|
|
1210
|
-
// rightkit#1511: a sub-handle the broker can no longer answer may instead carry the broker's signed revocation of exactly that sub-handle, bound to
|
|
1211
|
-
// this record's bytes (handle-revocation.mjs). It is offered only by a dead owner's reclaim (judgeOwner), never by a release; a bad revocation throws.
|
|
1212
|
-
const revokedOf = new Map();
|
|
1213
|
-
const revocation = (sub) => { if (!revoked) return null; if (!revokedOf.has(sub)) revokedOf.set(sub, revoked(sub)); return revokedOf.get(sub); };
|
|
1214
|
-
// rightkit#1513 (Adrian, 2026-11-05: "It should ideally auto recover"): in a dead owner's reclaim (never a live release), after every process
|
|
1215
|
-
// proof above passed, a sub-handle the broker answers UNKNOWN with no member row was never received when the SAME broker process has run since
|
|
1216
|
-
// before this ownership was acquired: that broker would hold a claim, lease or member row for anything it got, and no process remains to send it.
|
|
1217
|
-
const acquiredMs = Date.parse(owner.acquiredAt);
|
|
1218
|
-
const brokerUpThroughout = selfPid === null && broker && Number.isFinite(broker.startedMs) && Number.isFinite(acquiredMs) && broker.startedMs + 2000 < acquiredMs;
|
|
1219
|
-
// The broker holding no work at all (brokerIdle) proves the same for a broker that restarted after this ownership was acquired.
|
|
1220
|
-
const brokerHoldsNothing = selfPid === null && Boolean(broker?.idle);
|
|
1221
|
-
const neverReceived = new Set();
|
|
1222
|
-
const everyUnsent = () => handles.length > 0 && handles.every((sub) => settled(sub) || revocation(sub) !== null || brokerUpThroughout || brokerHoldsNothing);
|
|
1223
|
-
const status = measure("leaseMs", () => lease({ snapshot: owner.snapshot, handle: owner.handle, ...waitOptions }));
|
|
1224
|
-
if (status.state === "ACTIVE" || (status.state !== "REAPED" && !everyUnsent())) throw new Error(`broker work may exist under this handle and its lease is ${status.state} (${status.why})`);
|
|
1225
|
-
if (status.state === "REAPED") proofs.push(`broker lease for ${owner.handle} is REAPED`);
|
|
1226
|
-
// GB-23: the answer's own member rows account for each recorded sub-handle too: a recorded one that the broker lists and does not list REAPED keeps ownership, whatever the aggregate said.
|
|
1227
|
-
if (Array.isArray(status.members)) for (const sub of handles) { const row = status.members.find((m) => m.handle === sub); if (row && row.state !== "REAPED") throw new Error(`the broker lists sub-handle ${sub} as ${row.state} among the members of ${owner.handle}`); }
|
|
1228
|
-
let neverStarted = 0; let revokedCount = 0;
|
|
1229
|
-
for (const sub of handles) {
|
|
1230
|
-
if (typeof sub !== "string" || !sub.startsWith(`${owner.handle}#`) || sub.length <= owner.handle.length + 1) throw new Error(`the record lists ${JSON.stringify(sub)}, which is not a sub-handle of ${owner.handle}`);
|
|
1231
|
-
const one = measure("leaseMs", () => lease({ snapshot: owner.snapshot, handle: sub, ...waitOptions }));
|
|
1232
|
-
const member = Array.isArray(one.members) ? one.members.find((m) => m.handle === sub) : null;
|
|
1233
|
-
if (one.state === "REAPED") {
|
|
1234
|
-
if (Array.isArray(one.members) && !(member && member.state === "REAPED")) throw new Error(`the broker answers REAPED for ${sub} but lists no completed submission under that name`);
|
|
1235
|
-
continue;
|
|
1236
|
-
}
|
|
1237
|
-
if (settled(sub) && one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0) { proofs.push(`${sub} never started (${unsent[sub].reason}) and the broker holds nothing under it`); neverStarted += 1; continue; }
|
|
1238
|
-
// The revocation settles only what the broker cannot answer: UNKNOWN, no member row for it here or in the owner's answer. ACTIVE or a listed member always holds.
|
|
1239
|
-
const listed = Array.isArray(status.members) && status.members.some((m) => m.handle === sub);
|
|
1240
|
-
const rev = one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0 && !listed ? revocation(sub) : null;
|
|
1241
|
-
if (rev) { proofs.push(`${sub} is UNKNOWN to the broker and revoked by its signed revocation ${rev.file} (proof ${rev.payload.proofSha256})`); revokedCount += 1; continue; }
|
|
1242
|
-
if ((brokerUpThroughout || brokerHoldsNothing) && one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0 && !listed) { neverReceived.add(sub); continue; }
|
|
1243
|
-
throw new Error(`broker work may exist under sub-handle ${sub} and its lease is ${one.state} (${one.why})`);
|
|
1244
|
-
}
|
|
1245
|
-
if (neverReceived.size) proofs.push(`${neverReceived.size} sub-handle(s) hold no broker work: UNKNOWN with no member row, ${brokerUpThroughout ? `to broker pid ${broker.pid}, up since ${new Date(broker.startedMs).toISOString()}, before this ownership (${owner.acquiredAt})` : `and the broker holds no work at all (READY, recovery complete, nothing in flight, no owner)`}, and no process of the run remains (${[...neverReceived].slice(0, 3).join(", ")}${neverReceived.size > 3 ? ", ..." : ""})`);
|
|
1246
|
-
if (handles.length) proofs.push(neverStarted === 0 && revokedCount === 0 && neverReceived.size === 0 ? `broker lease for each of ${handles.length} sub-handle(s) is REAPED` : `every one of ${handles.length} sub-handle(s) is accounted for: ${handles.length - neverStarted - revokedCount - neverReceived.size} REAPED, ${neverStarted} proven never started, ${neverReceived.size} never reached the broker, ${revokedCount} revoked by the broker`);
|
|
1247
|
-
}
|
|
1248
|
-
return proofs;
|
|
1249
|
-
}
|
|
1250
|
-
|
|
1251
|
-
/**
|
|
1252
|
-
* rightkit#1511 (rustright#228): the process half of a dead owner's reclaim, for RustRight's offline revocation helper to bind before it signs: the owner pid is
|
|
1253
|
-
* gone (or now runs another process) and every process check of a reclaim passes (detached groups, token holders, snapshot users, containment), with NO broker
|
|
1254
|
-
* lease judged and nothing written. Returns `{ schema, ownerFile, dataRoot, ownerSha256, ownerHandle, snapshot, host, proofs, provedAt }`; throws OwnershipBusy
|
|
1255
|
-
* naming what is still live or unknown. It never stands in for a reclaim: the reclaim still runs every check, the broker's included.
|
|
1256
|
-
*/
|
|
1257
|
-
/** Which RightKit code produced a process proof: this package's name and version and the SHA-256 of build-ownership.mjs itself. */
|
|
1258
|
-
function probeIdentity() {
|
|
1259
|
-
const here = new URL(import.meta.url);
|
|
1260
|
-
const pkg = JSON.parse(fs.readFileSync(new URL("./package.json", here), "utf8"));
|
|
1261
|
-
return { package: pkg.name, version: pkg.version, moduleSha256: crypto.createHash("sha256").update(fs.readFileSync(here)).digest("hex") };
|
|
1262
|
-
}
|
|
1263
|
-
export const OWNER_PROCESS_PROOF_SCHEMA = "rightkit.owner-process-proof/1";
|
|
1264
|
-
export function proveOwnerProcessesGone({ file, platform = process.platform, probe = processProbe({ platform }), host = os.hostname(), now = () => new Date() }) {
|
|
1265
|
-
const observed = readText(file);
|
|
1266
|
-
if (observed === null) throw new OwnershipBusy(`build ownership ${file}: no record`);
|
|
1267
|
-
const noLease = () => { throw new Error("a process-only proof asks the broker nothing"); };
|
|
1268
|
-
const { owner, proofs } = judgeOwner(observed, { file, probe, lease: noLease, host, processOnly: true });
|
|
1269
|
-
if (readText(file) !== observed) throw new OwnershipBusy(`build ownership ${file} changed while its processes were judged`);
|
|
1270
|
-
return {
|
|
1271
|
-
schema: OWNER_PROCESS_PROOF_SCHEMA, ownerFile: fs.realpathSync.native(file), dataRoot: fs.realpathSync.native(dataRootOf(file)),
|
|
1272
|
-
ownerSha256: crypto.createHash("sha256").update(Buffer.from(observed, "utf8")).digest("hex"), ownerHandle: owner.handle, snapshot: owner.snapshot ?? null,
|
|
1273
|
-
host, proofs, provedAt: now().toISOString(), probe: probeIdentity(),
|
|
1274
|
-
};
|
|
1275
|
-
}
|
|
1276
|
-
|
|
1277
|
-
/**
|
|
1278
|
-
* Whether the claimant a standing `.reclaim` body names is `"dead"` (proven), `"live"` or `"unknown"`. The body is the claimant's own owner record, so the same identity
|
|
1279
|
-
* rules as the record's judge apply: another host or an unreadable body is unknown; a reboot since the claimant started, a gone pid, or a pid that now runs a process that
|
|
1280
|
-
* started at another time is dead; the same process still alive is live.
|
|
1281
|
-
*/
|
|
1282
|
-
export function judgeClaimant(text, { probe, host }) {
|
|
1283
|
-
let rec = null; try { rec = JSON.parse(text ?? ""); } catch { rec = null; }
|
|
1284
|
-
if (rec?.schema !== OWNERSHIP_SCHEMA || typeof rec.handle !== "string" || !Number.isInteger(rec.pid) || rec.pid <= 0 || rec.pid > 0x7fffffff || !Number.isFinite(rec.startedMs)) return "unknown";
|
|
1285
|
-
if (rec.host !== host) return "unknown";
|
|
1286
|
-
try { const boot = probe.bootTime?.(); if (Number.isFinite(boot) && rec.startedMs < boot) return "dead"; } catch { /* the pid proof below decides */ }
|
|
1287
|
-
let now; try { now = probe.identity(rec.pid); } catch { return "unknown"; }
|
|
1288
|
-
if (!now.alive) return "dead";
|
|
1289
|
-
if (!Number.isFinite(now.startedMs)) return "unknown";
|
|
1290
|
-
return sameStart(now.startedMs, rec.startedMs) ? "live" : "dead";
|
|
1291
|
-
}
|
|
1292
|
-
|
|
1293
|
-
/**
|
|
1294
|
-
* Why the record `observed` may be reclaimed (`{ owner, proofs }`), or an OwnershipBusy throw naming what is still live or
|
|
1295
|
-
* unknown. Pure apart from the probes.
|
|
1296
|
-
*/
|
|
1297
|
-
export function judgeOwner(observed, { file, probe, lease, host = os.hostname(), pins = null, processOnly = false, broker = null }) {
|
|
1298
|
-
let owner = null;
|
|
1299
|
-
try { owner = JSON.parse(observed); } catch { owner = null; }
|
|
1300
|
-
const busy = (why, detail = {}) => new OwnershipBusy(`build ownership ${file}: ${why}`, { owner, ...detail });
|
|
1301
|
-
if (owner?.schema !== OWNERSHIP_SCHEMA || typeof owner.handle !== "string" || !Number.isInteger(owner.pid) || owner.pid <= 0 || owner.pid > 0x7fffffff || !Number.isFinite(Date.parse(owner.acquiredAt))) {
|
|
1302
|
-
throw busy("the record cannot be read as an owner record; remove it only when no build is running on this host");
|
|
1303
|
-
}
|
|
1304
|
-
if (owner.host !== host) throw busy(`held by pid ${owner.pid} on ${owner.host}`);
|
|
1305
|
-
let self;
|
|
1306
|
-
try { self = probe.identity(owner.pid); } catch (e) { throw busy(`owner pid ${owner.pid} cannot be proven gone (${e.message})`); }
|
|
1307
|
-
if (self.alive && (!Number.isFinite(owner.startedMs) || !Number.isFinite(self.startedMs) || sameStart(self.startedMs, owner.startedMs))) {
|
|
1308
|
-
throw busy(`held by pid ${owner.pid} (${owner.stage ?? "stage"} of ${owner.commit ?? "a commit"}) since ${owner.acquiredAt}`);
|
|
1309
|
-
}
|
|
1310
|
-
const proofs = [self.alive ? `owner pid ${owner.pid} now runs another process (started ${new Date(self.startedMs).toISOString()}, owner started ${new Date(owner.startedMs).toISOString()})` : `owner pid ${owner.pid} is gone`];
|
|
1311
|
-
// rightkit#1511: revocations are judged against the exact bytes judged here; the reclaim rereads both under its claim before it removes anything.
|
|
1312
|
-
const revocations = [];
|
|
1313
|
-
const revoked = pins ? (sub) => {
|
|
1314
|
-
const dataRoot = fs.realpathSync.native(dataRootOf(file));
|
|
1315
|
-
const at = revocationFile(dataRoot, owner.handle, sub, owner.snapshot);
|
|
1316
|
-
const bytes = readRevocation(at);
|
|
1317
|
-
if (bytes === null || !isRevocationEnvelope(bytes)) return null;
|
|
1318
|
-
const payload = verifyRevocation(bytes, pins, { ownerFile: fs.realpathSync.native(file), dataRoot, ownerBytes: Buffer.from(observed, "utf8"), owner, sub });
|
|
1319
|
-
revocations.push({ file: at, bytes });
|
|
1320
|
-
return { file: at, payload };
|
|
1321
|
-
} : null;
|
|
1322
|
-
try { proofs.push(...coveredWorkGone(owner, { probe, lease, file, revoked, processOnly, broker })); } catch (e) { throw busy(`owner pid ${owner.pid} is gone but ${e.message}`); }
|
|
1323
|
-
return { owner, proofs, revocations };
|
|
1324
|
-
}
|
|
1325
|
-
|
|
1326
|
-
/**
|
|
1327
|
-
* Acquires a repository's build ownership (or joins it, when RIGHTKIT_BUILD_OWNERSHIP names the current record). Returns
|
|
1328
|
-
* `{ handle, file, joined, reclaimed, owner, markBrokerSubmit(callHandle), held(), release() }`. Throws OwnershipBusy while another build
|
|
1329
|
-
* owns this repository, its liveness is unknown, or this gate cannot be contained.
|
|
1330
|
-
*/
|
|
1331
|
-
export function acquireBuildOwnership({
|
|
1332
|
-
file,
|
|
1333
|
-
stage,
|
|
1334
|
-
snapshot,
|
|
1335
|
-
commit,
|
|
1336
|
-
platform = process.platform,
|
|
1337
|
-
env = process.env,
|
|
1338
|
-
probe = processProbe({ platform }),
|
|
1339
|
-
lease = (q) => brokerLeaseState({ ...q, env, platform }),
|
|
1340
|
-
exportEnv = true,
|
|
1341
|
-
hooks = {},
|
|
1342
|
-
managedRoot,
|
|
1343
|
-
device,
|
|
1344
|
-
brokerPins,
|
|
1345
|
-
brokerIdentity,
|
|
1346
|
-
} = {}) {
|
|
1347
|
-
// First, before the environment, the record or any write: the managed root exists (decision D4). `managedRoot` and `device` are
|
|
1348
|
-
// fixtures' seams; a production caller passes neither.
|
|
1349
|
-
if (typeof file !== "string" || file === "") throw new TypeError("acquireBuildOwnership: file is required (the path ownershipFile returns for a repository key)");
|
|
1350
|
-
guardManagedRoot(file, { platform, managedRoot, device });
|
|
1351
|
-
ensureOwnershipDir(path.dirname(file), { platform });
|
|
1352
|
-
const inherited = env[OWNERSHIP_ENV];
|
|
1353
|
-
// An older pinned gate on this host writes ONE host-wide record, `build-ownership/owner.json`, a plain file beside the repository
|
|
1354
|
-
// directories. It holds every repository: this code never joins it, reclaims it or deletes it.
|
|
1355
|
-
const olderFile = path.join(path.dirname(path.dirname(file)), "owner.json");
|
|
1356
|
-
let older = null;
|
|
1357
|
-
try { older = readText(olderFile); } catch (e) { throw new OwnershipBusy(`build ownership ${olderFile}: an older gate's host-wide record cannot be read (${e.code ?? e.message}); nothing runs while it may stand`); }
|
|
1358
|
-
if (older !== null && inherited) {
|
|
1359
|
-
let o = null; try { o = JSON.parse(older); } catch { o = null; }
|
|
1360
|
-
if (o?.handle === inherited) throw new OwnershipBusy(`build ownership ${olderFile}: ${OWNERSHIP_ENV}=${inherited} names the host-wide record of an older gate; the parent is an older gate, and a nested gate never joins it`);
|
|
1361
|
-
}
|
|
1362
|
-
if (inherited) {
|
|
1363
|
-
const current = readText(file);
|
|
1364
|
-
let owner = null; try { owner = JSON.parse(current ?? ""); } catch { owner = null; }
|
|
1365
|
-
if (owner?.handle === inherited) {
|
|
1366
|
-
// A nested gate joins the LIVE owner's record (row 5.20): the exact handle of a well-formed record of this host whose owner is
|
|
1367
|
-
// still running as the process that wrote it. A handle left in the environment of a survivor of a dead owner names a record
|
|
1368
|
-
// nobody holds any more; joining it would run a build under an ownership no live gate answers for.
|
|
1369
|
-
if (owner.schema !== OWNERSHIP_SCHEMA || !Number.isInteger(owner.pid) || owner.pid <= 0 || owner.host !== os.hostname()) {
|
|
1370
|
-
throw new OwnershipBusy(`build ownership ${file}: ${OWNERSHIP_ENV}=${inherited} names a record that is not a well-formed owner record of this host; a nested gate joins only a live owner's record`);
|
|
1371
|
-
}
|
|
1372
|
-
let live;
|
|
1373
|
-
try { live = probe.identity(owner.pid); } catch (e) { throw new OwnershipBusy(`build ownership ${file}: owner pid ${owner.pid} cannot be proven alive (${e.message}), so a nested gate cannot join it`); }
|
|
1374
|
-
if (!live.alive || (Number.isFinite(owner.startedMs) && Number.isFinite(live.startedMs) && !sameStart(live.startedMs, owner.startedMs))) {
|
|
1375
|
-
throw new OwnershipBusy(`build ownership ${file}: ${OWNERSHIP_ENV}=${inherited} names a record whose owner pid ${owner.pid} is no longer the process that took it; a nested gate joins only a live owner's record`);
|
|
1376
|
-
}
|
|
1377
|
-
return { handle: inherited, file, joined: true, reclaimed: null, owner, markBrokerSubmit: (callHandle, note) => markBrokerSubmit(file, inherited, callHandle, { note }), markBrokerUnsent: (callHandle, reason) => markBrokerUnsent(file, inherited, callHandle, reason), held: () => holds(file, inherited), release: () => ({ released: false, joined: true }) };
|
|
1378
|
-
}
|
|
1379
|
-
throw new OwnershipBusy(`build ownership ${file}: ${OWNERSHIP_ENV}=${inherited} is not the current owner; a nested gate never takes ownership of its own`);
|
|
1380
|
-
}
|
|
1381
|
-
if (older !== null) {
|
|
1382
|
-
// Judged exactly as the older code judged it, to word the refusal; never reclaimed from here, whatever the verdict.
|
|
1383
|
-
try { judgeOwner(older, { file: olderFile, probe, lease }); }
|
|
1384
|
-
catch (e) { if (!(e instanceof OwnershipBusy)) throw e; throw new OwnershipBusy(`${e.message}; this is an older gate's host-wide record and it holds every repository: let that gate finish or clear it (an older gate or a person), this gate does not`, e.detail ?? {}); }
|
|
1385
|
-
throw new OwnershipBusy(`build ownership ${olderFile}: an older gate's host-wide record stands (its owner is gone, but only an older gate or a person clears it; this gate never reclaims it), and it holds every repository; nothing ran`);
|
|
1386
|
-
}
|
|
1387
|
-
let me;
|
|
1388
|
-
try { me = probe.identity(process.pid); } catch (e) { throw new OwnershipBusy(`build ownership ${file}: this gate's own start identity cannot be read (${e.message})`); }
|
|
1389
|
-
if (!me.alive || !Number.isFinite(me.startedMs)) throw new OwnershipBusy(`build ownership ${file}: this gate's own start identity cannot be read`);
|
|
1390
|
-
if (platform !== "win32" && !(Number.isInteger(me.group) && me.group > 1)) throw new OwnershipBusy(`build ownership ${file}: this gate's process group cannot be read`);
|
|
1391
|
-
// The gate's ancestors, so a later gate can tell a peer of the owner (the shell it ran under) from an orphan a subreaper adopted.
|
|
1392
|
-
let ancestors = null;
|
|
1393
|
-
try { ancestors = probe.ancestors?.() ?? null; } catch { ancestors = null; }
|
|
1394
|
-
const handle = crypto.randomUUID();
|
|
1395
|
-
const record = {
|
|
1396
|
-
schema: OWNERSHIP_SCHEMA,
|
|
1397
|
-
handle,
|
|
1398
|
-
host: os.hostname(),
|
|
1399
|
-
platform,
|
|
1400
|
-
pid: process.pid,
|
|
1401
|
-
startedMs: me.startedMs,
|
|
1402
|
-
ancestors,
|
|
1403
|
-
containment: platform === "win32" ? { kind: "job", name: jobName(handle) } : { kind: "group", group: me.group },
|
|
1404
|
-
stage: stage ?? null,
|
|
1405
|
-
snapshot: snapshot ?? null,
|
|
1406
|
-
commit: commit ?? null,
|
|
1407
|
-
acquiredAt: new Date().toISOString(),
|
|
1408
|
-
// Set only for an acquisition on a free host after a release that proved zero readers (a reclaim never has it).
|
|
1409
|
-
cleanBefore: readCleanMarker(file),
|
|
1410
|
-
// True when this ownership was published on a free host (no owner record anywhere); a reclaim sets it false.
|
|
1411
|
-
freeHost: true,
|
|
1412
|
-
broker: { submitted: false },
|
|
1413
|
-
};
|
|
1414
|
-
const body = JSON.stringify(record);
|
|
1415
|
-
const release = () => {
|
|
1416
|
-
const timingKey = Symbol.for("rightkit.releaseTiming");
|
|
1417
|
-
const timing = process[timingKey] ?? null;
|
|
1418
|
-
const start = performance.now();
|
|
1419
|
-
if (timing) timing.releaseStartEpochMs = performance.timeOrigin + start;
|
|
1420
|
-
try {
|
|
1421
|
-
if (!holds(file, handle)) return { released: false, why: "no longer the owner" };
|
|
1422
|
-
let proofs;
|
|
1423
|
-
// The record as it is now (a broker submit may have been marked since it was written).
|
|
1424
|
-
try { proofs = coveredWorkGone(JSON.parse(readText(file)), { probe, lease, file, selfPid: process.pid, waitMs: RELEASE_LEASE_WAIT_MS, timing }); }
|
|
1425
|
-
catch (e) { return { released: false, why: `left for the next gate to reclaim: ${e.message}` }; }
|
|
1426
|
-
finally { if (exportEnv && process.env[OWNERSHIP_ENV] === handle) { delete process.env[OWNERSHIP_ENV]; delete process.env[OWNERSHIP_FILE_ENV]; } }
|
|
1427
|
-
// Only a release that proved zero readers leaves the marker; a held one leaves none (and keeps the record).
|
|
1428
|
-
writeCleanMarker(file, record);
|
|
1429
|
-
fs.rmSync(file, { force: true });
|
|
1430
|
-
fs.rmSync(markLockFile(file), { force: true });
|
|
1431
|
-
fs.rmSync(childrenDir(file, handle), { recursive: true, force: true });
|
|
1432
|
-
return { released: true, proofs };
|
|
1433
|
-
} finally {
|
|
1434
|
-
if (timing) {
|
|
1435
|
-
timing.releaseMs = performance.now() - start;
|
|
1436
|
-
timing.releaseEndEpochMs = performance.timeOrigin + performance.now();
|
|
1437
|
-
delete process[timingKey];
|
|
1438
|
-
try { process.stderr.write(`rightkit-release-timing ${JSON.stringify(timing)}\n`); } catch { /* diagnostics must not affect release */ }
|
|
1439
|
-
}
|
|
1440
|
-
}
|
|
1441
|
-
};
|
|
1442
|
-
const done = (reclaimed) => {
|
|
1443
|
-
// Windows: the gate enters its job before it returns, so every child it starts from here on is contained.
|
|
1444
|
-
if (platform === "win32") {
|
|
1445
|
-
let held;
|
|
1446
|
-
try { held = probe.contain({ name: record.containment.name, pid: process.pid, file: holderFile(file, handle) }); }
|
|
1447
|
-
catch (e) { if (holds(file, handle)) fs.rmSync(file, { force: true }); throw new OwnershipBusy(`build ownership ${file}: ${e.message}`); }
|
|
1448
|
-
// A gate the self-check did not find in its job would start work nothing can later prove gone, whether it exits or crashes.
|
|
1449
|
-
// No work has started yet (the self-check child has exited), so it refuses now and leaves no record, instead of running and
|
|
1450
|
-
// leaving the host held until a reboot.
|
|
1451
|
-
if (held?.contained !== true) {
|
|
1452
|
-
if (holds(file, handle)) fs.rmSync(file, { force: true });
|
|
1453
|
-
throw new OwnershipBusy(`build ownership ${file}: this gate's children would not stay in job ${record.containment.name} (its launcher lets children leave their job silently, e.g. a Node parent's job), so their exit could never be proven; start the gate from a shell or PowerShell, not under such a launcher`);
|
|
1454
|
-
}
|
|
1455
|
-
record.containment = { ...record.containment, contained: true };
|
|
1456
|
-
// Fail closed: a record this gate published but cannot finish is removed, never left held by a gate that is not running.
|
|
1457
|
-
try { rewriteRecord(file, handle, (r) => ({ ...r, containment: record.containment })); }
|
|
1458
|
-
catch (e) { if (holds(file, handle)) fs.rmSync(file, { force: true }); throw new OwnershipBusy(`build ownership ${file}: the containment could not be recorded (${e.code ?? e.message}: ${e.message})`); }
|
|
1459
|
-
}
|
|
1460
|
-
if (exportEnv) { process.env[OWNERSHIP_ENV] = handle; process.env[OWNERSHIP_FILE_ENV] = file; }
|
|
1461
|
-
return { handle, file, joined: false, reclaimed, owner: record, contained: platform === "win32" ? record.containment.contained === true : true, markBrokerSubmit: (callHandle, note) => markBrokerSubmit(file, handle, callHandle, { note }), markBrokerUnsent: (callHandle, reason) => markBrokerUnsent(file, handle, callHandle, reason), held: () => holds(file, handle), release };
|
|
1462
|
-
};
|
|
1463
|
-
if (publish(file, body)) return done(null);
|
|
1464
|
-
const observed = readText(file);
|
|
1465
|
-
if (observed === null) { if (publish(file, body)) return done(null); throw new OwnershipBusy(`build ownership ${file} was taken by another process`); }
|
|
1466
|
-
// GC-A25 is proposed, not operative: RustRight has not frozen the revocation's authoritative path (its f227 completion key fences legacy reuse; a record
|
|
1467
|
-
// only beside this one does not) nor its publication sequence. Until then no production reclaim honours a revocation; only a caller that passes
|
|
1468
|
-
// `brokerPins` explicitly (fixtures) exercises the branch. Enable by defaulting to enrolledPinsFor(file, platform) once GC-A25 is operative.
|
|
1469
|
-
const judged = judgeOwner(observed, { file, probe, lease, pins: brokerPins ?? null, broker: brokerIdentity === undefined ? { ...(runningBrokerProcess({ platform }) ?? {}), idle: brokerIdle({ platform }) } : brokerIdentity });
|
|
1470
|
-
hooks.afterJudge?.();
|
|
1471
|
-
// A reclaim means the previous release was not clean (a crash, or a release that ended held): nothing unreadable is skipped.
|
|
1472
|
-
record.cleanBefore = null;
|
|
1473
|
-
record.freeHost = false;
|
|
1474
|
-
const reclaimBody = JSON.stringify(record);
|
|
1475
|
-
const reclaim = `${file}.reclaim`;
|
|
1476
|
-
// GB-56: a `.reclaim` already there is judged by the identity its body carries (the claimant's owner record: pid, start, host, boot), never taken for a live claimant on its
|
|
1477
|
-
// existence alone. A claimant PROVEN dead (its pid is gone, the pid now runs a process that started at another time, or the host rebooted since) is removed, compare-by-content,
|
|
1478
|
-
// and the claim retried once; a live, unreadable or unprovable claimant keeps the lock. Bounded: one retry, so two reclaimers never loop.
|
|
1479
|
-
if (!publish(reclaim, reclaimBody)) {
|
|
1480
|
-
const standing = readText(reclaim);
|
|
1481
|
-
const verdict = judgeClaimant(standing, { probe, host: os.hostname() });
|
|
1482
|
-
if (verdict === "dead" && readText(reclaim) === standing) { fs.rmSync(reclaim, { force: true }); }
|
|
1483
|
-
if (verdict !== "dead" || !publish(reclaim, reclaimBody)) throw new OwnershipBusy(`build ownership ${file} is being reclaimed by another process (${verdict === "dead" ? "its claim was dropped but another gate took it first" : verdict === "live" ? "a live gate holds the reclaim claim" : "the reclaim claim cannot be proven dead"}: remove ${reclaim} only if no gate is running)`);
|
|
1484
|
-
}
|
|
1485
|
-
try {
|
|
1486
|
-
hooks.afterClaim?.(reclaim);
|
|
1487
|
-
// rightkit#1511: the reread, the removal and the new record run under the record's mark lock too, so no submit or unsent mark of the old owner can land
|
|
1488
|
-
// between the reread and the removal (a mark after it finds another handle and refuses). The lock is released by withMarkLock, not removed here.
|
|
1489
|
-
// A mark lock that cannot be read was left by a crash (it is only ever published whole). The owner and every process under it are proven gone and this
|
|
1490
|
-
// reclaim holds the claim, so no marker of this record can exist: that exact debris is removed, compare-by-content, instead of blocking every later gate.
|
|
1491
|
-
const debris = readText(markLockFile(file));
|
|
1492
|
-
if (debris !== null && !isMarkLockText(debris) && readText(markLockFile(file)) === debris) fs.rmSync(markLockFile(file), { force: true });
|
|
1493
|
-
withMarkLock(file, () => {
|
|
1494
|
-
if (readText(file) !== observed) throw new OwnershipBusy(`build ownership ${file} changed before it could be reclaimed`);
|
|
1495
|
-
for (const r of judged.revocations) { let now = null; try { now = readRevocation(r.file); } catch { now = null; } if (!now || !now.equals(r.bytes)) throw new OwnershipBusy(`build ownership ${file}: the broker revocation ${r.file} changed before the record could be reclaimed`); }
|
|
1496
|
-
fs.rmSync(file, { force: true });
|
|
1497
|
-
fs.rmSync(holderFile(file, judged.owner.handle), { force: true });
|
|
1498
|
-
fs.rmSync(holderScriptFile(holderFile(file, judged.owner.handle)), { force: true });
|
|
1499
|
-
fs.rmSync(childrenDir(file, judged.owner.handle), { recursive: true, force: true });
|
|
1500
|
-
if (!publish(file, reclaimBody)) throw new OwnershipBusy(`build ownership ${file} was taken by another process`);
|
|
1501
|
-
});
|
|
1502
|
-
} finally {
|
|
1503
|
-
// Token-checked: only this reclaim's own claim is removed (a successor's claim, published after this one was judged dead, stays).
|
|
1504
|
-
if (readText(reclaim) === reclaimBody) fs.rmSync(reclaim, { force: true });
|
|
1505
|
-
}
|
|
1506
|
-
return done({ from: judged.owner.handle, pid: judged.owner.pid, proofs: judged.proofs });
|
|
1507
|
-
}
|
|
1508
|
-
|
|
1509
|
-
/**
|
|
1510
|
-
* rightkit#1511: the host's ENROLLED broker pin (`<managed root>/pins/broker-<platform>.json`; the record is `<managed root>/build-ownership/<key>/owner.json`),
|
|
1511
|
-
* or null when none is enrolled or it cannot be read: then no revocation is honoured and the reclaim proofs stand as before. Never the checkout fallback.
|
|
1512
|
-
*/
|
|
1513
|
-
function enrolledPinsFor(file, platform) {
|
|
1514
|
-
try { return readEnrolledPins({ dataRoot: dataRootOf(file), platform }); } catch { return null; }
|
|
1515
|
-
}
|
|
1516
|
-
|
|
1517
|
-
/** The managed data root a record `<root>/build-ownership/<key>/owner.json` lives under. */
|
|
1518
|
-
const dataRootOf = (file) => path.dirname(path.dirname(path.dirname(file)));
|
|
1519
|
-
|
|
1520
|
-
/**
|
|
1521
|
-
* rightkit#1513: the running RustRight broker's pid and start time (epoch ms), from launchd and ps (macOS); null when it cannot be
|
|
1522
|
-
* established. A broker that has run continuously since before an ownership was acquired saw every request of that run.
|
|
1523
|
-
*/
|
|
1524
|
-
/**
|
|
1525
|
-
* rightkit#1513 (Adrian: "It should ideally auto recover"): the broker's own answer that it holds no work at all: phase READY, its restart
|
|
1526
|
-
* recovery complete, nothing in flight, no build owner and no quiet lease (`rustright list`). With that answer a sub-handle the broker calls
|
|
1527
|
-
* UNKNOWN with no member row has no work anywhere, even when the broker restarted after the ownership was acquired. Any other answer is null.
|
|
1528
|
-
*/
|
|
1529
|
-
export function brokerIdle({ env = process.env, platform = process.platform, spawn = spawnSync, client = managedRuntimeClient(env, platform) } = {}) {
|
|
1530
|
-
if (!client) return null;
|
|
1531
|
-
try {
|
|
1532
|
-
const r = run(spawn, client, ["list"], env);
|
|
1533
|
-
if (r.error || r.status !== 0) return null;
|
|
1534
|
-
const d = JSON.parse(String(r.stdout ?? "").trim());
|
|
1535
|
-
const b = d?.broker;
|
|
1536
|
-
const idle = b?.phase === "READY" && b?.recovery?.complete === true && b?.quietLease === null && Array.isArray(d?.inFlight) && d.inFlight.length === 0 && Array.isArray(d?.owners) && d.owners.length === 0;
|
|
1537
|
-
return idle ? { phase: b.phase, recovered: b.recovery?.recovered ?? null } : null;
|
|
1538
|
-
} catch { return null; }
|
|
1539
|
-
}
|
|
1540
|
-
|
|
1541
|
-
export function runningBrokerProcess({ platform = process.platform, run = spawnSync, uid = process.getuid?.() } = {}) {
|
|
1542
|
-
if (platform === "win32") {
|
|
1543
|
-
// The Dell's broker runs as rustright-broker.exe (D:\.rustright\runtime). Exactly one such process, else unknown (fail safe).
|
|
1544
|
-
try {
|
|
1545
|
-
const script = "$p = @(Get-Process -Name rustright-broker -ErrorAction SilentlyContinue); if ($p.Count -eq 1) { \"$($p[0].Id) $($p[0].StartTime.ToUniversalTime().ToString('o'))\" }";
|
|
1546
|
-
const r = run("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8", timeout: 15000, windowsHide: true });
|
|
1547
|
-
const m = /^(\d+) (\S+)\s*$/m.exec(String(r.stdout ?? ""));
|
|
1548
|
-
if (!m) return null;
|
|
1549
|
-
const pid = Number(m[1]); const startedMs = Date.parse(m[2]);
|
|
1550
|
-
return Number.isInteger(pid) && pid > 0 && Number.isFinite(startedMs) ? { pid, startedMs } : null;
|
|
1551
|
-
} catch { return null; }
|
|
1552
|
-
}
|
|
1553
|
-
if (platform !== "darwin") return null;
|
|
1554
|
-
try {
|
|
1555
|
-
// The broker alternates between two launchd entries at each cutover (rustright-install entries.rs: `dev.rustright.broker` and
|
|
1556
|
-
// `dev.rustright.broker.b`). Exactly one of them running is the broker; none or both (mid-cutover) is unknown (fail safe).
|
|
1557
|
-
const pids = ["dev.rustright.broker", "dev.rustright.broker.b"]
|
|
1558
|
-
.map((label) => Number(/^\s*pid = (\d+)$/m.exec(String(run("launchctl", ["print", `gui/${uid}/${label}`], { encoding: "utf8", timeout: 5000 }).stdout ?? ""))?.[1]))
|
|
1559
|
-
.filter((pid) => Number.isInteger(pid) && pid > 0);
|
|
1560
|
-
if (pids.length !== 1) return null;
|
|
1561
|
-
const pid = pids[0];
|
|
1562
|
-
const ps = run("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5000, env: { ...process.env, LC_ALL: "C", LANG: "C" } });
|
|
1563
|
-
const startedMs = Date.parse(String(ps.stdout ?? "").trim());
|
|
1564
|
-
return Number.isFinite(startedMs) ? { pid, startedMs } : null;
|
|
1565
|
-
} catch { return null; }
|
|
1566
|
-
}
|
|
1567
|
-
|
|
1568
|
-
/** Replaces the record atomically while it is still `handle`'s. */
|
|
1569
|
-
function rewriteRecord(file, handle, change) {
|
|
1570
|
-
const text = readText(file);
|
|
1571
|
-
let owner = null; try { owner = JSON.parse(text ?? ""); } catch { owner = null; }
|
|
1572
|
-
if (owner?.handle !== handle) throw new OwnershipBusy(`build ownership ${file} is no longer held by ${handle}`);
|
|
1573
|
-
const tmp = `${file}.${crypto.randomUUID()}.tmp`;
|
|
1574
|
-
fs.writeFileSync(tmp, JSON.stringify(change(owner)), { flag: "wx", mode: 0o600 });
|
|
1575
|
-
try { fs.renameSync(tmp, file); } finally { fs.rmSync(tmp, { force: true }); }
|
|
1576
|
-
}
|
|
1577
|
-
|
|
1578
|
-
|