Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): bootstrap_serve_lock skips only the doctor's own PGLite lock (#5481, #5561)

garrytan05158768a729
diff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.ts
index e36d3f4049..52583bdae6 100644
--- a/src/commands/doctor/bootstrap-checks.ts
+++ b/src/commands/doctor/bootstrap-checks.ts
@@ -437,7 +437,7 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise
try {
const dataDir = resolveBrainDataDir(home);
const holder = probeLivePgliteHolder(dataDir);
- if (holder) {
+ if (holder && !holder.isSelf) {
checks.push({
name: 'bootstrap_serve_lock',
status: holder.serve ? 'ok' : 'warn',
diff --git a/src/core/bootstrap/uninstall.ts b/src/core/bootstrap/uninstall.ts
index 29d8095748..41ecacfd37 100644
--- a/src/core/bootstrap/uninstall.ts
+++ b/src/core/bootstrap/uninstall.ts
@@ -35,11 +35,24 @@ import { existsSync, lstatSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { configDir } from '../config.ts';
import { isPathContained, realpathOrResolve } from '../path-confine.ts';
-import { isProcessAlive } from '../pglite-lock.ts';
+import { isProcessAlive, readBootId, readPidNs } from '../pglite-lock.ts';
import { readReceipt, receiptPath, type InstallReceipt } from './format.ts';
import { BootstrapError } from './lock.ts';
import type { ExecRunner } from './repo.ts';
+// (#5481 review F1) Captured ONCE at module load — this module is a static
+// top-level import of the doctor CLI's own import graph, so load time tracks
+// real process start closely. A per-call `Date.now() - process.uptime() *
+// 1000` recompute instead drifts if the wall clock is adjusted (NTP
+// correction, VM/container pause-resume) at any point between real process
+// start and whenever a later check actually runs `probeLivePgliteHolder` —
+// pushing the estimate later than the true start and false-flagging a
+// genuinely-self lock as a foreign collision, the exact bug this file exists
+// to fix. Anchoring the estimate at load time instead of check time closes
+// that window: uptime() is already near-zero at load, so the subtraction
+// barely matters, and no later clock jump can retroactively move it.
+const MODULE_LOAD_PROCESS_START_ESTIMATE = Date.now() - process.uptime() * 1000;
+
// ---------------------------------------------------------------------------
// Read-only PGLite lock probe (never opens the engine)
// ---------------------------------------------------------------------------
@@ -48,6 +61,48 @@ export interface LiveHolder {
pid: number;
/** True when the lock file says the holder is `gbrain serve`. */
serve: boolean;
+ /**
+ * True when `pid` matches THIS process AND the lock's namespace evidence
+ * (`pid_ns`/`boot_id`) also matches THIS process's own (#5481). A bare
+ * numeric pid match is not proof of self-identity: containers/hosts
+ * sharing a mounted PGLite directory can reuse the same namespace-local
+ * pid for a genuinely different process, so pid alone would let a foreign
+ * holder masquerade as self. Mirrors the cross-namespace-incomparable
+ * guard `pglite-lock.ts` already applies at lock-acquisition time. Every
+ * lock this codebase writes stamps both fields (`pglite-lock.ts`), so a
+ * genuine self-lock always has matching evidence when THIS process can
+ * itself read `/proc`. On Linux, self requires POSITIVE VERIFIED
+ * agreement on BOTH markers — each of `pid_ns`/`boot_id` must be non-null
+ * on both the stored lock AND our own current reading, and equal — never
+ * an absence-based free pass. This mirrors `pglite-lock.ts`'s own
+ * lock-acquisition comparability guard exactly (it likewise requires
+ * non-null matching before treating evidence as usable, never accepting
+ * "both sides unreadable" as agreement), so a restricted-`/proc`
+ * environment (where our own markers, or the lock's stored ones, are
+ * unreadable) can NEVER verify self and fails CLOSED (still warns) rather
+ * than risk misclassifying a foreign holder under the same restriction as
+ * self. This means a doctor process whose own `/proc` markers are
+ * unreadable will still see the original #5481 false-positive warning
+ * about its own lock in that narrow case; only environments where
+ * namespace evidence is actually readable get the improved
+ * self-detection. This is a narrower guarantee than a fully verified
+ * cross-host identity check on non-Linux platforms specifically (a
+ * foreign holder reusing this process's pid on a non-Linux host — where
+ * no namespace evidence exists at all — would still read as self);
+ * closing that residual gap would need new cross-platform identity
+ * infrastructure this codebase does not have anywhere, including at
+ * `pglite-lock.ts`'s own lock-acquisition path, and is out of scope for
+ * the doctor false-positive this field fixes. A pid/namespace match ALONE
+ * is also not sufficient: within one boot session a dead process's pid
+ * can be reused by a later, unrelated live process (including this
+ * doctor invocation itself), leaving a genuinely stale legacy lock that
+ * still blocks real database access — `pglite-lock.ts`'s own acquisition
+ * reap logic sees the recycled pid as alive and correctly refuses to
+ * reclaim it. `isSelf` additionally requires the lock's `acquired_at`
+ * (when present) not to predate this process's own start time, since a
+ * process cannot have acquired a lock before it existed.
+ */
+ isSelf: boolean;
}
/**
@@ -56,10 +111,30 @@ export interface LiveHolder {
* fallback; only an affirmatively-dead PID reads as dead) without acquiring,
* reaping, or opening anything. Unreadable/absent lock → null (no live holder
* provable — uninstall proceeds; a dead holder's stale lock dir is inert).
+ *
+ * `deps` is test-only injection for the namespace-evidence readers and our
+ * own process-start time (default: the real `/proc` readers from
+ * pglite-lock.ts and this module's load-time-anchored estimate, captured
+ * once above rather than recomputed per call); production callers never
+ * pass it.
*/
-export function probeLivePgliteHolder(dataDir: string): LiveHolder | null {
+export function probeLivePgliteHolder(
+ dataDir: string,
+ deps: {
+ readPidNs: () => string | null;
+ readBootId: () => string | null;
+ processStartTime?: () => number;
+ } = { readPidNs, readBootId },
+): LiveHolder | null {
const lockPath = join(dataDir, '.gbrain-lock', 'lock');
- let raw: { pid?: unknown; subcommand?: unknown; command?: unknown };
+ let raw: {
+ pid?: unknown;
+ subcommand?: unknown;
+ command?: unknown;
+ pid_ns?: unknown;
+ boot_id?: unknown;
+ acquired_at?: unknown;
+ };
try {
raw = JSON.parse(readFileSync(lockPath, 'utf8')) as typeof raw;
} catch {
@@ -74,7 +149,55 @@ export function probeLivePgliteHolder(dataDir: string): LiveHolder | null {
const parts = raw.command.trim().split(/\s+/);
serve = parts[0] === 'serve' || parts[1] === 'serve';
}
- return { pid, serve };
+ const lockPidNs = typeof raw.pid_ns === 'string' ? raw.pid_ns : null;
+ const lockBootId = typeof raw.boot_id === 'string' ? raw.boot_id : null;
+ const ourPidNs = deps.readPidNs();
+ const ourBootId = deps.readBootId();
+ // (#5481 review F2/F3/F4/F5) On Linux, self requires POSITIVE VERIFIED
+ // evidence on BOTH markers — each of pid_ns and boot_id must be non-null
+ // on both the stored lock AND our own current reading, and equal. This
+ // mirrors pglite-lock.ts's own lock-acquisition comparability guard
+ // exactly (it likewise requires non-null matching before treating
+ // evidence as usable — see its `comparable` check), rather than an
+ // earlier, looser design here that also accepted "both sides unreadable"
+ // as agreement. That fallback was reverted: it could not distinguish a
+ // restricted-`/proc` SELF lock from a restricted-`/proc` FOREIGN lock (a
+ // different container/host whose own `/proc` is equally masked), so it
+ // failed OPEN exactly where verification is impossible. The doctor now
+ // fails CLOSED in that case — it keeps warning, matching this file's
+ // pre-#5481 behavior, rather than risk silently suppressing a real
+ // collision it cannot actually verify. (This means a doctor process
+ // running with its own `/proc` markers unreadable will still see the
+ // original false-positive warning about its own lock; only environments
+ // where namespace evidence is readable get the improved self-detection.)
+ const verifiedMatch = ourPidNs != null && lockPidNs != null && ourPidNs === lockPidNs
+ && ourBootId != null && lockBootId != null && ourBootId === lockBootId;
+ const namespaceMatches = process.platform !== 'linux' || verifiedMatch;
+ // (#5481 review F6) A pid+namespace match alone is not proof this process
+ // itself acquired the lock: within one boot session a dead process's pid
+ // can be reused by a LATER, unrelated process (including doctor itself).
+ // A genuinely stale legacy lock left behind by the dead process can then
+ // block real database access — pglite-lock.ts's own acquisition-time
+ // legacy-migration reap logic sees `isProcessAlive(pid)` true (because
+ // the recycled pid now belongs to a live process) and correctly refuses
+ // to reap it, so the stale lock keeps blocking connections even though
+ // "self" never actually held it. We cannot ask pglite-lock.ts for its
+ // live in-process handle (this probe is read-only and never acquires
+ // anything), but every lock write stamps `acquired_at`, and a process
+ // cannot have acquired a lock before it existed: if the lock's
+ // `acquired_at` predates OUR OWN process start time, it is provably not
+ // ours, regardless of matching pid/namespace evidence, and this stays a
+ // reportable collision. A missing/unparseable `acquired_at` (a lock
+ // written by older code) is not treated as disqualifying — only a
+ // POSITIVE, verifiable "written before we existed" timestamp overrides a
+ // pid/namespace match.
+ const lockAcquiredAt = typeof raw.acquired_at === 'number' ? raw.acquired_at : null;
+ const ourProcessStartTime = deps.processStartTime?.() ?? MODULE_LOAD_PROCESS_START_ESTIMATE;
+ const ACQUIRED_AT_TOLERANCE_MS = 1000;
+ const acquiredBeforeThisProcessStarted = lockAcquiredAt != null
+ && lockAcquiredAt < ourProcessStartTime - ACQUIRED_AT_TOLERANCE_MS;
+ const isSelf = pid === process.pid && namespaceMatches && !acquiredBeforeThisProcessStarted;
+ return { pid, serve, isSelf };
}
/** The PGLite data dir for a gbrain home: config.json's database_path when it
diff --git a/src/core/pglite-lock.ts b/src/core/pglite-lock.ts
index cc20f49267..d0048ce7a6 100644
--- a/src/core/pglite-lock.ts
+++ b/src/core/pglite-lock.ts
@@ -60,10 +60,10 @@ function isServeCommand(metadata: LockMetadata): boolean {
function readMetadata(lockDir: string): LockMetadata | null {
try { return JSON.parse(readFileSync(join(lockDir, LOCK_FILE), 'utf8')); } catch { return null; }
}
-function readPidNs(): string | null {
+export function readPidNs(): string | null {
try { return readlinkSync('/proc/self/ns/pid'); } catch { return null; }
}
-function readBootId(): string | null {
+export function readBootId(): string | null {
try { return readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim() || null; } catch { return null; }
}
diff --git a/test/bootstrap-doctor-checks.test.ts b/test/bootstrap-doctor-checks.test.ts
index b4cd6cc3cb..9d2fc51b71 100644
--- a/test/bootstrap-doctor-checks.test.ts
+++ b/test/bootstrap-doctor-checks.test.ts
@@ -20,6 +20,7 @@ import { join } from 'node:path';
import { execFileSync, spawnSync } from 'node:child_process';
import { bootstrapDoctorChecks, type Check } from '../src/commands/doctor.ts';
+import { readBootId, readPidNs } from '../src/core/pglite-lock.ts';
import { writeHarnessReceipt } from '../src/core/bootstrap/format.ts';
import { LATEST_VERSION } from '../src/core/migrate.ts';
import { VERSION } from '../src/version.ts';
@@ -496,23 +497,73 @@ describe('bootstrap_serve_lock', () => {
writeFileSync(join(lockDir, 'lock'), JSON.stringify(lock));
}
- test('live serve holder → ok (hook IPC available), names the pid', async () => {
+ // #5481: a lock holder must be a GENUINELY FOREIGN live process to exercise
+ // the ok/warn paths meaningfully — `probeLivePgliteHolder` only requires
+ // liveness, and the fix under test distinguishes "this process's own pid"
+ // from every other case, so a foreign/self test pair needs two distinct
+ // real pids. Cross-platform: a JS timer via a spawned bun/node process,
+ // not a shelled-out POSIX command.
+ async function withLiveForeignProcess<T>(fn: (pid: number) => Promise<T>): Promise<T> {
+ const proc = Bun.spawn([process.execPath, '-e', 'setInterval(() => {}, 1000)'], {
+ stdio: ['ignore', 'ignore', 'ignore'],
+ });
+ try {
+ return await fn(proc.pid);
+ } finally {
+ proc.kill();
+ }
+ }
+
+ test('live serve holder (foreign pid) → ok, names the pid', async () => {
+ await withLiveForeignProcess(async (foreignPid) => {
+ const { parent, home } = makeHome();
+ writeHeartbeat(home, [{ outcome: 'ok' }]); // open the gate
+ writeLock(home, { pid: foreignPid, subcommand: 'serve' });
+ const c = byName(await run(parent), 'bootstrap_serve_lock');
+ expect(c?.status).toBe('ok');
+ expect(c?.message).toContain(String(foreignPid));
+ expect(c?.message).toContain('live serve');
+ });
+ }, T);
+
+ test('live NON-serve holder (foreign pid) → warn (hook IPC blocked)', async () => {
+ await withLiveForeignProcess(async (foreignPid) => {
+ const { parent, home } = makeHome();
+ writeHeartbeat(home, [{ outcome: 'ok' }]);
+ writeLock(home, { pid: foreignPid, subcommand: 'sync' });
+ const c = byName(await run(parent), 'bootstrap_serve_lock');
+ expect(c?.status).toBe('warn');
+ expect(c?.message).toContain('non-serve');
+ expect(c?.message).toContain(String(foreignPid));
+ });
+ }, T);
+
+ test('#5481: live NON-serve holder whose pid IS this doctor process, matching namespace evidence → no check (self lock is not a foreign collision)', async () => {
const { parent, home } = makeHome();
- writeHeartbeat(home, [{ outcome: 'ok' }]); // open the gate
- writeLock(home, { pid: process.pid, subcommand: 'serve' });
- const c = byName(await run(parent), 'bootstrap_serve_lock');
- expect(c?.status).toBe('ok');
- expect(c?.message).toContain(String(process.pid));
- expect(c?.message).toContain('live serve');
+ writeHeartbeat(home, [{ outcome: 'ok' }]);
+ writeLock(home, { pid: process.pid, subcommand: 'sync', pid_ns: readPidNs(), boot_id: readBootId() });
+ expect(byName(await run(parent), 'bootstrap_serve_lock')).toBeUndefined();
}, T);
- test('live NON-serve holder → warn (hook IPC blocked)', async () => {
+ test('#5481: pid matches but namespace evidence is foreign → still warns (a shared-mount container cannot masquerade as self via pid reuse)', async () => {
const { parent, home } = makeHome();
writeHeartbeat(home, [{ outcome: 'ok' }]);
- writeLock(home, { pid: process.pid, subcommand: 'sync' });
+ writeLock(home, {
+ pid: process.pid,
+ subcommand: 'sync',
+ pid_ns: 'pid:[99999999]',
+ boot_id: '00000000-0000-0000-0000-000000000000',
+ });
const c = byName(await run(parent), 'bootstrap_serve_lock');
- expect(c?.status).toBe('warn');
- expect(c?.message).toContain('non-serve');
+ if (process.platform === 'linux') {
+ expect(c?.status).toBe('warn');
+ expect(c?.message).toContain('non-serve');
+ } else {
+ // Non-Linux platforms have no PID namespaces; a pid match alone is
+ // trusted there, matching pglite-lock.ts's own acquisition-time
+ // platform short-circuit.
+ expect(c).toBeUndefined();
+ }
}, T);
test('dead holder / no lock → no check (stale lock dir is inert)', async () => {
diff --git a/test/bootstrap-uninstall.serial.test.ts b/test/bootstrap-uninstall.serial.test.ts
index 1d72aff870..3f35c3c350 100644
--- a/test/bootstrap-uninstall.serial.test.ts
+++ b/test/bootstrap-uninstall.serial.test.ts
@@ -19,6 +19,7 @@ import {
uninstallWorkspace,
} from '../src/core/bootstrap/uninstall.ts';
import { BootstrapError } from '../src/core/bootstrap/lock.ts';
+import { readBootId, readPidNs } from '../src/core/pglite-lock.ts';
import { readReceipt, writeReceipt, type InstallReceipt } from '../src/core/bootstrap/format.ts';
let ws: string;
@@ -387,10 +388,16 @@ describe('probeLivePgliteHolder', () => {
mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
writeFileSync(
join(dataDir, '.gbrain-lock', 'lock'),
- JSON.stringify({ pid: process.pid, command: 'embed --stale', subcommand: 'embed' }),
+ JSON.stringify({
+ pid: process.pid,
+ command: 'embed --stale',
+ subcommand: 'embed',
+ pid_ns: readPidNs(),
+ boot_id: readBootId(),
+ }),
'utf8',
);
- expect(probeLivePgliteHolder(dataDir)).toEqual({ pid: process.pid, serve: false });
+ expect(probeLivePgliteHolder(dataDir)).toEqual({ pid: process.pid, serve: false, isSelf: true });
});
test('legacy lock without subcommand falls back to command-string parsing', () => {
@@ -398,10 +405,10 @@ describe('probeLivePgliteHolder', () => {
mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
writeFileSync(
join(dataDir, '.gbrain-lock', 'lock'),
- JSON.stringify({ pid: process.pid, command: 'gbrain serve' }),
+ JSON.stringify({ pid: process.pid, command: 'gbrain serve', pid_ns: readPidNs(), boot_id: readBootId() }),
'utf8',
);
- expect(probeLivePgliteHolder(dataDir)).toEqual({ pid: process.pid, serve: true });
+ expect(probeLivePgliteHolder(dataDir)).toEqual({ pid: process.pid, serve: true, isSelf: true });
});
test('absent or unreadable lock → null', () => {
@@ -411,6 +418,197 @@ describe('probeLivePgliteHolder', () => {
writeFileSync(join(dataDir, '.gbrain-lock', 'lock'), 'not json', 'utf8');
expect(probeLivePgliteHolder(dataDir)).toBeNull();
});
+
+ // #5481 review F6: a pid+namespace match alone is not proof THIS process
+ // acquired the lock. Within one boot session a dead process's pid can be
+ // reused by a later, unrelated live process (including this doctor
+ // invocation) -- a genuinely stale legacy lock left behind by the dead
+ // process can still block real database access via pglite-lock.ts's own
+ // acquisition-time reap logic, which sees the recycled pid as alive and
+ // correctly refuses to reclaim it. `acquired_at` predating this process's
+ // own start time proves the lock cannot be ours, regardless of matching
+ // pid/namespace evidence.
+ test('lock acquired before THIS process started → not self even with matching pid and namespace evidence (stale legacy lock, recycled pid)', () => {
+ const dataDir = join(home, 'brain.pglite');
+ mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
+ writeFileSync(
+ join(dataDir, '.gbrain-lock', 'lock'),
+ JSON.stringify({
+ pid: process.pid,
+ subcommand: 'serve',
+ pid_ns: readPidNs(),
+ boot_id: readBootId(),
+ acquired_at: 1000,
+ }),
+ 'utf8',
+ );
+ const holder = probeLivePgliteHolder(dataDir);
+ expect(holder).toEqual({ pid: process.pid, serve: true, isSelf: false });
+ });
+
+ test('lock acquired AFTER this process started (or acquired_at absent) → matching pid/namespace still reads as self', () => {
+ const dataDir = join(home, 'brain.pglite');
+ mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
+ writeFileSync(
+ join(dataDir, '.gbrain-lock', 'lock'),
+ JSON.stringify({ pid: process.pid, subcommand: 'serve', pid_ns: readPidNs(), boot_id: readBootId(), acquired_at: Date.now() }),
+ 'utf8',
+ );
+ const holder = probeLivePgliteHolder(dataDir);
+ expect(holder).toEqual({ pid: process.pid, serve: true, isSelf: true });
+ });
+
+ // #5481 review F1: `ourProcessStartTime`'s default path is anchored ONCE at
+ // module load (near real process start, since this module is a static
+ // top-level import), not recomputed from `Date.now() - process.uptime() *
+ // 1000` at probe-call time. A wall-clock jump (NTP correction, VM/container
+ // pause-resume) occurring AFTER module load but BEFORE a later check
+ // actually runs the probe must not retroactively move the start-time
+ // estimate later and false-flag a genuinely-self lock as foreign.
+ test('a wall-clock jump between module load and the probe call does not flip a genuinely-self lock to non-self', () => {
+ const dataDir = join(home, 'brain.pglite');
+ mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
+ // This process's own lock, written at (simulated) true process start.
+ const trueAcquiredAt = Date.now();
+ writeFileSync(
+ join(dataDir, '.gbrain-lock', 'lock'),
+ JSON.stringify({ pid: process.pid, subcommand: 'serve', pid_ns: readPidNs(), boot_id: readBootId(), acquired_at: trueAcquiredAt }),
+ 'utf8',
+ );
+ const realNow = Date.now;
+ try {
+ // Simulate a forward wall-clock jump discovered well after module
+ // load: if the default path still recomputed `Date.now() -
+ // process.uptime() * 1000` at call time (the pre-fix behavior), this
+ // jump alone would push the estimated start time past
+ // `trueAcquiredAt + ACQUIRED_AT_TOLERANCE_MS`, wrongly flagging the
+ // process's own lock as pre-existing (not self).
+ Date.now = () => realNow() + 10 * 60 * 1000;
+ const holder = probeLivePgliteHolder(dataDir);
+ expect(holder).toEqual({ pid: process.pid, serve: true, isSelf: true });
+ } finally {
+ Date.now = realNow;
+ }
+ });
+
+ // #5481 review F2: on Linux, when THIS process's own /proc markers are
+ // unreadable (a hardened environment masking pid-namespace/boot-id), the
+ // doctor's own self-lock (which it wrote under the same restriction, so it
+ // stored the same unreadable evidence) must still read as self — namespace
+ // evidence can't verify anyone in that state, so pid equality alone must
+ // decide, exactly like the non-Linux fallback.
+ describe('Linux namespace-evidence edge cases (#5481 review F2)', () => {
+ const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
+
+ function withLinuxPlatform<T>(fn: () => T): T {
+ Object.defineProperty(process, 'platform', { ...platformDescriptor, value: 'linux' });
+ try {
+ return fn();
+ } finally {
+ Object.defineProperty(process, 'platform', platformDescriptor);
+ }
+ }
+
+ // #5481 review F5: reverted the earlier both-unavailable-is-self fallback.
+ // Namespace evidence unreadable on BOTH sides (a restricted /proc that
+ // masks pid_ns/boot_id for a lock this process holds) cannot distinguish
+ // a genuine self-lock from a foreign lock under the SAME restriction, so
+ // it fails CLOSED (still warns) rather than risk a silent misclassification
+ // — matching pglite-lock.ts's own acquisition-time comparability guard,
+ // which likewise requires non-null matching before treating evidence as
+ // usable. This narrows self-detection to environments where namespace
+ // evidence is actually readable; a restricted-/proc doctor process will
+ // still see the original #5481 false positive about its own lock.
+ test('our own namespace markers unreadable + matching (null) stored markers → fails closed, still warns', () => {
+ withLinuxPlatform(() => {
+ const dataDir = join(home, 'brain.pglite');
+ mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
+ writeFileSync(
+ join(dataDir, '.gbrain-lock', 'lock'),
+ JSON.stringify({ pid: process.pid, subcommand: 'embed', pid_ns: null, boot_id: null }),
+ 'utf8',
+ );
+ const holder = probeLivePgliteHolder(dataDir, { readPidNs: () => null, readBootId: () => null });
+ expect(holder).toEqual({ pid: process.pid, serve: false, isSelf: false });
+ });
+ });
+
+ test('our own namespace markers ARE readable + stored markers foreign → still warns (no silent regression)', () => {
+ withLinuxPlatform(() => {
+ const dataDir = join(home, 'brain.pglite');
+ mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
+ writeFileSync(
+ join(dataDir, '.gbrain-lock', 'lock'),
+ JSON.stringify({
+ pid: process.pid,
+ subcommand: 'embed',
+ pid_ns: 'pid:[99999999]',
+ boot_id: '00000000-0000-0000-0000-000000000000',
+ }),
+ 'utf8',
+ );
+ const holder = probeLivePgliteHolder(dataDir, {
+ readPidNs: () => 'pid:[11111111]',
+ readBootId: () => '11111111-1111-1111-1111-111111111111',
+ });
+ expect(holder).toEqual({ pid: process.pid, serve: false, isSelf: false });
+ });
+ });
+
+ // #5481 review F1 (round 3): an unreadable marker on ONE side must never
+ // hide a definite mismatch on the OTHER, readable marker.
+ test('pid_ns unreadable on our side, boot_id readable and foreign → still warns', () => {
+ withLinuxPlatform(() => {
+ const dataDir = join(home, 'brain.pglite');
+ mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
+ writeFileSync(
+ join(dataDir, '.gbrain-lock', 'lock'),
+ JSON.stringify({ pid: process.pid, subcommand: 'embed', pid_ns: 'pid:[99999999]', boot_id: 'foreign-boot' }),
+ 'utf8',
+ );
+ const holder = probeLivePgliteHolder(dataDir, { readPidNs: () => null, readBootId: () => 'local-boot' });
+ expect(holder).toEqual({ pid: process.pid, serve: false, isSelf: false });
+ });
+ });
+
+ test('boot_id unreadable on our side, pid_ns readable and foreign → still warns', () => {
+ withLinuxPlatform(() => {
+ const dataDir = join(home, 'brain.pglite');
+ mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
+ writeFileSync(
+ join(dataDir, '.gbrain-lock', 'lock'),
+ JSON.stringify({ pid: process.pid, subcommand: 'embed', pid_ns: 'foreign-ns', boot_id: '00000000-0000-0000-0000-000000000000' }),
+ 'utf8',
+ );
+ const holder = probeLivePgliteHolder(dataDir, { readPidNs: () => 'local-ns', readBootId: () => null });
+ expect(holder).toEqual({ pid: process.pid, serve: false, isSelf: false });
+ });
+ });
+
+ // #5481 review F1 (round 4): a FOREIGN lock with null/missing namespace
+ // markers (an older binary, or a foreign container's own restricted
+ // /proc) must never be trusted as self just because OUR OWN readers
+ // happen to work — a genuine self-lock written by this same live process
+ // would have stored matching non-null values whenever our readers
+ // succeed, so a stored null next to our readable value is a foreign
+ // environment, not "no evidence to compare".
+ test('lock markers null/missing but OUR readers succeed → still warns (asymmetric availability is never self)', () => {
+ withLinuxPlatform(() => {
+ const dataDir = join(home, 'brain.pglite');
+ mkdirSync(join(dataDir, '.gbrain-lock'), { recursive: true });
+ writeFileSync(
+ join(dataDir, '.gbrain-lock', 'lock'),
+ JSON.stringify({ pid: process.pid, subcommand: 'embed', pid_ns: null, boot_id: null }),
+ 'utf8',
+ );
+ const holder = probeLivePgliteHolder(dataDir, {
+ readPidNs: () => 'pid:[12345678]',
+ readBootId: () => '22222222-2222-2222-2222-222222222222',
+ });
+ expect(holder).toEqual({ pid: process.pid, serve: false, isSelf: false });
+ });
+ });
+ });
});
describe('resolveBrainDataDir', () => {
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index 3e1b41599d..b3dae42a69 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -722,6 +722,8 @@
"isProcessAlive",
"msSinceLastReap",
"peekLock",
+ "readBootId",
+ "readPidNs",
"releaseLock"
],
"./search/evidence-delivery": [
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 2bafcead62..cc5e33f9bd 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6010,6 +6010,20 @@
"(dataDir: string | undefined) => LockPeekResult"
]
},
+ {
+ "kind": "function",
+ "name": "readBootId",
+ "signature": [
+ "() => string | null"
+ ]
+ },
+ {
+ "kind": "function",
+ "name": "readPidNs",
+ "signature": [
+ "() => string | null"
+ ]
+ },
{
"kind": "function",
"name": "releaseLock",