Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-130 PR 2: legacy-lock repair reads macOS locality from df -P and mount (local flag + known-local type), fails closed otherwise

garrytan31d56bfef12a
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index a02985d2a1..6966be9faa 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -547,7 +547,7 @@ the same reason and fix on its `connection` check.
never opens the engine and never creates anything. It names the recorded
PID, whether `kill -0` says it is running and its command, the processes
an open-file scan of `/proc` (Linux) saw holding files under the data dir,
- and the filesystem type (Linux `statfs`), and prints the `plan_hash` and
+ and the filesystem type (Linux `statfs`, macOS `df -P` and `mount`), and prints the `plan_hash` and
the apply command. This evidence is advisory: it covers only this host and
PID namespace and cannot see other containers or other hosts that share the
folder.
@@ -559,9 +559,11 @@ the same reason and fix on its `connection` check.
could be gbrain (`live_holder`), or when the data dir is on a network or
shared filesystem such as NFS, SMB, 9p, virtiofs or FUSE
(`network_filesystem`), or when it cannot confirm the filesystem is local
- (`filesystem_unverified`: locality is read only on Linux, so macOS and
- other systems, a failing `statfs` and an unrecognised filesystem type all
- refuse). A lock that changed since the preview refuses `preview_changed`.
+ (`filesystem_unverified`: Linux reads `statfs`; macOS reads the mount
+ point from `df -P` and its `mount` line, and counts it local only with
+ the `local` flag and a local type such as apfs or hfs. Other systems, a
+ failed probe, an unrecognised type, a macOS network mount such as smbfs or
+ nfs, and a macOS mount without the `local` flag all refuse). A lock that changed since the preview refuses `preview_changed`.
It inspects again after consent, so a holder or change that appears while
the prompt waits refuses the same way. Otherwise it moves the folder into
`<data-dir>.legacy-lock-removed-<timestamp>/` (nothing is deleted) with a
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 623d417a2b..0da51cdc63 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -43,6 +43,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/pglite-statements.ts` — `PgliteStatementCache`, the PGLite counterpart of postgres.js prepared statements. `PGLiteEngine._attachDatabase` routes the root handle's `query`/`exec` through it and `transaction()` routes each transaction handle. A statement text seen twice is prepared once as a named server-side statement; later calls send one Bind/Execute/Sync batch and parse rows with parsers resolved at prepare time, instead of PGlite's parse/describe round trips and its per-query copy of `db.parsers`. PostgreSQL's plan cache replans on invalidation; a changed result shape (`0A000`) or missing statement (`26000`) drops the entry and retries outside a transaction. `ALTER`/`CREATE`/`DROP`/`DO`/`DISCARD`/`DEALLOCATE` text, `ANALYZE`/`VACUUM` (PostgreSQL keeps a prepared plan across a statistics refresh, so a plan made before the table had statistics would outlive planner-stats' first-read ANALYZE) and any non-transaction-control `exec` clear the cache, retired names are closed in the next prepare batch, an instance-level `query`/`exec` override (test seams) takes precedence on the root handle, and `_closeInternal` drops the cache with the database so a disconnected engine does not retain its PGLite instance. `configurePgliteCodecs` removes composite-row array parsers after connect, since gbrain never selects those arrays, and replaces PGlite's per-byte bytea codec with Buffer's hex codec (a 4 MiB bytea batch no longer allocates ~250 MB of garbage). Pinned by `test/pglite-statements.test.ts`.
-- `src/core/pglite-legacy-lock.ts` — core of `gbrain pglite-repair --legacy-lock` (C-3): read-only `inspectLegacyLock` (verdict, plan hash over the legacy dir, advisory this-host-only evidence: kill -0, /proc fd scan, statfs; refuses `live_holder`/`network_filesystem`/`filesystem_unverified`, the last when locality is unknown: not Linux, statfs failed or an unrecognised type) and `applyLegacyLockRemoval` (moves the dir aside with a receipt, backs up the prior ownership marker bytes, writes the kernel-v1 marker; the restore command puts the marker back). Test: `test/pathological/c3-pglite-legacy-lock.test.ts`.
+- `src/core/pglite-legacy-lock.ts` — core of `gbrain pglite-repair --legacy-lock` (C-3): read-only `inspectLegacyLock` (verdict, plan hash over the legacy dir, advisory this-host-only evidence: kill -0, /proc fd scan, statfs; refuses `live_holder`/`network_filesystem`/`filesystem_unverified`, the last when locality is unknown: neither Linux statfs nor macOS `df -P` + `mount` (`local` flag and a known-local type) confirms a local disk, or a probe failed) and `applyLegacyLockRemoval` (moves the dir aside with a receipt, backs up the prior ownership marker bytes, writes the kernel-v1 marker; the restore command puts the marker back). Test: `test/pathological/c3-pglite-legacy-lock.test.ts`.
- `src/core/pglite-repair.ts` — WAL-repair orchestrator wrapping the resetWal port with the safety layers that make it runnable automatically from `connect()`: `validateWalRepairTarget` (read-only, fail-closed; refuses symlinked dataDir/pg_wal/`global`/pg_control — lstat follows INTERMEDIATE symlinks, so `global/` itself must be checked or surgery would write pg_control through it into a foreign dir; tolerates the in-dir `.gbrain-lock`), rename-based backup (the ENTIRE `pg_wal/` dir + postmaster.pid renamed into a sibling `<dataDir>.wal-repair-backup-<ts>/`, only the 8KB pg_control copied — zero transient disk cost), `restoreWalBackup` (overwrite order: control first via atomic tmp+rename, then a pg_wal dir swap with the reset dir set ASIDE inside the backup — nothing is ever deleted during restore; mtime guard refuses when a foreign segment is newer than the backup; a missing/empty backup NEVER reports `restored:true`), `WalRepairError` (thrown when resetWal fails AFTER the backup — carries the receipt + the best-effort restore's REAL result so the seam's `restored` flag and the `failed-restored`/`failed-not-restored` message arms never lie), a cooldown sidecar `<dataDir>.wal-repair-attempt.json` (skip `'recently-failed'` inside `GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600 — bounds the autopilot/supervisor reconnect loops) with episode-scoped backups (attempts within one corruption episode REUSE the episode's first backup — the pre-damage forensic state, honored only when the sidecar's path is a real non-symlink `<dataDir>.wal-repair-backup-*` sibling since the sidecar is user-writable JSON; retention keeps the newest 3 episodes, never pruning the open episode's), and `attemptWalRepairAndRetry` — the engine seam that NEVER throws (gates: kill-switch → reaped-lock `'possibly-live-writer'` → 10-minute reap-marker quarantine (`msSinceLastReap`, cross-process) → validation → cooldown; then repair → retry create once → restore-and-record on failure; prints a repair-start stderr line so a timeout-killed attempt is self-explaining). `inspectPgliteDataDir` is the read-only diagnosis for `gbrain doctor` + `pglite-repair --dry-run`. Imports runtime values only from `pglite-lock.ts`/`pglite-resetwal.ts`/node:fs — never from `pglite-engine.ts` (no cycle; the engine statically imports THIS file per the engine-live rule). Pinned by `test/pglite-repair.test.ts` + `test/pglite-wal-repair.serial.test.ts`.
- `src/core/pglite-repair-consent.ts` + the repair-failed marker in `src/core/pglite-repair.ts` — when automatic WAL repair fails (or a recent failure put it on cooldown) `recordFailedAutoRepair` writes the sibling `<dataDir>.repair-failed.json`; while it exists `PGLiteEngine.connect()` refuses before `acquireLock` (zero writes to the data dir) with `repairFailedRefusal`: the exit-3 consent payload (effects `destructive`, fix `gbrain pglite-repair [--path] --yes --expect <plan_hash>` from the same `walRepairPlan` the command binds, preview `--dry-run --json`, and the hands-off text `HANDS_OFF_BRAIN_FILES`). The CLI's `exitOnRepairFailed` (`src/cli/cli-error.ts`) exits 3 on it from `connectEngine`; stdio serve maps it to status reason `repair_failed`. Cleared by a completed `pglite-repair` or `reinit-pglite`. Pinned by `test/agent-operator-gate-fixes.{,serial.}test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index cfed93e76a..accd7d217e 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2084,7 +2084,7 @@ More: [docs/guides/repair.md#legacy-jobs-active](../../docs/guides/repair.md#leg
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| `gbrain pglite-repair --legacy-lock` refused to move a legacy PGLite lock aside: a process on this host still uses the data dir, the data dir is on a network or shared filesystem, or gbrain could not confirm the filesystem is local. | The evidence the repair reads (kill -0, the process command, an open-file scan) covers only this host and PID namespace. A process that still holds the data dir, or a filesystem other hosts can mount or whose locality cannot be read (not Linux, statfs failed, an unrecognised type), means the old owner may still be writing, and removing its lock would let two writers corrupt the brain. | Stop the process the message names (on a shared filesystem: every gbrain on every host that mounts it), then preview again with gbrain pglite-repair --legacy-lock --dry-run. For filesystem_unverified, run the repair on a Linux host where the folder is on a local disk; elsewhere only the user can confirm no gbrain on any computer reaches the folder and move the lock folder aside. | host_admin | `gbrain doctor --json` | 1 | no |
+| `gbrain pglite-repair --legacy-lock` refused to move a legacy PGLite lock aside: a process on this host still uses the data dir, the data dir is on a network or shared filesystem, or gbrain could not confirm the filesystem is local. | The evidence the repair reads (kill -0, the process command, an open-file scan) covers only this host and PID namespace. A process that still holds the data dir, or a filesystem other hosts can mount or whose locality cannot be confirmed (neither Linux nor macOS, a failed probe, an unrecognised type, a macOS mount without the local flag), means the old owner may still be writing, and removing its lock would let two writers corrupt the brain. | Stop the process the message names (on a shared filesystem: every gbrain on every host that mounts it), then preview again with gbrain pglite-repair --legacy-lock --dry-run. For filesystem_unverified, run the repair on a Linux or macOS host where the folder is on a local disk; elsewhere only the user can confirm no gbrain on any computer reaches the folder and move the lock folder aside. | host_admin | `gbrain doctor --json` | 1 | no |
Reasons: `live_holder`, `network_filesystem`, `filesystem_unverified`.
diff --git a/llms-full.txt b/llms-full.txt
index b51afbeebf..0f740f9399 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5832,7 +5832,7 @@ the same reason and fix on its `connection` check.
never opens the engine and never creates anything. It names the recorded
PID, whether `kill -0` says it is running and its command, the processes
an open-file scan of `/proc` (Linux) saw holding files under the data dir,
- and the filesystem type (Linux `statfs`), and prints the `plan_hash` and
+ and the filesystem type (Linux `statfs`, macOS `df -P` and `mount`), and prints the `plan_hash` and
the apply command. This evidence is advisory: it covers only this host and
PID namespace and cannot see other containers or other hosts that share the
folder.
@@ -5844,9 +5844,11 @@ the same reason and fix on its `connection` check.
could be gbrain (`live_holder`), or when the data dir is on a network or
shared filesystem such as NFS, SMB, 9p, virtiofs or FUSE
(`network_filesystem`), or when it cannot confirm the filesystem is local
- (`filesystem_unverified`: locality is read only on Linux, so macOS and
- other systems, a failing `statfs` and an unrecognised filesystem type all
- refuse). A lock that changed since the preview refuses `preview_changed`.
+ (`filesystem_unverified`: Linux reads `statfs`; macOS reads the mount
+ point from `df -P` and its `mount` line, and counts it local only with
+ the `local` flag and a local type such as apfs or hfs. Other systems, a
+ failed probe, an unrecognised type, a macOS network mount such as smbfs or
+ nfs, and a macOS mount without the `local` flag all refuse). A lock that changed since the preview refuses `preview_changed`.
It inspects again after consent, so a holder or change that appears while
the prompt waits refuses the same way. Otherwise it moves the folder into
`<data-dir>.legacy-lock-removed-<timestamp>/` (nothing is deleted) with a
diff --git a/src/commands/pglite-repair-legacy-lock.ts b/src/commands/pglite-repair-legacy-lock.ts
index 7af3748548..74c2a0960e 100644
--- a/src/commands/pglite-repair-legacy-lock.ts
+++ b/src/commands/pglite-repair-legacy-lock.ts
@@ -68,7 +68,7 @@ function printPreview(i: LegacyLockInspection, json: boolean): number {
function refuse(i: LegacyLockInspection, json: boolean): number {
const refusal = i.refusal!;
const hint = refusal.reason === 'filesystem_unverified'
- ? 'Run the preview and the repair on a Linux host where this folder is on a local disk. Where gbrain cannot check locality (macOS, an unrecognised filesystem), only the user can confirm that no gbrain on any computer reaches this folder and move the lock folder aside themselves.'
+ ? 'If the folder is on a network or shared mount, stop every gbrain on every host that mounts it. Otherwise run the preview and the repair on a Linux or macOS host where this folder is on a local disk. Where gbrain cannot check locality (another system, an unrecognised filesystem), only the user can confirm that no gbrain on any computer reaches this folder and move the lock folder aside themselves.'
: 'Stop the process named in the message (on a shared filesystem: every gbrain on every host that mounts it), then run the preview again.';
const e = opError('legacy_lock_removal_refused', `${refusal.message} The legacy lock at ${i.legacy_lock.dir} was left in place.`, hint,
{ reason: refusal.reason, fix: previewFix(i.data_dir) });
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 5a50706ebf..9189ff3b10 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -354,7 +354,7 @@ export const CODES = {
ipc_path_too_long: { class: 'host_only', summary: "The brain's local IPC socket path is longer than the operating system allows, even after the per-user run-dir fallback, so hooks and local commands cannot reach gbrain serve.", why: 'A Unix-domain socket path must fit sockaddr_un (107 bytes on Windows afunix, 103 on macOS); on Windows a long PGLite data-dir path already moves to %USERPROFILE%\\.gbrain\\run, and only a profile path too long for that is reported.', docs: 'docs/guides/troubleshooting.md#ipc-path-too-long', suggestion: 'Stop gbrain serve, move the brain to a shorter path (`gbrain config set database_path <shorter path>` after moving the data directory), then restart serve.', fix: { argv: ['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the socket path, its byte count and the limit.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json'] } } },
legacy_job_selection_invalid: { class: 'caller', summary: "The legacy job selection is invalid." },
legacy_jobs_active: { class: 'caller', summary: "Legacy jobs are still active." },
- legacy_lock_removal_refused: { class: 'host_only', summary: "`gbrain pglite-repair --legacy-lock` refused to move a legacy PGLite lock aside: a process on this host still uses the data dir, the data dir is on a network or shared filesystem, or gbrain could not confirm the filesystem is local.", why: "The evidence the repair reads (kill -0, the process command, an open-file scan) covers only this host and PID namespace. A process that still holds the data dir, or a filesystem other hosts can mount or whose locality cannot be read (not Linux, statfs failed, an unrecognised type), means the old owner may still be writing, and removing its lock would let two writers corrupt the brain.", reasons: ['live_holder', 'network_filesystem', 'filesystem_unverified'], docs: 'docs/ENGINES.md#legacy-pglite-lock', suggestion: 'Stop the process the message names (on a shared filesystem: every gbrain on every host that mounts it), then preview again with gbrain pglite-repair --legacy-lock --dry-run. For filesystem_unverified, run the repair on a Linux host where the folder is on a local disk; elsewhere only the user can confirm no gbrain on any computer reaches the folder and move the lock folder aside.' },
+ legacy_lock_removal_refused: { class: 'host_only', summary: "`gbrain pglite-repair --legacy-lock` refused to move a legacy PGLite lock aside: a process on this host still uses the data dir, the data dir is on a network or shared filesystem, or gbrain could not confirm the filesystem is local.", why: "The evidence the repair reads (kill -0, the process command, an open-file scan) covers only this host and PID namespace. A process that still holds the data dir, or a filesystem other hosts can mount or whose locality cannot be confirmed (neither Linux nor macOS, a failed probe, an unrecognised type, a macOS mount without the local flag), means the old owner may still be writing, and removing its lock would let two writers corrupt the brain.", reasons: ['live_holder', 'network_filesystem', 'filesystem_unverified'], docs: 'docs/ENGINES.md#legacy-pglite-lock', suggestion: 'Stop the process the message names (on a shared filesystem: every gbrain on every host that mounts it), then preview again with gbrain pglite-repair --legacy-lock --dry-run. For filesystem_unverified, run the repair on a Linux or macOS host where the folder is on a local disk; elsewhere only the user can confirm no gbrain on any computer reaches the folder and move the lock folder aside.' },
local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },
lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },
loops_extraction_skipped: { class: 'unavailable', summary: "A Google sweep or the managed catch-up queued no paid loop extraction; the sync summary's `skipped_reason` says why. Nothing failed and the email pages still imported.", why: "Extraction is gated before any model call: a kill switch, a missing chat provider, the day's spend cap (`loops.extraction_max_usd_per_day`, default $2.00; `spend_cap_zero` means the user set it to 0), or an exclusion label (`g_loops_exclude_labels` / `loops.extraction_exclude_labels`) that did not resolve against the account's labels, which fails closed until a sweep resolves it.", reasons: ['no_candidates', 'extraction_disabled', 'chat_unavailable', 'enqueue_failed', 'daily_spend_cap', 'spend_cap_zero', 'excluded_label', 'excluded_label_unresolved'], docs: 'docs/guides/open-loops.md#two-detectors', suggestion: 'Read the reason. `daily_spend_cap` clears at the next UTC day or when the user raises `loops.extraction_max_usd_per_day`; `excluded_label_unresolved` names the label token to fix in `gbrain sources status <id>` or `gbrain config get loops.extraction_exclude_labels`; the threads are extracted on their next touch or by `gbrain sync --source <id> --full`.', fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: the last sweep\'s loop extraction report with its skipped_reason and the unresolved label tokens.', requires_exclusive: false, verify: { argv: ['gbrain', 'config', 'get', 'loops.extraction_max_usd_per_day'] } } },
diff --git a/src/core/pglite-legacy-lock.ts b/src/core/pglite-legacy-lock.ts
index 0e16ad744e..c34d7496c9 100644
--- a/src/core/pglite-legacy-lock.ts
+++ b/src/core/pglite-legacy-lock.ts
@@ -9,12 +9,13 @@
* canonical data dir plus the legacy dir's inode, every entry's bytes and the
* marker bytes) and ADVISORY evidence: kill -0 and the command of the recorded
* PID, an open-file scan of /proc (Linux), and the filesystem type (Linux
- * statfs). That evidence covers only this host and PID namespace; it cannot
+ * statfs; macOS `df -P` plus `mount`, local only with the `local` flag). That evidence covers only this host and PID namespace; it cannot
* see other containers, PID namespaces or hosts sharing the folder, so it is
* never stated as proof. A live holder (an open file under the data dir, a
* live recorded PID whose command could be gbrain, or a comparable live PID),
* a network/shared filesystem, or a filesystem whose locality cannot be read
- * (not Linux, statfs failed, an unrecognised type: fail closed) makes the lock
+ * (neither Linux nor macOS, a failed probe, an unrecognised type, a macOS
+ * mount without the `local` flag: fail closed) makes the lock
* not removable.
*
* `applyLegacyLockRemoval` runs only under the stable sibling kernel lock and
@@ -30,6 +31,7 @@ import { createHash } from 'node:crypto';
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, statfsSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { shellQuote } from './agent-output.ts';
+import { execFileSync } from './spawn.ts';
import { computePlanHash, type PlanSelection } from './consent.ts';
import { isProcessAlive, legacyOwnerUnverified, pgliteLockDirFor, readMetadata, readProcessArgs, PGLITE_LOCK_PROTOCOL, type LegacyUnverifiedReason } from './pglite-lock.ts';
@@ -44,6 +46,8 @@ const LOCAL_FILESYSTEMS: Readonly<Record<number, string>> = {
0xca451a4e: 'bcachefs', 0x4d44: 'vfat', 0x2011bab0: 'exfat', 0x5346544e: 'ntfs', 0x7366746e: 'ntfs3', 0x482b: 'hfsplus', 0x858458f6: 'ramfs',
0x52654973: 'reiserfs', 0x3153464a: 'jfs', 0x3434: 'nilfs',
};
+/** macOS `mount` types that are local disks; a mount counts as local only with one of these AND the `local` flag. */
+const DARWIN_LOCAL_FILESYSTEMS: ReadonlySet<string> = new Set(['apfs', 'hfs', 'exfat', 'msdos']);
export function networkFilesystemName(magic: number): string | null {
return NETWORK_FILESYSTEMS[magic >>> 0] ?? null;
}
@@ -58,7 +62,7 @@ export interface LegacyLockEvidence {
pid_alive: boolean | null;
pid_command: string | null;
fd_scan: { method: 'proc' | 'unavailable'; holders: Array<{ pid: number; command: string | null; paths: string[] }>; uninspectable: number };
- /** `network: null` means locality is unknown (not Linux, statfs failed, or an unrecognised type) and refuses like a network filesystem. */
+ /** `network: null` means locality is unknown (neither Linux nor macOS, a failed probe, an unrecognised type, or a macOS mount that is not local) and refuses `filesystem_unverified`. */
filesystem: { type: string | null; magic: number | null; network: boolean | null };
}
@@ -87,7 +91,11 @@ const markerPathOf = (dataDir: string) => `${dataDir}.gbrain-owner.json`;
export interface LegacyLockProbe {
platform?: NodeJS.Platform;
statfs?: (path: string) => { type: number };
+ /** Runs an absolute-path command without a shell and returns its stdout (macOS `df` and `mount`). */
+ exec?: (file: string, args: readonly string[]) => string;
}
+const execNoShell = (file: string, args: readonly string[]): string =>
+ String(execFileSync(file, [...args], { encoding: 'utf8', timeout: 5_000, stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, LC_ALL: 'C' } }));
function scanOpenFiles(dataDir: string, platform: NodeJS.Platform): LegacyLockEvidence['fd_scan'] {
if (platform !== 'linux' || !existsSync('/proc/self/fd')) return { method: 'unavailable', holders: [], uninspectable: 0 };
@@ -112,8 +120,33 @@ function scanOpenFiles(dataDir: string, platform: NodeJS.Platform): LegacyLockEv
return { method: 'proc', holders, uninspectable };
}
+/**
+ * macOS: the data dir's mount point from `df -P` (everything after the
+ * capacity column, so spaces survive), then that mount point's one line in
+ * `mount` (`<dev> on <mountpoint> (<type>, <flags...>)`). Local only with the
+ * `local` flag and a known-local type; anything else, including a network
+ * type, a missing or duplicated line and any parse or command failure, is
+ * unknown (`network: null`).
+ */
+function darwinFilesystemOf(dataDir: string, exec: NonNullable<LegacyLockProbe['exec']>): LegacyLockEvidence['filesystem'] {
+ const unknown = (type: string | null = null) => ({ type, magic: null, network: null });
+ try {
+ const df = exec('/bin/df', ['-P', dataDir]).split('\n').filter(line => line.trim() !== '');
+ const mountPoint = df.length === 2 ? /^.+?\s+\d+\s+\d+\s+\d+\s+\d+%\s+(.+)$/.exec(df[1]!)?.[1] : undefined;
+ if (!mountPoint) return unknown();
+ const marker = ` on ${mountPoint} (`;
+ const lines = exec('/sbin/mount', []).split('\n').filter(line => line.endsWith(')') && line.includes(marker));
+ if (lines.length !== 1) return unknown();
+ const [type, ...flags] = lines[0]!.slice(lines[0]!.indexOf(marker) + marker.length, -1).split(',').map(part => part.trim());
+ if (!type) return unknown();
+ return flags.includes('local') && DARWIN_LOCAL_FILESYSTEMS.has(type) ? { type, magic: null, network: false } : unknown(type);
+ } catch { return unknown(); }
+}
+
function filesystemOf(dataDir: string, probe: LegacyLockProbe): LegacyLockEvidence['filesystem'] {
- if ((probe.platform ?? process.platform) !== 'linux') return { type: null, magic: null, network: null };
+ const platform = probe.platform ?? process.platform;
+ if (platform === 'darwin') return darwinFilesystemOf(dataDir, probe.exec ?? execNoShell);
+ if (platform !== 'linux') return { type: null, magic: null, network: null };
try {
const magic = (probe.statfs ?? statfsSync)(dataDir).type >>> 0;
const network = networkFilesystemName(magic);
@@ -160,8 +193,9 @@ function evidenceFor(dataDir: string, pid: number | null, recordedCommand: strin
return { evidence, refusal: { reason: 'network_filesystem', message: `The data dir is on a ${fs.type} filesystem that other hosts can mount; this host cannot see their processes.` } };
}
if (fs.network === null) {
- const why = platform !== 'linux' ? `gbrain reads filesystem locality only on Linux and this host runs ${platform}`
- : fs.type === null ? 'reading its filesystem type (statfs) failed' : `its filesystem type ${fs.type} is not one gbrain knows to be local`;
+ const why = platform !== 'linux' && platform !== 'darwin' ? `gbrain reads filesystem locality only on Linux and macOS and this host runs ${platform}`
+ : fs.type === null ? `reading its filesystem type (${platform === 'darwin' ? 'df and mount' : 'statfs'}) failed`
+ : `its filesystem ${fs.type} is not one gbrain can confirm is a local disk`;
return { evidence, refusal: { reason: 'filesystem_unverified', message: `gbrain could not confirm that the data dir is on a local filesystem (${why}), so another host sharing this folder could still hold the lock.` } };
}
return { evidence, refusal: null };
diff --git a/test/pathological/c3-pglite-legacy-lock.test.ts b/test/pathological/c3-pglite-legacy-lock.test.ts
index 82b7e5ac10..30d9e1b788 100644
--- a/test/pathological/c3-pglite-legacy-lock.test.ts
+++ b/test/pathological/c3-pglite-legacy-lock.test.ts
@@ -96,6 +96,26 @@ function repairWith(dataDir: string, opts: { dryRun?: boolean; expect?: string;
}
const removedDirs = (root: string) => readdirSync(root).filter(n => n.includes('.legacy-lock-removed-'));
+/** Real `/sbin/mount` output from a macOS 15 arm64 host, plus synthetic network lines. */
+const MAC_MOUNT = [
+ '/dev/disk3s1s1 on / (apfs, sealed, local, read-only, journaled)',
+ 'devfs on /dev (devfs, local, nobrowse)',
+ '/dev/disk3s5 on /System/Volumes/Data (apfs, local, journaled, nobrowse, protect, root data)',
+ 'map auto_home on /System/Volumes/Data/home (autofs, automounted, nobrowse)',
+ '/dev/disk4s1 on /Volumes/Capy 0.4.4-arm64 (hfs, local, nodev, nosuid, read-only, noowners, quarantine, mounted by garrytan)',
+].join('\n');
+const SMB_LINE = '//alice-example@nas/share on /Volumes/share (smbfs, nodev, nosuid, mounted by alice-example)';
+const NFS_LINE = 'nas-example:/export/brain on /Volumes/brain (nfs, nodev, nosuid, mounted by alice-example)';
+/** A darwin probe whose `df -P` puts the data dir on `mountPoint` and whose `mount` adds `extraLine`. */
+function macProbe(mountPoint: string, extraLine: string | null): LegacyLockProbe {
+ const df = `Filesystem 512-blocks Used Available Capacity Mounted on\n/dev/disk3s5 3896910480 1518591512 2313784664 40% ${mountPoint}\n`;
+ return { platform: 'darwin', exec: (file: string) => {
+ if (file === '/bin/df') return df;
+ if (file === '/sbin/mount') return `${MAC_MOUNT}${extraLine ? `\n${extraLine}` : ''}\n`;
+ throw new Error(`unexpected command ${file}`);
+ } };
+}
+
/** A child that keeps a file inside the data dir open, as a live pre-kernel gbrain would. */
async function liveHolder(dataDir: string): Promise<Bun.Subprocess> {
writeFileSync(join(dataDir, 'PG_VERSION'), '17\n');
@@ -326,7 +346,15 @@ describe('C-3 pglite-repair --legacy-lock: review fixes F4-F6', () => {
}
const UNKNOWN_LOCALITY: Array<[string, LegacyLockProbe]> = [
- ['a non-Linux platform', { platform: 'darwin' }],
+ ['a platform gbrain cannot probe', { platform: 'win32' }],
+ ['a macOS smbfs mount', macProbe('/Volumes/share', SMB_LINE)],
+ ['a macOS nfs mount', macProbe('/Volumes/brain', NFS_LINE)],
+ ['a macOS autofs home', macProbe('/System/Volumes/Data/home', 'map auto_home on /System/Volumes/Data/home (autofs, automounted, nobrowse)')],
+ ['a macOS apfs mount without the local flag', macProbe('/Volumes/remote', '/dev/disk9s1 on /Volumes/remote (apfs, nodev, nosuid)')],
+ ['a macOS local mount of a type gbrain does not know', macProbe('/dev', 'devfs on /dev (devfs, local, nobrowse)')],
+ ['a macOS mount point with no mount line', macProbe('/Volumes/gone', null)],
+ ['a macOS df output that does not parse', { platform: 'darwin', exec: (file: string) => file === '/bin/df' ? 'df: unexpected\n' : MAC_MOUNT }],
+ ['a macOS probe command that fails', { platform: 'darwin', exec: () => { throw new Error('spawn /bin/df ETIMEDOUT'); } }],
['a statfs probe that fails', { platform: 'linux', statfs: () => { throw Object.assign(new Error('EIO: i/o error, statfs'), { code: 'EIO' }); } }],
['an unrecognised filesystem type', { platform: 'linux', statfs: () => ({ type: 0x12345678 }) }],
];
@@ -349,6 +377,29 @@ describe('C-3 pglite-repair --legacy-lock: review fixes F4-F6', () => {
});
}
+ const MAC_LOCAL: Array<[string, string, string]> = [
+ ['the apfs data volume', '/System/Volumes/Data', 'apfs'],
+ ['an hfs volume whose mount point has spaces', '/Volumes/Capy 0.4.4-arm64', 'hfs'],
+ ];
+ for (const [label, mountPoint, type] of MAC_LOCAL) {
+ test(`F6 macOS: ${label} mounted local is removable, and the approved apply moves the lock`, async () => {
+ const root = temporary(), dataDir = join(root, 'store');
+ const dir = plantLegacyLock(dataDir, 'corrupt');
+ const calls: Array<[string, string[]]> = [];
+ const base = macProbe(mountPoint, null);
+ const probe: LegacyLockProbe = { platform: 'darwin', exec: (file, args) => { calls.push([file, [...args]]); return base.exec!(file, args); } };
+ await withEnv({ GBRAIN_HOME: join(root, 'home') }, async () => {
+ const shown = await repairWith(dataDir, { dryRun: true, probe });
+ expect({ type: shown.json.evidence?.filesystem?.type, network: shown.json.evidence?.filesystem?.network, removable: shown.json.removable, refusal: shown.json.refusal })
+ .toEqual({ type, network: false, removable: true, refusal: null });
+ expect(calls.slice(0, 2)).toEqual([['/bin/df', ['-P', dataDir]], ['/sbin/mount', []]]);
+ const done = await repairWith(dataDir, { expect: shown.json.plan_hash, probe });
+ expect({ code: done.code, action: done.json.action }).toEqual({ code: 0, action: 'removed' });
+ });
+ expect(existsSync(dir)).toBe(false);
+ });
+ }
+
test('F6: a recognised local Linux filesystem stays removable', async () => {
const root = temporary(), dataDir = join(root, 'store');
plantLegacyLock(dataDir, 'corrupt');