Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-130 PR 2: legacy-lock repair re-inspects after consent, undo restores the prior owner marker, unknown filesystem locality refuses (review F4-F6)

garrytanaced9e4f6cd7
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 812ffbb511..a02985d2a1 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -558,10 +558,16 @@ the same reason and fix on its `connection` check.
on this host holds the data dir or the recorded PID runs a command that
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`). A lock that changed since the preview refuses
- `preview_changed`. Otherwise it moves the folder into
+ (`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`.
+ 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
- `receipt.json` and the exact restore command, writes the kernel-v1 marker
+ `receipt.json` and the exact restore command (it also puts back the prior
+ `<data-dir>.gbrain-owner.json` bytes, kept as `prior-owner-marker.json`,
+ or removes the new marker when there was none), writes the kernel-v1 marker
`<data-dir>.gbrain-owner.json`, and starts the 10-minute WAL-repair
quarantine (`<data-dir>.lock-reap.json`). The next ordinary open succeeds.
diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.md
index 47882c00b2..390179a595 100644
--- a/docs/architecture/key-files/commands-4-continued.md
+++ b/docs/architecture/key-files/commands-4-continued.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
- `src/commands/persistence-delegate.ts` — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. `reportPersistenceCliError` owns the write exit verdict (`writeErrorExitCode` in `persistence/write-wait.ts`: pending exits 10 with `poll_command`, 0 with `--accept-pending`); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. `runDeferredPersistenceCommand` drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. `scripts/generate-flag-registry.ts` excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: `test/persistence-cli-delegation.test.ts`. #6255: a pending receipt's envelope carries the receipt fix, and `poll_command` plus the `Poll:` line are that same argv.
-- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Consent (C2) is `consentGate` (`src/core/consent-cli.ts`): `destructive`, bound to a `plan_hash` over the data dir, WAL segment names and a stale postmaster.pid (`--dry-run --json` reports it; approval is `--yes --expect <plan_hash>`, a bare `--yes` re-asks). The risk text (WAL tail may be lost, indexes not rebuilt, the `.wal-repair-backup-<ts>` folder, `restoreCommand`'s undo) is on stderr, in the payload and the dry run; the receipt adds `restore_command`. Non-TTY without approval exits 3; the TTY prompt is interaction.readLine (EOF = decline). `src/commands/reinit-pglite.ts` asks the same way (destructive, plan bound to the brain path and target model/width, the `.bak` restore command in the risk text; the `.bak` collision is refused before asking). The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`. `--legacy-lock` routes to `src/commands/pglite-repair-legacy-lock.ts` (`runLegacyLockRepair`): `--dry-run` prints `inspectLegacyLock` (`src/core/pglite-legacy-lock.ts`) with `apply_argv`, risk and user_message; apply takes `acquireKernelLockOnly` (5 s; busy → `pglite_busy` reason `timeout`), re-inspects under it, refuses `legacy_lock_removal_refused` (`live_holder` / `network_filesystem`, fix = the preview), asks `consentGate` (`destructive`, plan hash bound to the legacy lock; a changed lock refuses `preview_changed`), then applies and prints the receipt. Pinned by `test/pathological/c3-pglite-legacy-lock.test.ts`.
+- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Consent (C2) is `consentGate` (`src/core/consent-cli.ts`): `destructive`, bound to a `plan_hash` over the data dir, WAL segment names and a stale postmaster.pid (`--dry-run --json` reports it; approval is `--yes --expect <plan_hash>`, a bare `--yes` re-asks). The risk text (WAL tail may be lost, indexes not rebuilt, the `.wal-repair-backup-<ts>` folder, `restoreCommand`'s undo) is on stderr, in the payload and the dry run; the receipt adds `restore_command`. Non-TTY without approval exits 3; the TTY prompt is interaction.readLine (EOF = decline). `src/commands/reinit-pglite.ts` asks the same way (destructive, plan bound to the brain path and target model/width, the `.bak` restore command in the risk text; the `.bak` collision is refused before asking). The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`. `--legacy-lock` routes to `src/commands/pglite-repair-legacy-lock.ts` (`runLegacyLockRepair`): `--dry-run` prints `inspectLegacyLock` (`src/core/pglite-legacy-lock.ts`) with `apply_argv`, risk and user_message; apply takes `acquireKernelLockOnly` (5 s; busy → `pglite_busy` reason `timeout`), re-inspects under it, refuses `legacy_lock_removal_refused` (`live_holder` / `network_filesystem` / `filesystem_unverified`, fix = the preview), asks `consentGate` (`destructive`, plan hash bound to the legacy lock; a changed lock refuses `preview_changed`), inspects again after consent (refusal or a changed plan hash refuses; `consentEnv` / `probe` are test seams), then applies and prints the receipt. Pinned by `test/pathological/c3-pglite-legacy-lock.test.ts`.
- `src/commands/protocol.ts` — `gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]`. `--json` emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev `.ts` entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean `unavailable` error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.
- `src/commands/providers.ts` — `gbrain providers list | test [--touchpoint T] [--model ID] | env <id> | explain [--json]`: provider-recipe discovery + smoke-testing over the recipe registry. `list` renders `formatRecipeTable` against the SAME env the gateway actually sees (`buildGatewayConfig(cfg).env`, file-plane keys folded in) so the STATUS column matches what `providers test` and init would report. The pure `formatEnvOutput(recipe, env)` renders required keys, setup hints and endpoints; `explain --json` returns the recipe capability matrix without exposing key values. Pinned by `test/providers.test.ts`.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index e7bc4c1ff7..623d417a2b 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`) and `applyLegacyLockRemoval` (moves the dir aside with a receipt, writes the kernel-v1 marker). 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: 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-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 55acb70651..cfed93e76a 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2084,9 +2084,9 @@ 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, or the data dir is on a network or shared filesystem. | 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, 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. | 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 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 |
-Reasons: `live_holder`, `network_filesystem`.
+Reasons: `live_holder`, `network_filesystem`, `filesystem_unverified`.
More: [docs/ENGINES.md#legacy-pglite-lock](../../docs/ENGINES.md#legacy-pglite-lock)
diff --git a/llms-full.txt b/llms-full.txt
index 419448feba..b51afbeebf 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5843,10 +5843,16 @@ the same reason and fix on its `connection` check.
on this host holds the data dir or the recorded PID runs a command that
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`). A lock that changed since the preview refuses
- `preview_changed`. Otherwise it moves the folder into
+ (`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`.
+ 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
- `receipt.json` and the exact restore command, writes the kernel-v1 marker
+ `receipt.json` and the exact restore command (it also puts back the prior
+ `<data-dir>.gbrain-owner.json` bytes, kept as `prior-owner-marker.json`,
+ or removes the new marker when there was none), writes the kernel-v1 marker
`<data-dir>.gbrain-owner.json`, and starts the 10-minute WAL-repair
quarantine (`<data-dir>.lock-reap.json`). The next ordinary open succeeds.
diff --git a/src/commands/pglite-repair-legacy-lock.ts b/src/commands/pglite-repair-legacy-lock.ts
index 2c0345c115..7af3748548 100644
--- a/src/commands/pglite-repair-legacy-lock.ts
+++ b/src/commands/pglite-repair-legacy-lock.ts
@@ -6,17 +6,21 @@
* --dry-run read-only: the verdict, the advisory evidence and the plan_hash.
* apply takes the stable sibling kernel lock (no kernel-v1 process can be
* live while it is held), re-inspects under it, refuses a live
- * holder or a network filesystem (`legacy_lock_removal_refused`),
- * asks for consent bound to the plan hash (`--yes --expect`; a
- * changed lock refuses `preview_changed`), then moves the legacy
- * dir aside and writes the kernel-v1 marker (core/pglite-legacy-lock.ts).
+ * holder, a network filesystem or one whose locality it cannot
+ * read (`legacy_lock_removal_refused`), asks for consent bound
+ * to the plan hash (`--yes --expect`), inspects again after
+ * consent (a holder or change that appeared while the prompt
+ * waited refuses; a changed plan refuses `preview_changed`), then
+ * moves the legacy dir aside and writes the kernel-v1 marker
+ * (core/pglite-legacy-lock.ts).
*/
import { shellQuote, type Action } from '../core/agent-output.ts';
import { currentExitCode, writeJsonDocument } from '../core/cli-force-exit.ts';
import { consentGate } from '../core/consent-cli.ts';
+import type { ConsentEnv } from '../core/consent.ts';
import { opError, OperationError } from '../core/ops/contract.ts';
import { acquireKernelLockOnly, PgliteBusyError, releaseLock, type LockHandle } from '../core/pglite-lock.ts';
-import { applyLegacyLockRemoval, inspectLegacyLock, type LegacyLockInspection } from '../core/pglite-legacy-lock.ts';
+import { applyLegacyLockRemoval, inspectLegacyLock, type LegacyLockInspection, type LegacyLockProbe } from '../core/pglite-legacy-lock.ts';
import { writeCliError } from '../cli/cli-error.ts';
const RISK = 'The legacy lock folder is moved into a sibling <data-dir>.legacy-lock-removed-<timestamp> folder with a receipt and the exact restore command; nothing is deleted. '
@@ -63,14 +67,19 @@ function printPreview(i: LegacyLockInspection, json: boolean): number {
function refuse(i: LegacyLockInspection, json: boolean): number {
const refusal = i.refusal!;
- const e = opError('legacy_lock_removal_refused', `${refusal.message} The legacy lock at ${i.legacy_lock.dir} was left in place.`,
- '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 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.'
+ : '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) });
return writeCliError(e, 'pglite-repair', { json, emit: emitText });
}
-async function applyUnderKernelLock(dataDir: string, json: boolean, args: readonly string[]): Promise<number> {
- const inspection = inspectLegacyLock(dataDir);
+interface LegacyLockRepairOpts { dryRun: boolean; json: boolean; args: readonly string[]; consentEnv?: ConsentEnv; probe?: LegacyLockProbe }
+
+async function applyUnderKernelLock(dataDir: string, opts: LegacyLockRepairOpts): Promise<number> {
+ const { json, args } = opts;
+ const inspection = inspectLegacyLock(dataDir, opts.probe);
if (!inspection.legacy_lock.legacy) {
emit({ status: 'ok', action: 'none', data_dir: inspection.data_dir, verdict: inspection.legacy_lock.verdict });
return 0;
@@ -83,16 +92,22 @@ async function applyUnderKernelLock(dataDir: string, json: boolean, args: readon
risk: RISK, user_message: userMessage(inspection),
argv: applyArgv(inspection.data_dir), preview_argv: previewArgv(inspection.data_dir),
plan_hash: inspection.plan_hash!, selection: inspection.selection, args,
- }, { json });
+ }, { json, env: opts.consentEnv });
if (!auth) return currentExitCode();
- const receipt = applyLegacyLockRemoval(inspection);
+ const fresh = inspectLegacyLock(dataDir, opts.probe);
+ if (fresh.refusal) return refuse(fresh, json);
+ if (fresh.plan_hash !== inspection.plan_hash) {
+ throw opError('preview_changed', `The legacy lock of ${inspection.data_dir} changed while consent was pending (approved plan ${inspection.plan_hash}, current plan ${fresh.plan_hash ?? 'none'}); nothing was changed.`,
+ 'Preview again, show the user the new plan, and re-run with the new --expect value only if they approve it.', { fix: previewFix(inspection.data_dir) });
+ }
+ const receipt = applyLegacyLockRemoval(fresh);
if (json) emit({ status: 'ok', ...receipt, next_command: 'gbrain doctor --json' });
else console.log(`Moved the legacy lock of ${receipt.data_dir} to ${receipt.moved_to} and wrote the kernel-v1 marker.\n Undo (once no process has the brain open): ${receipt.restore_command}\n Next: gbrain doctor --json`);
return 0;
}
-export async function runLegacyLockRepair(dataDir: string, opts: { dryRun: boolean; json: boolean; args: readonly string[] }): Promise<number> {
- const inspection = inspectLegacyLock(dataDir);
+export async function runLegacyLockRepair(dataDir: string, opts: LegacyLockRepairOpts): Promise<number> {
+ const inspection = inspectLegacyLock(dataDir, opts.probe);
if (opts.dryRun) return printPreview(inspection, opts.json);
if (!inspection.legacy_lock.legacy) {
if (opts.json) emit({ status: 'ok', action: 'none', data_dir: inspection.data_dir, verdict: inspection.legacy_lock.verdict });
@@ -109,7 +124,7 @@ export async function runLegacyLockRepair(dataDir: string, opts: { dryRun: boole
return writeCliError(e, 'pglite-repair', { json: opts.json, emit: emitText });
}
try {
- return await applyUnderKernelLock(inspection.data_dir, opts.json, opts.args);
+ return await applyUnderKernelLock(inspection.data_dir, opts);
} catch (error) {
if (!(error instanceof OperationError)) throw error;
return writeCliError(error, 'pglite-repair', { json: opts.json, emit: emitText });
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index dbc9cc1e5b..5a50706ebf 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, or the data dir is on a network or shared filesystem.", 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, means the old owner may still be writing, and removing its lock would let two writers corrupt the brain.", reasons: ['live_holder', 'network_filesystem'], 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.' },
+ 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.' },
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 3a4417f956..0e16ad744e 100644
--- a/src/core/pglite-legacy-lock.ts
+++ b/src/core/pglite-legacy-lock.ts
@@ -12,15 +12,19 @@
* statfs). 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)
- * or a network/shared filesystem makes the lock not removable.
+ * 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
+ * not removable.
*
* `applyLegacyLockRemoval` runs only under the stable sibling kernel lock and
* after consent bound to the plan hash: it moves the legacy dir into a sibling
* `<data-dir>.legacy-lock-removed-<ts>/` (nothing is deleted), writes the
* kernel-v1 marker the normal path writes, starts the 10-minute WAL-repair
* quarantine (`<data-dir>.lock-reap.json`, read by `msSinceLastReap`) and
- * leaves a receipt with the exact restore command.
+ * leaves a receipt with the exact restore command, which also puts back the
+ * prior ownership marker's exact bytes (or removes the new marker when there
+ * was none), so an undo restores the original refusal.
*/
import { createHash } from 'node:crypto';
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, statfsSync, writeFileSync } from 'node:fs';
@@ -37,6 +41,8 @@ const NETWORK_FILESYSTEMS: Readonly<Record<number, string>> = {
};
const LOCAL_FILESYSTEMS: Readonly<Record<number, string>> = {
0xef53: 'ext4', 0x58465342: 'xfs', 0x9123683e: 'btrfs', 0x01021994: 'tmpfs', 0x794c7630: 'overlay', 0x2fc12fc1: 'zfs', 0xf2f52010: 'f2fs',
+ 0xca451a4e: 'bcachefs', 0x4d44: 'vfat', 0x2011bab0: 'exfat', 0x5346544e: 'ntfs', 0x7366746e: 'ntfs3', 0x482b: 'hfsplus', 0x858458f6: 'ramfs',
+ 0x52654973: 'reiserfs', 0x3153464a: 'jfs', 0x3434: 'nilfs',
};
export function networkFilesystemName(magic: number): string | null {
return NETWORK_FILESYSTEMS[magic >>> 0] ?? null;
@@ -52,6 +58,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. */
filesystem: { type: string | null; magic: number | null; network: boolean | null };
}
@@ -67,7 +74,7 @@ export interface LegacyLockInspection {
metadata: { pid: number | null; command: string | null; acquired_at: number | null; pid_ns: string | null; boot_id: string | null } | null;
};
evidence: LegacyLockEvidence | null;
- refusal: { reason: 'live_holder' | 'network_filesystem'; message: string } | null;
+ refusal: { reason: 'live_holder' | 'network_filesystem' | 'filesystem_unverified'; message: string } | null;
removable: boolean;
plan_hash: string | null;
selection: PlanSelection | null;
@@ -76,8 +83,14 @@ export interface LegacyLockInspection {
const sha256 = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex');
const markerPathOf = (dataDir: string) => `${dataDir}.gbrain-owner.json`;
-function scanOpenFiles(dataDir: string): LegacyLockEvidence['fd_scan'] {
- if (process.platform !== 'linux' || !existsSync('/proc/self/fd')) return { method: 'unavailable', holders: [], uninspectable: 0 };
+/** Test seam for the host probes; production reads the real platform and statfs. */
+export interface LegacyLockProbe {
+ platform?: NodeJS.Platform;
+ statfs?: (path: string) => { type: number };
+}
+
+function scanOpenFiles(dataDir: string, platform: NodeJS.Platform): LegacyLockEvidence['fd_scan'] {
+ if (platform !== 'linux' || !existsSync('/proc/self/fd')) return { method: 'unavailable', holders: [], uninspectable: 0 };
const holders: LegacyLockEvidence['fd_scan']['holders'] = [];
let uninspectable = 0;
for (const entry of readdirSync('/proc')) {
@@ -99,12 +112,13 @@ function scanOpenFiles(dataDir: string): LegacyLockEvidence['fd_scan'] {
return { method: 'proc', holders, uninspectable };
}
-function filesystemOf(dataDir: string): LegacyLockEvidence['filesystem'] {
- if (process.platform !== 'linux') return { type: null, magic: null, network: null };
+function filesystemOf(dataDir: string, probe: LegacyLockProbe): LegacyLockEvidence['filesystem'] {
+ if ((probe.platform ?? process.platform) !== 'linux') return { type: null, magic: null, network: null };
try {
- const magic = statfsSync(dataDir).type >>> 0;
+ const magic = (probe.statfs ?? statfsSync)(dataDir).type >>> 0;
const network = networkFilesystemName(magic);
- return { type: network ?? LOCAL_FILESYSTEMS[magic] ?? `0x${magic.toString(16)}`, magic, network: network !== null };
+ const local = LOCAL_FILESYSTEMS[magic];
+ return { type: network ?? local ?? `0x${magic.toString(16)}`, magic, network: network !== null ? true : local ? false : null };
} catch { return { type: null, magic: null, network: null }; }
}
@@ -131,24 +145,30 @@ function planSelection(dataDir: string, lockDir: string): PlanSelection {
};
}
-function evidenceFor(dataDir: string, pid: number | null, recordedCommand: string | null, verdict: LegacyLockInspection['legacy_lock']['verdict']): { evidence: LegacyLockEvidence; refusal: LegacyLockInspection['refusal'] } {
+function evidenceFor(dataDir: string, pid: number | null, recordedCommand: string | null, verdict: LegacyLockInspection['legacy_lock']['verdict'], probe: LegacyLockProbe): { evidence: LegacyLockEvidence; refusal: LegacyLockInspection['refusal'] } {
const pidAlive = pid === null ? null : isProcessAlive(pid);
const pidCommand = pid !== null && pidAlive ? readProcessArgs(pid)?.slice(0, 200) ?? null : null;
const evidence: LegacyLockEvidence = { advisory: true, scope: LEGACY_LOCK_EVIDENCE_SCOPE, pid, pid_alive: pidAlive, pid_command: pidCommand,
- fd_scan: scanOpenFiles(dataDir), filesystem: filesystemOf(dataDir) };
+ fd_scan: scanOpenFiles(dataDir, probe.platform ?? process.platform), filesystem: filesystemOf(dataDir, probe) };
const holder = evidence.fd_scan.holders[0];
if (holder) return { evidence, refusal: { reason: 'live_holder', message: `Process ${holder.pid} (${holder.command ?? 'command unreadable'}) has ${holder.paths[0]} open, so the data dir is still in use on this host.` } };
if (pidAlive && (verdict === 'live' || couldBeOwner(pidCommand, recordedCommand))) {
return { evidence, refusal: { reason: 'live_holder', message: `The recorded legacy PID ${pid} is running (${pidCommand ?? 'command unreadable'}) and may still be the old gbrain.` } };
}
- if (evidence.filesystem.network) {
- return { evidence, refusal: { reason: 'network_filesystem', message: `The data dir is on a ${evidence.filesystem.type} filesystem that other hosts can mount; this host cannot see their processes.` } };
+ const fs = evidence.filesystem, platform = probe.platform ?? process.platform;
+ if (fs.network) {
+ 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`;
+ 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 };
}
/** Read-only: never creates the data dir, the legacy dir or the kernel lock. */
-export function inspectLegacyLock(path: string): LegacyLockInspection {
+export function inspectLegacyLock(path: string, probe: LegacyLockProbe = {}): LegacyLockInspection {
const lockDir = pgliteLockDirFor(path), dataDir = dirname(lockDir);
const present = existsSync(lockDir) && lstatSync(lockDir).isDirectory();
let migrated = false;
@@ -159,7 +179,7 @@ export function inspectLegacyLock(path: string): LegacyLockInspection {
const pid = Number.isInteger(metadata?.pid) && metadata!.pid! > 0 ? metadata!.pid! : null;
const verdict = !present ? 'absent' : !legacy ? 'current' : reason ? 'unverified' : isProcessAlive(pid!) ? 'live' : 'dead';
const recordedCommand = typeof metadata?.command === 'string' ? metadata.command : null;
- const { evidence, refusal } = legacy ? evidenceFor(dataDir, pid, recordedCommand, verdict) : { evidence: null, refusal: null };
+ const { evidence, refusal } = legacy ? evidenceFor(dataDir, pid, recordedCommand, verdict, probe) : { evidence: null, refusal: null };
const selection = legacy ? planSelection(dataDir, lockDir) : null;
return {
data_dir: dataDir,
@@ -177,6 +197,8 @@ export interface LegacyLockRemovalReceipt {
moved_to: string;
marker_path: string;
prior_marker: string | null;
+ /** Exact bytes of the prior ownership marker, restored by `restore_command`; null when there was none (the undo removes the new marker). */
+ prior_marker_backup: string | null;
plan_hash: string;
removed_at: string;
evidence: LegacyLockEvidence | null;
@@ -187,14 +209,20 @@ export interface LegacyLockRemovalReceipt {
export function applyLegacyLockRemoval(inspection: LegacyLockInspection, now = new Date()): LegacyLockRemovalReceipt {
const { data_dir: dataDir, legacy_lock: { dir: lockDir } } = inspection;
const markerPath = markerPathOf(dataDir);
- const priorMarker = existsSync(markerPath) ? readFileSync(markerPath, 'utf8') : null;
+ const priorBytes = existsSync(markerPath) ? readFileSync(markerPath) : null;
const movedTo = `${dataDir}.legacy-lock-removed-${now.toISOString().replace(/[:.]/g, '-')}`;
mkdirSync(movedTo, { mode: 0o700 });
+ const priorBackup = priorBytes === null ? null : join(movedTo, 'prior-owner-marker.json');
+ if (priorBackup) writeFileSync(priorBackup, priorBytes!, { mode: 0o600 });
renameSync(lockDir, join(movedTo, '.gbrain-lock'));
writeFileSync(markerPath, JSON.stringify({ protocol: PGLITE_LOCK_PROTOCOL }), { mode: 0o600 });
writeFileSync(`${dataDir}.lock-reap.json`, JSON.stringify({ ts: now.getTime(), reason: 'legacy_lock_removed' }), { mode: 0o600 });
- const restore = [shellQuote(['mv', join(movedTo, '.gbrain-lock'), lockDir]), ...(priorMarker === null ? [shellQuote(['rm', '-f', markerPath])] : [])].join(' && ');
- const receipt: LegacyLockRemovalReceipt = { action: 'removed', data_dir: dataDir, moved_to: movedTo, marker_path: markerPath, prior_marker: priorMarker,
+ const restoring = `${markerPath}.restore`;
+ const markerUndo = priorBackup === null ? [shellQuote(['rm', '-f', markerPath])]
+ : [shellQuote(['cp', priorBackup, restoring]), shellQuote(['mv', '-f', restoring, markerPath])];
+ const restore = [shellQuote(['mv', join(movedTo, '.gbrain-lock'), lockDir]), ...markerUndo].join(' && ');
+ const receipt: LegacyLockRemovalReceipt = { action: 'removed', data_dir: dataDir, moved_to: movedTo, marker_path: markerPath,
+ prior_marker: priorBytes === null ? null : priorBytes.toString('utf8'), prior_marker_backup: priorBackup,
plan_hash: inspection.plan_hash!, removed_at: now.toISOString(), evidence: inspection.evidence, restore_command: restore };
writeFileSync(join(movedTo, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 });
return receipt;
diff --git a/test/pathological/c3-pglite-legacy-lock.test.ts b/test/pathological/c3-pglite-legacy-lock.test.ts
index 67ee51c970..82b7e5ac10 100644
--- a/test/pathological/c3-pglite-legacy-lock.test.ts
+++ b/test/pathological/c3-pglite-legacy-lock.test.ts
@@ -20,7 +20,14 @@
* other than the one previewed.
* Why new: test/pglite-lock.test.ts pins only that ambiguous legacy ownership
* is refused; nothing covered the exit.
- * Seams: none (the filesystem classifier is exercised directly).
+ * Review fixes (F4-F6): a holder that appears while the consent prompt
+ * waits is refused after consent (re-inspected, plan hash re-compared); the
+ * emitted undo restores the exact prior ownership marker bytes, so an empty or
+ * torn marker brings the original refusal back; a filesystem whose locality
+ * cannot be read (non-Linux, a failing statfs, an unrecognised type) refuses
+ * `filesystem_unverified` instead of passing as local.
+ * Seams: the consent prompt (`consentEnv.readLine`) and the host probes
+ * (`probe.platform` / `probe.statfs`) of runLegacyLockRepair.
*/
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
@@ -30,6 +37,10 @@ import { setTimeout as delay } from 'node:timers/promises';
import { acquireLock, releaseLock, PgliteBusyError } from '../../src/core/pglite-lock.ts';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { runPgliteRepair } from '../../src/commands/pglite-repair.ts';
+import { runLegacyLockRepair } from '../../src/commands/pglite-repair-legacy-lock.ts';
+import { _resetCliExitVerdictForTests } from '../../src/core/cli-force-exit.ts';
+import type { ConsentEnv } from '../../src/core/consent.ts';
+import type { LegacyLockProbe } from '../../src/core/pglite-legacy-lock.ts';
import { deadPid } from '../helpers/dead-pid.ts';
import { withEnv } from '../helpers/with-env.ts';
import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, renderFix, snapshotItems } from './harness.ts';
@@ -38,6 +49,7 @@ const roots: string[] = [];
const children: Bun.Subprocess[] = [];
function temporary(): string { const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-c3-'))); roots.push(root); return root; }
afterEach(async () => {
+ _resetCliExitVerdictForTests(); process.exitCode = 0;
for (const child of children.splice(0)) { if (child.exitCode === null) child.kill(9); await child.exited; }
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
});
@@ -63,20 +75,26 @@ async function refusalOf(dataDir: string): Promise<PgliteBusyError & { fix?: unk
return thrown as PgliteBusyError & { fix?: unknown };
}
-async function repair(args: string[]): Promise<{ code: number; json: Record<string, any> }> {
+async function repair(args: string[], run: () => Promise<number> = () => runPgliteRepair(args)): Promise<{ code: number; json: Record<string, any> }> {
const logs: string[] = [];
const log = console.log, err = console.error, write = process.stderr.write;
console.log = (...a: unknown[]) => { logs.push(a.map(String).join(' ')); };
console.error = () => {};
process.stderr.write = (() => true) as typeof process.stderr.write;
let code: number;
- try { code = await runPgliteRepair(args); } finally { console.log = log; console.error = err; process.stderr.write = write; }
+ try { code = await run(); } finally { console.log = log; console.error = err; process.stderr.write = write; }
const line = [...logs].reverse().find(l => l.trim().startsWith('{'));
expect({ args, line: line ? 'json' : logs.join('\n') }).toEqual({ args, line: 'json' });
return { code, json: JSON.parse(line!) };
}
const preview = (dataDir: string) => repair(['--legacy-lock', '--path', dataDir, '--dry-run', '--json']);
const apply = (dataDir: string, hash: string) => repair(['--legacy-lock', '--path', dataDir, '--yes', '--expect', hash, '--json']);
+/** The command with its seams: an interactive prompt answered by `readLine`, and injected host probes. */
+function repairWith(dataDir: string, opts: { dryRun?: boolean; expect?: string; consentEnv?: ConsentEnv; probe?: LegacyLockProbe }) {
+ const args = ['--legacy-lock', '--path', dataDir, ...(opts.expect ? ['--yes', '--expect', opts.expect] : []), '--json'];
+ return repair(args, () => runLegacyLockRepair(dataDir, { dryRun: opts.dryRun ?? false, json: true, args, consentEnv: opts.consentEnv, probe: opts.probe }));
+}
+const removedDirs = (root: string) => readdirSync(root).filter(n => n.includes('.legacy-lock-removed-'));
/** 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> {
@@ -236,3 +254,108 @@ describe('C-3 pglite-repair --legacy-lock refusals', () => {
expect(statSync(dir).isDirectory()).toBe(true);
});
});
+
+describe('C-3 pglite-repair --legacy-lock: review fixes F4-F6', () => {
+ test('F4: a pre-kernel holder that appears while the consent prompt waits is refused after consent and the lock is untouched', async () => {
+ if (process.platform !== 'linux') return;
+ const root = temporary(), dataDir = join(root, 'store');
+ const dir = plantLegacyLock(dataDir, 'corrupt');
+ let holder: Bun.Subprocess | undefined;
+ const consentEnv: ConsentEnv = { interactive: true, readLine: async () => {
+ holder = await liveHolder(dataDir);
+ writeFileSync(join(dir, 'lock'), JSON.stringify({ pid: holder.pid, acquired_at: Date.now(), command: 'gbrain sync' }));
+ return { kind: 'line', text: 'y' };
+ } };
+ await withEnv({ GBRAIN_HOME: join(root, 'home') }, async () => {
+ const refused = await repairWith(dataDir, { consentEnv });
+ expect(holder).toBeDefined();
+ expect({ code: refused.code, error: refused.json.code, reason: refused.json.reason, action: refused.json.action })
+ .toEqual({ code: 1, error: 'legacy_lock_removal_refused', reason: 'live_holder', action: undefined });
+ expect(refused.json.fix?.command).toBe(`gbrain pglite-repair --legacy-lock --path ${dataDir} --dry-run --json`);
+ });
+ expect(readFileSync(join(dir, 'lock'), 'utf8')).toContain(String(holder!.pid));
+ expect(existsSync(`${dataDir}.gbrain-owner.json`)).toBe(false);
+ expect(removedDirs(root)).toEqual([]);
+ }, 30_000);
+
+ test('F4: a lock that changes while the consent prompt waits refuses preview_changed after consent and removes nothing', async () => {
+ const root = temporary(), dataDir = join(root, 'store');
+ const dir = plantLegacyLock(dataDir, 'corrupt');
+ let asked = 0;
+ const consentEnv: ConsentEnv = { interactive: true, readLine: async () => {
+ asked++;
+ writeFileSync(join(dir, 'lock'), '{torn by a pre-kernel writer');
+ return { kind: 'line', text: 'y' };
+ } };
+ await withEnv({ GBRAIN_HOME: join(root, 'home') }, async () => {
+ const refused = await repairWith(dataDir, { consentEnv });
+ expect({ asked, code: refused.code, error: refused.json.code }).toEqual({ asked: 1, code: 1, error: 'preview_changed' });
+ expect(refused.json.fix?.command).toBe(`gbrain pglite-repair --legacy-lock --path ${dataDir} --dry-run --json`);
+ });
+ expect(readFileSync(join(dir, 'lock'), 'utf8')).toBe('{torn by a pre-kernel writer');
+ expect(existsSync(`${dataDir}.gbrain-owner.json`)).toBe(false);
+ expect(removedDirs(root)).toEqual([]);
+ });
+
+ const PRIOR_MARKERS: Array<[string, string | null]> = [['an empty', ''], ['a torn', '{"protocol":"kern'], ['no', null]];
+ for (const [label, prior] of PRIOR_MARKERS) {
+ test(`F5: with ${label} prior ownership marker, the emitted undo brings back the original refusal`, async () => {
+ const root = temporary(), dataDir = join(root, 'store'), marker = `${dataDir}.gbrain-owner.json`;
+ plantLegacyLock(dataDir, 'corrupt');
+ if (prior !== null) writeFileSync(marker, prior);
+ expect((await refusalOf(dataDir)).reason).toBe('legacy_owner_unverified');
+ await withEnv({ GBRAIN_HOME: join(root, 'home') }, async () => {
+ const shown = await preview(dataDir);
+ expect({ verdict: shown.json.legacy_lock?.verdict, reason: shown.json.legacy_lock?.reason, removable: shown.json.removable })
+ .toEqual({ verdict: 'unverified', reason: 'metadata_unreadable', removable: true });
+ const done = await apply(dataDir, shown.json.plan_hash);
+ expect({ code: done.code, action: done.json.action }).toEqual({ code: 0, action: 'removed' });
+ expect(JSON.parse(readFileSync(marker, 'utf8')).protocol).toBe('kernel-v1');
+
+ const undo = Bun.spawnSync(['sh', '-c', done.json.restore_command], { stdout: 'pipe', stderr: 'pipe' });
+ expect({ exit: undo.exitCode, stderr: undo.stderr.toString() }).toEqual({ exit: 0, stderr: '' });
+ expect(prior === null ? existsSync(marker) : readFileSync(marker, 'utf8')).toBe(prior === null ? false : prior);
+ const again = await preview(dataDir);
+ expect({ legacy: again.json.legacy_lock?.legacy, verdict: again.json.legacy_lock?.verdict, reason: again.json.legacy_lock?.reason })
+ .toEqual({ legacy: true, verdict: 'unverified', reason: 'metadata_unreadable' });
+ expect(again.json.plan_hash).toBe(shown.json.plan_hash);
+ });
+ expect(readFileSync(join(dataDir, '.gbrain-lock', 'lock'), 'utf8')).toBe('{corrupt');
+ expect((await refusalOf(dataDir)).reason).toBe('legacy_owner_unverified');
+ });
+ }
+
+ const UNKNOWN_LOCALITY: Array<[string, LegacyLockProbe]> = [
+ ['a non-Linux platform', { platform: 'darwin' }],
+ ['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 }) }],
+ ];
+ for (const [label, probe] of UNKNOWN_LOCALITY) {
+ test(`F6: ${label} leaves locality unknown, so preview and the approved apply refuse filesystem_unverified`, async () => {
+ const root = temporary(), dataDir = join(root, 'store');
+ const dir = plantLegacyLock(dataDir, 'corrupt');
+ await withEnv({ GBRAIN_HOME: join(root, 'home') }, async () => {
+ const shown = await repairWith(dataDir, { dryRun: true, probe });
+ expect({ network: shown.json.evidence?.filesystem?.network, removable: shown.json.removable, refusal: shown.json.refusal?.reason, apply: shown.json.apply_argv })
+ .toEqual({ network: null, removable: false, refusal: 'filesystem_unverified', apply: undefined });
+ const refused = await repairWith(dataDir, { expect: shown.json.plan_hash, probe });
+ expect({ code: refused.code, error: refused.json.code, reason: refused.json.reason })
+ .toEqual({ code: 1, error: 'legacy_lock_removal_refused', reason: 'filesystem_unverified' });
+ expect(refused.json.message).toMatch(/could not confirm that the data dir is on a local filesystem/);
+ });
+ expect(readFileSync(join(dir, 'lock'), 'utf8')).toBe('{corrupt');
+ expect(existsSync(`${dataDir}.gbrain-owner.json`)).toBe(false);
+ expect(removedDirs(root)).toEqual([]);
+ });
+ }
+
+ test('F6: a recognised local Linux filesystem stays removable', async () => {
+ const root = temporary(), dataDir = join(root, 'store');
+ plantLegacyLock(dataDir, 'corrupt');
+ await withEnv({ GBRAIN_HOME: join(root, 'home') }, async () => {
+ const shown = await repairWith(dataDir, { dryRun: true, probe: { platform: 'linux', statfs: () => ({ type: 0xef53 }) } });
+ expect({ type: shown.json.evidence?.filesystem?.type, network: shown.json.evidence?.filesystem?.network, removable: shown.json.removable })
+ .toEqual({ type: 'ext4', network: false, removable: true });
+ });
+ });
+});