Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(pglite): an unverifiable legacy lock refuses legacy_owner_unverified with a preview-first exit (C-3)

garrytane601286e6346
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 570f3ef369..812ffbb511 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -525,6 +525,46 @@ to connect: it diagnoses the dir from disk, names the repair command, reports
retained repair backups, and escalates when repairs keep recurring (that
means the unclean-shutdown genesis is still active — see the ladder's rung 4).
+<a id="legacy-pglite-lock"></a>
+### Legacy PGLite lock (`pglite_busy` reason `legacy_owner_unverified`)
+
+A PGLite brain is owned through the stable sibling kernel lock
+`<data-dir>.gbrain-owner.lock`. Brains last opened by an older gbrain may
+still hold that release's lock folder, `<data-dir>/.gbrain-lock/`. The first
+open by a current gbrain removes it automatically only when it can prove the
+old owner is dead: readable metadata with a PID that `kill -0` reports gone
+and, on Linux, the same PID namespace and boot id as this process. A live
+owner keeps the ordinary `pglite_busy` refusal.
+
+When the folder's metadata is torn or missing, records no PID, or (Linux) does
+not prove the PID ran in this namespace since the last boot, waiting never
+helps, so the open refuses `pglite_busy` with reason
+`legacy_owner_unverified` (class consent, exit 3, not retryable). Its fix
+asks the user and starts with the read-only preview; `gbrain doctor` shows
+the same reason and fix on its `connection` check.
+
+1. **Preview.** `gbrain pglite-repair --legacy-lock --dry-run --json [--path <dir>]`
+ 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
+ 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.
+2. **Apply, after the user agrees.**
+ `gbrain pglite-repair --legacy-lock --path <dir> --yes --expect <plan_hash>`
+ takes the kernel lock (so no current gbrain can be running), inspects
+ again under it and refuses `legacy_lock_removal_refused` while a process
+ 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
+ `<data-dir>.legacy-lock-removed-<timestamp>/` (nothing is deleted) with a
+ `receipt.json` and the exact restore command, 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.
+
## Canonical schema sources
Schema DDL text has one hand-edited copy. `bun run build:schema`
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 92fb8cc390..9669644346 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -39,7 +39,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers the façade: re-exports, `Check`/`DoctorReport` and report scoring, the `buildChecks` flag parse, `runDoctor`, output rendering and `--locks`; every check block lives in a registry entry under `doctor/checks/*` (refactor wave 1 W4 doctor), remediation in `doctor/remediate.ts`, wave checks in `doctor/wave-checks.ts`.
- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json`, Codex `config.toml` and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. #6453: with no PGLite lock, an HTTP registration gets a credential-free 3 s GET of `/health` (`probeHttpRegistration`): gbrain `ok` → `wired_running` + `mcp_access: 'unverified'`; refused loopback `http:` → `http_serve_missing` + fix; else `http_serve_unreachable`/`http_serve_unhealthy`, no fix. `redactRegistrationUrl` strips userinfo, query and fragment from every printed URL (`test/harness-wiring-redaction-6453.test.ts`). `agent_contract` reads `readAgentContractEvents()` (7 days) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). `harness_wiring` with no registration drops every detected harness an enabled plugin lane covers (`enabledPluginLanes`): all covered → `ok`, `reason: plugin_lane_enabled` with the plugins, harnesses and a verify hint (plugin lanes are not smoke-tested); partly covered → the missing-registration warning for the uncovered harnesses only. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.
-- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). A pre-gate entry declares the names it only emits with a connected engine in `engineChecks` (#6303), so `onlyNeedsEngine` connects for `--only` of them; `test/doctor-only-engine-checks.test.ts` is the drift guard. To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
+- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` — a live serve owner warns with the exclusive two-step fix, a `pglite_busy` reason `legacy_owner_unverified` fails with details.reason and the refusal's ask_user preview fix, anything else is classified for `db-repair` — and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). A pre-gate entry declares the names it only emits with a connected engine in `engineChecks` (#6303), so `onlyNeedsEngine` connects for `--only` of them; `test/doctor-only-engine-checks.test.ts` is the drift guard. To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run, cursor in config `doctor.timeline_history.scan:<sources>` so runs finish a pass (a clean pass stays `ok` until a newer row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, non-round-trippable rows informational, repair `gbrain repair timeline`; segmented pages counted apart (`segmented_*`), no repair advice), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). It drops every walked path sync would refuse (`unsyncableReason(prefix + relPath)`: metafiles such as root `AGENTS.md`/`CLAUDE.md`, pruned dirs, malformed names) before probing, so a same-slug page on `default` is not reported for a file sync never imports (#6681). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. `graph_coverage` and `orphan_ratio` count the entity types the active schema pack declares (#4772, `src/core/schema-pack/entity-types.ts`, resolved per source: brain-wide for `graph_coverage`, the asked source for `orphan_ratio --source`); a pack that does not load makes `graph_coverage` a warn naming the pack (never the old hardcoded list) and `orphan_ratio` answers with an "entity count unknown" caveat instead of a vacuous ok. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.
diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.md
index b190c665b5..ac41d17e8b 100644
--- a/docs/architecture/key-files/commands-4-continued.md
+++ b/docs/architecture/key-files/commands-4-continued.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md) · [Previous entries](commands-4.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `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`.
+- `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/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 087942425f..e7bc4c1ff7 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -39,9 +39,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/pglite-lifecycle.ts` — tracks admitted datastore statements and transactions across early-null, rejects new work through captured handles, and supplies the typed closing error. A successful same-datastore reopen resumes its stopped persistence consumer only after database open and filesystem-registry success; replaced or disposed services unregister their lifecycle hooks. Pending or failed close never resets the admission barrier. Both engines expose `registerBeforeDisconnect(stop)` (returns unregister) as a mandatory resident-consumer barrier and `transactionDirect(fn)` for short control work on the existing direct route; nested calls stay in their transaction.
-- `src/core/pglite-lock.ts` — persistent datastore ownership uses a canonical sibling `.gbrain-owner.lock` retained inode and the native kernel binding. `.gbrain-lock/lock` retains PID, structured argv, command/subcommand and heartbeat diagnostics for `inspectLockHolder`/`peekLock` and engine-free IPC routing; `peekLock` also reports a serve holder's transport (`http` from its recorded `--http` argv) and `acquiredAt`, in one metadata read. `heldLockFor(dataDir)` answers "does this process hold it" from the in-memory retained handles (no file access while none are held). The exported ps/proc/Windows CIM process probe is diagnostic compatibility only; ownership and takeover never consult it. Metadata age, corruption and PID reuse never override a kernel owner. The initial protocol upgrade refuses live/unknown legacy owners; all older processes must be stopped. Handles remain strongly retained until explicit release, so GC cannot unlock a datastore after a close timeout. Dead legacy migration keeps the one-acquisition WAL-repair quarantine; `msSinceLastReap` reads older persisted quarantine markers. Tests: `test/pglite-lock.test.ts` (real paused/crashed process, replacement/aliases, migration, metadata).
+- `src/core/pglite-lock.ts` — persistent datastore ownership uses a canonical sibling `.gbrain-owner.lock` retained inode and the native kernel binding. `.gbrain-lock/lock` retains PID, structured argv, command/subcommand and heartbeat diagnostics for `inspectLockHolder`/`peekLock` and engine-free IPC routing; `peekLock` also reports a serve holder's transport (`http` from its recorded `--http` argv) and `acquiredAt`, in one metadata read. `heldLockFor(dataDir)` answers "does this process hold it" from the in-memory retained handles (no file access while none are held). The exported ps/proc/Windows CIM process probe is diagnostic compatibility only; ownership and takeover never consult it. Metadata age, corruption and PID reuse never override a kernel owner. The initial protocol upgrade refuses live/unknown legacy owners; all older processes must be stopped. An owner `legacyOwnerUnverified` cannot prove dead (bad or missing metadata, no PID, Linux pid_ns/boot_id mismatch) throws `LegacyOwnerUnverifiedError` (reason `legacy_owner_unverified`, not retryable, ask_user fix: the `pglite-repair --legacy-lock` preview). Handles remain strongly retained until explicit release, so GC cannot unlock a datastore after a close timeout. Dead legacy migration keeps the one-acquisition WAL-repair quarantine; `msSinceLastReap` reads older persisted quarantine markers. Tests: `test/pglite-lock.test.ts` (real paused/crashed process, replacement/aliases, migration, metadata).
- `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-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 4505c2e33a..1b3b11d5e1 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2066,6 +2066,18 @@ More: [docs/guides/repair.md#legacy-job-selection-invalid](../../docs/guides/rep
More: [docs/guides/repair.md#legacy-jobs-active](../../docs/guides/repair.md#legacy-jobs-active)
+### legacy_lock_removal_refused
+
+<a id="legacy_lock_removal_refused"></a>
+
+| 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 |
+
+Reasons: `live_holder`, `network_filesystem`.
+
+More: [docs/ENGINES.md#legacy-pglite-lock](../../docs/ENGINES.md#legacy-pglite-lock)
+
### local_conflict
<a id="local_conflict"></a>
@@ -2636,9 +2648,13 @@ More: [docs/ENGINES.md#pg-statement-build-failed](../../docs/ENGINES.md#pg-state
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| Another gbrain process holds this PGLite brain's single-writer lock. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait for the current command or server to close, then retry. Do not remove a live lock. | agent | `repeat the read that failed` | 1 | yes |
+| Another gbrain process holds this PGLite brain's single-writer lock. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait for the current command or server to close, then retry. Do not remove a live lock. Reason legacy_owner_unverified is different: a lock folder from an older gbrain whose owner cannot be proven dead never frees itself, so ask the user and run the read-only preview in fix (gbrain pglite-repair --legacy-lock --dry-run). | agent | `repeat the read that failed` | 1 | yes |
+
+Reasons: `timeout`, `live_serve`, `legacy_owner_unverified`.
+
+Override: reason `legacy_owner_unverified`: consent, exit 3, not retryable.
-Reasons: `timeout`, `live_serve`.
+More: [docs/ENGINES.md#legacy-pglite-lock](../../docs/ENGINES.md#legacy-pglite-lock)
### pglite_vector_index_too_large
diff --git a/llms-full.txt b/llms-full.txt
index df8aa185a6..ec01b073d6 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5810,6 +5810,46 @@ to connect: it diagnoses the dir from disk, names the repair command, reports
retained repair backups, and escalates when repairs keep recurring (that
means the unclean-shutdown genesis is still active — see the ladder's rung 4).
+<a id="legacy-pglite-lock"></a>
+### Legacy PGLite lock (`pglite_busy` reason `legacy_owner_unverified`)
+
+A PGLite brain is owned through the stable sibling kernel lock
+`<data-dir>.gbrain-owner.lock`. Brains last opened by an older gbrain may
+still hold that release's lock folder, `<data-dir>/.gbrain-lock/`. The first
+open by a current gbrain removes it automatically only when it can prove the
+old owner is dead: readable metadata with a PID that `kill -0` reports gone
+and, on Linux, the same PID namespace and boot id as this process. A live
+owner keeps the ordinary `pglite_busy` refusal.
+
+When the folder's metadata is torn or missing, records no PID, or (Linux) does
+not prove the PID ran in this namespace since the last boot, waiting never
+helps, so the open refuses `pglite_busy` with reason
+`legacy_owner_unverified` (class consent, exit 3, not retryable). Its fix
+asks the user and starts with the read-only preview; `gbrain doctor` shows
+the same reason and fix on its `connection` check.
+
+1. **Preview.** `gbrain pglite-repair --legacy-lock --dry-run --json [--path <dir>]`
+ 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
+ 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.
+2. **Apply, after the user agrees.**
+ `gbrain pglite-repair --legacy-lock --path <dir> --yes --expect <plan_hash>`
+ takes the kernel lock (so no current gbrain can be running), inspects
+ again under it and refuses `legacy_lock_removal_refused` while a process
+ 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
+ `<data-dir>.legacy-lock-removed-<timestamp>/` (nothing is deleted) with a
+ `receipt.json` and the exact restore command, 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.
+
## Canonical schema sources
Schema DDL text has one hand-edited copy. `bun run build:schema`
diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.ts
index cdce45b4a5..3a61258228 100644
--- a/src/cli/cli-error.ts
+++ b/src/cli/cli-error.ts
@@ -8,7 +8,7 @@
* idle and the patched `process.exit` drains anything queued, so callers may
* exit right after.
*/
-import { cliRenderContext, renderCliError, renderNotice, type AgentEnvelope, type Notice } from '../core/agent-output.ts';
+import { cliRenderContext, renderCliError, renderNotice, type Action, type AgentEnvelope, type Notice } from '../core/agent-output.ts';
import { renderCliNotices } from '../core/agent-markers.ts';
import { jsonGuardActive, jsonRequested, noteRenderedErrorCode, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { opError, type OpErrorOpts, type OperationError } from '../core/ops/contract.ts';
@@ -159,7 +159,12 @@ export function unknownFlagError(command: string, flag: string, message: string,
export function writeFatalCliError(e: unknown, opts: { argv?: readonly string[]; dbUrl?: string | null; brainId?: string } = {}): number {
const argv = opts.argv ?? process.argv.slice(2);
const command = cliCommandOf(argv);
- const busy = e as { code?: unknown; reason?: unknown; message?: unknown } | null;
+ const busy = e as { code?: unknown; reason?: unknown; message?: unknown; fix?: Action } | null;
+ if (busy?.code === 'pglite_busy' && busy.reason === 'legacy_owner_unverified' && busy.fix) {
+ const next = 'Waiting does not free this lock. Ask the user (fix.user_message); if they agree, run the read-only preview in fix and follow it.';
+ const err = opError('pglite_busy', String(busy.message), next, { reason: busy.reason, fix: busy.fix, retryable: false });
+ return writeCliError(err, command, { argv, legacy: { error: 'pglite_busy', retryable: false, reason: busy.reason } });
+ }
if (busy?.code === 'pglite_busy') {
const next = 'Wait for the current command or server to close, then retry. Do not remove a live lock.';
// A7: a live serve owns the brain (usually an agent session's stdio serve), so
diff --git a/src/commands/doctor/checks/db-connection.ts b/src/commands/doctor/checks/db-connection.ts
index 00de3c0e1e..6594246ec9 100644
--- a/src/commands/doctor/checks/db-connection.ts
+++ b/src/commands/doctor/checks/db-connection.ts
@@ -185,6 +185,12 @@ function classifiedConnectionCheck(e: unknown, dbSource?: DbUrlSource): Check {
{ requires_exclusive: true }), owner),
};
}
+ // C-3: a legacy lock whose owner cannot be proven dead never frees itself; its fix asks the user and starts with the preview.
+ const legacy = e as { code?: unknown; reason?: unknown; fix?: Action; message?: unknown } | null;
+ if (legacy?.code === 'pglite_busy' && legacy.reason === 'legacy_owner_unverified' && legacy.fix) {
+ return { name: 'connection', status: 'fail', readiness_state: 'unknown', message: `${String(legacy.message)} The database checks did not run.`,
+ details: { reason: 'legacy_owner_unverified' }, fix: legacy.fix };
+ }
const d = classifyPgAccessError(e, { url: loadConfig()?.database_url ?? null });
const source = describeUrlSource(dbSource ?? getDbUrlSource());
return {
diff --git a/src/commands/pglite-repair-legacy-lock.ts b/src/commands/pglite-repair-legacy-lock.ts
new file mode 100644
index 0000000000..45c75f7b88
--- /dev/null
+++ b/src/commands/pglite-repair-legacy-lock.ts
@@ -0,0 +1,119 @@
+/**
+ * `gbrain pglite-repair --legacy-lock` (GBRA-130 C-3): the preview-first exit
+ * for a legacy (pre-kernel) PGLite lock whose owner cannot be proven dead.
+ * Engine-free and pre-connect, like the WAL repair it sits beside.
+ *
+ * --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).
+ */
+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 { 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 { 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. '
+ + 'If the old gbrain is in fact still running (in another container, PID namespace or on another host sharing this folder), two writers can corrupt the brain.';
+
+const previewArgv = (dataDir: string) => ['gbrain', 'pglite-repair', '--legacy-lock', '--path', dataDir, '--dry-run', '--json'];
+const applyArgv = (dataDir: string) => ['gbrain', 'pglite-repair', '--legacy-lock', '--path', dataDir];
+const previewFix = (dataDir: string): Action => ({ argv: previewArgv(dataDir), consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Read-only: shows the legacy lock, the advisory evidence and the current plan_hash.' });
+
+function userMessage(i: LegacyLockInspection): string {
+ const pid = i.legacy_lock.metadata?.pid, scan = i.evidence?.fd_scan;
+ const seen = scan?.method !== 'proc' ? 'gbrain could not check which processes on this computer have the brain open'
+ : `no process gbrain could inspect on this computer has the brain open${scan.uninspectable ? ` (${scan.uninspectable} processes of other users could not be inspected)` : ''}`;
+ return `Your gbrain brain at ${i.data_dir} has a lock left by an older gbrain${pid ? ` (process ${pid})` : ''} that gbrain cannot prove has stopped. `
+ + `As far as this computer can tell, ${seen}, but that check cannot see other containers or other computers that share this folder. `
+ + 'If no older gbrain is running anywhere that can reach this folder, I can move the stale lock aside (it is kept, not deleted) so gbrain can open the brain. Should I?';
+}
+
+function emit(doc: unknown): void { void writeJsonDocument(JSON.stringify(doc)); }
+function emitText(doc: string): void { void writeJsonDocument(doc.trimEnd()); }
+
+function printPreview(i: LegacyLockInspection, json: boolean): number {
+ const { selection: _selection, ...shown } = i;
+ const apply = i.removable && i.plan_hash ? [...applyArgv(i.data_dir), '--yes', '--expect', i.plan_hash] : null;
+ if (json) {
+ emit({ status: 'ok', action: 'dry-run', ...shown, ...(apply ? { apply_argv: apply, risk: RISK, user_message: userMessage(i) } : {}) });
+ return 0;
+ }
+ const lock = i.legacy_lock, ev = i.evidence;
+ console.log(`PGLite data dir: ${i.data_dir}`);
+ console.log(` Legacy lock: ${lock.verdict}${lock.reason ? ` (${lock.reason})` : ''}${lock.metadata?.pid ? `, recorded PID ${lock.metadata.pid}` : ''}`);
+ if (ev) {
+ console.log(` kill -0: ${ev.pid_alive === null ? 'no PID recorded' : ev.pid_alive ? `running (${ev.pid_command ?? 'command unreadable'})` : 'not running here'}`);
+ console.log(` Open-file scan: ${ev.fd_scan.method === 'unavailable' ? 'unavailable on this platform' : `${ev.fd_scan.holders.length} holder(s)${ev.fd_scan.uninspectable ? `, ${ev.fd_scan.uninspectable} process(es) not inspectable` : ''}`}`);
+ console.log(` Filesystem: ${ev.filesystem.type ?? 'not checked'}`);
+ console.log(` ${ev.scope}`);
+ }
+ if (i.refusal) console.log(` Removable: NO (${i.refusal.reason}): ${i.refusal.message}`);
+ else if (apply) console.log(` Removable: yes. ${RISK}\n The removal is the user's decision. Once they agree: ${shellQuote(apply)}`);
+ else console.log(' Nothing to do: no legacy lock blocks this data dir.');
+ return 0;
+}
+
+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.',
+ { 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);
+ if (!inspection.legacy_lock.legacy) {
+ emit({ status: 'ok', action: 'none', data_dir: inspection.data_dir, verdict: inspection.legacy_lock.verdict });
+ return 0;
+ }
+ if (inspection.refusal) return refuse(inspection, json);
+ const auth = await consentGate({
+ command: 'pglite-repair', effects: ['destructive'], actor: 'agent',
+ what: `Move the legacy PGLite lock of ${inspection.data_dir} aside`,
+ why: `A lock folder from an older gbrain blocks every open of this brain and gbrain cannot prove its owner stopped (${inspection.legacy_lock.reason ?? inspection.legacy_lock.verdict}). ${inspection.evidence?.scope ?? ''}`,
+ 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 });
+ if (!auth) return currentExitCode();
+ const receipt = applyLegacyLockRemoval(inspection);
+ 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 (with gbrain stopped): ${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);
+ 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 });
+ else console.log(`Nothing to do: no legacy lock blocks ${inspection.data_dir}.`);
+ return 0;
+ }
+ let kernel: LockHandle;
+ try {
+ kernel = await acquireKernelLockOnly(inspection.data_dir, { lockDir: inspection.legacy_lock.dir, timeoutMs: 5_000 });
+ } catch (error) {
+ if (!(error instanceof PgliteBusyError)) throw error;
+ const e = opError('pglite_busy', `A running gbrain holds the kernel lock of ${inspection.data_dir}, so the legacy lock is not what blocks it; nothing was changed.`,
+ 'Wait for that gbrain command or server to finish, then run the preview again. Do not remove a live lock.', { reason: 'timeout', fix: previewFix(inspection.data_dir) });
+ return writeCliError(e, 'pglite-repair', { json: opts.json, emit: emitText });
+ }
+ try {
+ return await applyUnderKernelLock(inspection.data_dir, opts.json, opts.args);
+ } catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ return writeCliError(error, 'pglite-repair', { json: opts.json, emit: emitText });
+ } finally {
+ await releaseLock(kernel);
+ }
+}
diff --git a/src/commands/pglite-repair.ts b/src/commands/pglite-repair.ts
index a7395d68c8..8b2578bc62 100644
--- a/src/commands/pglite-repair.ts
+++ b/src/commands/pglite-repair.ts
@@ -46,12 +46,13 @@ interface RepairCmdOpts {
jsonOutput: boolean;
customPath: string | null;
help: boolean;
+ legacyLock: boolean;
}
class UnknownFlagError extends Error {}
function parseArgs(args: string[]): RepairCmdOpts {
- const opts: RepairCmdOpts = { dryRun: false, yes: false, jsonOutput: false, customPath: null, help: false };
+ const opts: RepairCmdOpts = { dryRun: false, yes: false, jsonOutput: false, customPath: null, help: false, legacyLock: false };
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === '--dry-run') opts.dryRun = true;
@@ -70,6 +71,7 @@ function parseArgs(args: string[]): RepairCmdOpts {
opts.customPath = val;
}
else if (a === '--help' || a === '-h') opts.help = true;
+ else if (a === '--legacy-lock') opts.legacyLock = true;
// Reject unknown args on a DESTRUCTIVE command (codex): silently ignoring
// a typo like `--dry-rnu` would run a real WAL reset instead of a dry run.
else throw new UnknownFlagError(`unknown argument: ${a}`);
@@ -92,6 +94,10 @@ Usage:
gbrain pglite-repair --dry-run [--json] [--path <dir>] diagnose only
gbrain pglite-repair [--yes --expect <plan_hash>] [--json] [--path <dir>]
repair (asks first)
+ gbrain pglite-repair --legacy-lock --dry-run [--json] [--path <dir>]
+ preview a legacy lock
+ gbrain pglite-repair --legacy-lock [--yes --expect <plan_hash>] [--json] [--path <dir>]
+ move it aside (asks first)
Flags:
--dry-run Read-only diagnosis of the data dir. Mutates nothing.
@@ -102,6 +108,12 @@ Flags:
user_message to the user).
--json Machine-readable output on stdout.
--path <dir> Repair a specific data dir (default: the configured brain).
+ --legacy-lock Act on a lock folder (.gbrain-lock) left by an older gbrain whose
+ owner cannot be proven dead (pglite_busy reason
+ legacy_owner_unverified) instead of the WAL. The preview's
+ evidence covers only this host and PID namespace; the removal
+ refuses while a process here still uses the data dir or on a
+ network filesystem, and keeps the old folder and a receipt.
Notes:
Auto-repair runs on ordinary commands by default; disable it with
@@ -165,6 +177,10 @@ export async function runPgliteRepair(args: string[]): Promise<number> {
}
dataDir = cfg.database_path || gbrainPath('brain.pglite');
}
+ if (opts.legacyLock) {
+ const { runLegacyLockRepair } = await import('./pglite-repair-legacy-lock.ts');
+ return runLegacyLockRepair(dataDir, { dryRun: opts.dryRun, json: opts.jsonOutput, args: opts.yes ? [...args, '--yes'] : args });
+ }
// Read-only diagnosis first — BEFORE any lock (acquireLock mkdirs the data
// dir; a typo'd --path must produce a clean refusal with zero side effects).
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 54671426dc..4376863263 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -17,7 +17,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],
'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
- 'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--uninstall', '--url', '--yes'],
+ 'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--uninstall', '--url', '--yes'],
'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
@@ -46,20 +46,20 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'conversation-parser': ['--brain', '--help', '--json', '--source'],
'core': ['--apply', '--brain', '--fail-fast', '--help', '--include-core', '--json', '--priority', '--revision', '--slug', '--source', '--tools-json'],
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
- 'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
+ 'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
- 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--max-cost', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--wait', '--yes'],
+ 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
- 'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
+ 'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--legacy-lock', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--body', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
- 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--body', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--retry-held', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
+ 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--body', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--retry-held', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--conversation', '--dry-run', '--entity', '--examples', '--expected-state', '--force', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--slug', '--slugs', '--source', '--source-id'],
'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--held', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--retry-held', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
@@ -74,10 +74,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
@@ -91,19 +91,19 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'onboard': ['--access', '--add', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--older-than', '--retry-parked', '--source', '--state', '--yes'],
- 'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],
+ 'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],
'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],
'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
- 'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
+ 'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--since', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
- 'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
+ 'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
@@ -119,21 +119,21 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--brain', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],
'serve': ['--absolute-git-dir', '--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--verify', '--yes'],
- 'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],
+ 'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
- 'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
+ 'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 05ba4803b5..930e44a0b8 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -353,6 +353,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.' },
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'] } } },
@@ -454,7 +455,7 @@ export const CODES = {
pg_connection_stuck: { class: 'retryable', summary: "A pooled Postgres statement ran past its in-flight budget (the pool's statement_timeout plus grace, or the longer statement_timeout its operation declared) with nothing coming back from the server (reason=idle) or while bytes kept arriving (reason=age), so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK.", why: "Nothing arriving for that long usually means the connection is wedged: a pipeline the server and client no longer agree on, a transaction-mode pooler that swallowed a CancelRequest and left the backend in ClientRead, or a dead peer. It is not proof: behind a transaction-mode pooler the startup statement_timeout never applies (SHOW statement_timeout reads 0), so a legitimately slow statement can reach the budget too. reason=age is a statement that kept streaming rows or notices past its budget (#6543); an operation that needs longer declares it with SET LOCAL statement_timeout (0 for no limit), which the driver tracks per statement. Before #6383 such a connection held its queue forever while /health answered 200. The pool reconnects on its own; the warn line names the pool, the age, the queue depth and the statement by keyword and table.", docs: 'docs/ENGINES.md#pg-connection-stuck', suggestion: 'Retry the failed call. If the line repeats, run gbrain doctor --json and report the warn lines with the operations that preceded them; GBRAIN_PG_STUCK_GRACE_MS raises the grace, and off disables the watchdog.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports pool pressure, the pooler mode and the recent persistence hold lines beside this warning.', requires_exclusive: false } },
pg_pool_stalled: { class: 'retryable', summary: "The Postgres pool of a resident gbrain process has had connections checked out or statements waiting for one across two 30 s ticks without completing a single statement.", why: "One slow statement is one quiet tick; two in a row with nothing settled means every checked-out connection is waiting on the server at once, which is what a wedged pool or an unreachable database looks like from inside the process. With the in-flight watchdog on, the stall ends within statement_timeout plus grace and a pg_pool_recovered line follows; with it off this line is the only trace.", docs: 'docs/ENGINES.md#pg-pool-stalled', suggestion: 'Wait one more tick for pg_pool_recovered or pg_connection_stuck; if the line keeps repeating, check the database and pooler (gbrain doctor --json) and restart the process if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: checks the database and pooler from a fresh process beside the stalled one.', requires_exclusive: false } },
pg_statement_build_failed: { class: 'server', summary: "A Postgres statement could not be built from its parameters (UNDEFINED_VALUE: a parameter was undefined; MAX_PARAMETERS_EXCEEDED: more than 65534 parameters) and was answered in its place in the pipeline by a query the server refuses; it failed, and a transaction it was part of was aborted rather than committed without it.", why: "Either a gbrain programming error at the call site the warn line names by keyword and table (and by `param=$n`), or, behind a transaction-mode pooler (port 6543, prepare off), a value read from a row that belonged to another statement: a pooler that misroutes pipelined answers hands a statement someone else's row, and binding one of its missing columns fails here. Before #6383 the same failure, when it happened behind another statement on the connection, rejected that other statement, desynced the connection and left every later statement on it hanging; the driver now answers the culprit in its place (the approach of porsager/postgres#1236), so only it rejects and a transaction it was in aborts.", docs: 'docs/ENGINES.md#pg-statement-build-failed', suggestion: 'On a transaction-mode pooler, check /health?deep=1 transport (max_pipeline should be 0; PGMAX_PIPELINE=0 on the serve environment forces it) and treat earlier reads as suspect (docs/guides/pooler-misroute-audit.md); otherwise report the warn line (it names the statement and parameter) as a gbrain bug so the call site gets a null where it bound undefined.' },
- pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve'], suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' },
+ pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve', 'legacy_owner_unverified'], reason_overrides: { legacy_owner_unverified: { class: 'consent', exit: 3 } }, docs: 'docs/ENGINES.md#legacy-pglite-lock', suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock. Reason legacy_owner_unverified is different: a lock folder from an older gbrain whose owner cannot be proven dead never frees itself, so ask the user and run the read-only preview in fix (gbrain pglite-repair --legacy-lock --dry-run).' },
pglite_vector_index_too_large: { class: 'unavailable', summary: "A PGLite vector (HNSW) index build was refused before it started because its in-memory graph would not fit PGLite's WebAssembly heap.", why: "pglite.wasm caps memory at 2 GiB and pgvector keeps the whole HNSW graph in memory while it builds; a build past the budget used to run out of memory or fall back to hours of on-disk inserts. Vector search keeps working with exact scans.", docs: 'docs/ENGINES.md#pglite-vector-index-ceiling', suggestion: 'Preview a move to Postgres (read-only): gbrain migrate --to postgres --plan --json', fix: { argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists what moves to Postgres, the blockers and the exact run command.', requires_exclusive: false } },
plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },
plan_stale: { class: 'caller', summary: "The saved plan has no valid repository identity." },
diff --git a/src/core/pglite-legacy-lock.ts b/src/core/pglite-legacy-lock.ts
new file mode 100644
index 0000000000..3a4417f956
--- /dev/null
+++ b/src/core/pglite-legacy-lock.ts
@@ -0,0 +1,201 @@
+/**
+ * The engine-free core of `gbrain pglite-repair --legacy-lock` (GBRA-130 C-3):
+ * a legacy (pre-kernel) `<data-dir>/.gbrain-lock/` whose owner `acquireLock`
+ * cannot prove dead refuses `pglite_busy` reason `legacy_owner_unverified`
+ * forever, so this is its exit.
+ *
+ * `inspectLegacyLock` is read-only and never creates anything: it reports the
+ * legacy metadata, a verdict, the plan hash an approved removal binds (the
+ * 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
+ * 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.
+ *
+ * `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.
+ */
+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 { computePlanHash, type PlanSelection } from './consent.ts';
+import { isProcessAlive, legacyOwnerUnverified, pgliteLockDirFor, readMetadata, readProcessArgs, PGLITE_LOCK_PROTOCOL, type LegacyUnverifiedReason } from './pglite-lock.ts';
+
+/** Linux statfs magic numbers of filesystems another host (or a VM host) can mount, where this host cannot see every process. */
+const NETWORK_FILESYSTEMS: Readonly<Record<number, string>> = {
+ 0x6969: 'nfs', 0xff534d42: 'cifs', 0xfe534d42: 'smb2', 0x517b: 'smb', 0x01021997: '9p', 0x5346414f: 'afs', 0x73757245: 'coda',
+ 0x564c: 'ncp', 0x00c36400: 'ceph', 0x01161970: 'gfs2', 0x7461636f: 'ocfs2', 0x6a656a63: 'virtiofs', 0x65735546: 'fuse',
+ 0x47504653: 'gpfs', 0x0bd00bd0: 'lustre',
+};
+const LOCAL_FILESYSTEMS: Readonly<Record<number, string>> = {
+ 0xef53: 'ext4', 0x58465342: 'xfs', 0x9123683e: 'btrfs', 0x01021994: 'tmpfs', 0x794c7630: 'overlay', 0x2fc12fc1: 'zfs', 0xf2f52010: 'f2fs',
+};
+export function networkFilesystemName(magic: number): string | null {
+ return NETWORK_FILESYSTEMS[magic >>> 0] ?? null;
+}
+
+export const LEGACY_LOCK_EVIDENCE_SCOPE = 'Advisory only: kill -0, the process command and the open-file scan cover only this host and PID namespace. '
+ + 'They cannot see processes in other containers or PID namespaces, or on other hosts that share this folder, so they are not proof that the old owner has stopped.';
+
+export interface LegacyLockEvidence {
+ advisory: true;
+ scope: string;
+ pid: number | null;
+ pid_alive: boolean | null;
+ pid_command: string | null;
+ fd_scan: { method: 'proc' | 'unavailable'; holders: Array<{ pid: number; command: string | null; paths: string[] }>; uninspectable: number };
+ filesystem: { type: string | null; magic: number | null; network: boolean | null };
+}
+
+export interface LegacyLockInspection {
+ data_dir: string;
+ legacy_lock: {
+ dir: string;
+ present: boolean;
+ /** The dir would block a kernel-v1 open (no marker yet, or metadata from another protocol). */
+ legacy: boolean;
+ verdict: 'absent' | 'current' | 'live' | 'dead' | 'unverified';
+ reason: LegacyUnverifiedReason | null;
+ 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;
+ removable: boolean;
+ plan_hash: string | null;
+ selection: PlanSelection | null;
+}
+
+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 };
+ const holders: LegacyLockEvidence['fd_scan']['holders'] = [];
+ let uninspectable = 0;
+ for (const entry of readdirSync('/proc')) {
+ const pid = Number(entry);
+ if (!/^\d+$/.test(entry) || pid === process.pid) continue;
+ let fds: string[];
+ try { fds = readdirSync(`/proc/${pid}/fd`); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') uninspectable++;
+ continue;
+ }
+ const paths = new Set<string>();
+ for (const fd of fds) {
+ let target: string;
+ try { target = readlinkSync(`/proc/${pid}/fd/${fd}`); } catch { continue; }
+ if (target === dataDir || target.startsWith(`${dataDir}/`)) paths.add(target);
+ }
+ if (paths.size > 0) holders.push({ pid, command: readProcessArgs(pid)?.slice(0, 200) ?? null, paths: [...paths].sort().slice(0, 5) });
+ }
+ return { method: 'proc', holders, uninspectable };
+}
+
+function filesystemOf(dataDir: string): LegacyLockEvidence['filesystem'] {
+ if (process.platform !== 'linux') return { type: null, magic: null, network: null };
+ try {
+ const magic = statfsSync(dataDir).type >>> 0;
+ const network = networkFilesystemName(magic);
+ return { type: network ?? LOCAL_FILESYSTEMS[magic] ?? `0x${magic.toString(16)}`, magic, network: network !== null };
+ } catch { return { type: null, magic: null, network: null }; }
+}
+
+/** Whether a live recorded PID could still be the legacy gbrain: its command is unreadable, names gbrain, or names the recorded script. */
+function couldBeOwner(command: string | null, recorded: string | null): boolean {
+ if (command === null) return true;
+ if (command.includes('gbrain')) return true;
+ const script = recorded?.trim().split(/\s+/)[0];
+ return !!script && command.includes(script);
+}
+
+function planSelection(dataDir: string, lockDir: string): PlanSelection {
+ const dir = lstatSync(lockDir);
+ const entries = readdirSync(lockDir).sort().map(name => {
+ const path = join(lockDir, name);
+ const st = lstatSync(path);
+ return { id: `.gbrain-lock/${name}`, revision: st.isFile() ? sha256(readFileSync(path)) : `${st.isDirectory() ? 'dir' : 'other'}:${st.ino}` };
+ });
+ const marker = markerPathOf(dataDir);
+ return {
+ brain: dataDir, source: null, operation: 'pglite-repair --legacy-lock',
+ records: [{ id: '.gbrain-lock', revision: `${dir.dev}:${dir.ino}` }, ...entries],
+ parameters: { marker: existsSync(marker) ? sha256(readFileSync(marker)) : null }, effects: ['destructive'],
+ };
+}
+
+function evidenceFor(dataDir: string, pid: number | null, recordedCommand: string | null, verdict: LegacyLockInspection['legacy_lock']['verdict']): { 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) };
+ 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.` } };
+ }
+ return { evidence, refusal: null };
+}
+
+/** Read-only: never creates the data dir, the legacy dir or the kernel lock. */
+export function inspectLegacyLock(path: string): LegacyLockInspection {
+ const lockDir = pgliteLockDirFor(path), dataDir = dirname(lockDir);
+ const present = existsSync(lockDir) && lstatSync(lockDir).isDirectory();
+ let migrated = false;
+ try { migrated = JSON.parse(readFileSync(markerPathOf(dataDir), 'utf8')).protocol === PGLITE_LOCK_PROTOCOL; } catch { /* not yet upgraded */ }
+ const metadata = present ? readMetadata(lockDir) : null;
+ const legacy = present && (!migrated || (!!metadata && metadata.protocol !== PGLITE_LOCK_PROTOCOL));
+ const reason = legacy ? legacyOwnerUnverified(metadata, lockDir) : null;
+ 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 selection = legacy ? planSelection(dataDir, lockDir) : null;
+ return {
+ data_dir: dataDir,
+ legacy_lock: { dir: lockDir, present, legacy, verdict, reason,
+ metadata: metadata ? { pid, command: recordedCommand, acquired_at: typeof metadata.acquired_at === 'number' ? metadata.acquired_at : null,
+ pid_ns: metadata.pid_ns ?? null, boot_id: metadata.boot_id ?? null } : null },
+ evidence, refusal, removable: legacy && refusal === null,
+ plan_hash: selection ? computePlanHash(selection) : null, selection,
+ };
+}
+
+export interface LegacyLockRemovalReceipt {
+ action: 'removed';
+ data_dir: string;
+ moved_to: string;
+ marker_path: string;
+ prior_marker: string | null;
+ plan_hash: string;
+ removed_at: string;
+ evidence: LegacyLockEvidence | null;
+ restore_command: string;
+}
+
+/** Caller holds the stable sibling kernel lock and consent bound to `inspection.plan_hash`, re-inspected under that lock. */
+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 movedTo = `${dataDir}.legacy-lock-removed-${now.toISOString().replace(/[:.]/g, '-')}`;
+ mkdirSync(movedTo, { mode: 0o700 });
+ 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,
+ 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/src/core/pglite-lock.ts b/src/core/pglite-lock.ts
index 8541b4ccc8..d5d1311904 100644
--- a/src/core/pglite-lock.ts
+++ b/src/core/pglite-lock.ts
@@ -7,19 +7,42 @@ import { readProcessCommand, type ProcessCommandProbeDeps } from './autopilot-lo
import { setTimeout as delay } from 'node:timers/promises';
import { parseGlobalFlags } from './cli-options.ts';
import { tryAcquireNativeLock, type NativeLockHandle } from './persistence/native-lock.ts';
+import type { Action } from './agent-output.ts';
const HEARTBEAT_INTERVAL_MS = 30_000;
+/** How long an unverifiable legacy owner may stay unverifiable before the typed refusal (covers a legacy writer between mkdir and its metadata write). */
+const LEGACY_UNVERIFIED_GRACE_MS = 1_000;
const LOCK_FILE = 'lock';
// A dropped engine reference must never let GC release a still-open datastore.
const retainedOwners = new Set<LockHandle>();
export class PgliteBusyError extends Error {
readonly code = 'pglite_busy';
- readonly retryable = true;
- constructor(message: string, public reason: 'timeout' | 'live_serve' = 'timeout') {
+ readonly retryable: boolean = true;
+ constructor(message: string, public reason: 'timeout' | 'live_serve' | 'legacy_owner_unverified' = 'timeout') {
super(message); this.name = 'PgliteBusyError';
}
}
+/**
+ * A legacy (pre-kernel) `.gbrain-lock/` whose owner cannot be proven dead: torn
+ * or missing metadata, no recorded PID, or (Linux) no matching pid_ns+boot_id.
+ * Waiting never changes that, so it is not retryable: the fix asks the user
+ * and starts with the read-only `gbrain pglite-repair --legacy-lock` preview.
+ */
+export class LegacyOwnerUnverifiedError extends PgliteBusyError {
+ override readonly retryable = false;
+ readonly fix: Action;
+ constructor(readonly dataDir: string, readonly legacyPid: number | null, readonly why: string) {
+ super(`GBrain: the PGLite data dir ${dataDir} still has a lock folder (.gbrain-lock) from an older gbrain${legacyPid === null ? '' : ` (PID ${legacyPid})`}, and ${why}, so gbrain cannot prove that process has stopped and will not open the brain. Waiting does not change this. Never remove a live holder's lock.`, 'legacy_owner_unverified');
+ this.name = 'LegacyOwnerUnverifiedError';
+ this.fix = {
+ argv: ['gbrain', 'pglite-repair', '--legacy-lock', '--path', dataDir, '--dry-run', '--json'], ask_user: true, consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Read-only: names the legacy PID, whether it still runs and which processes on this host have the data dir open, and prints the plan_hash an approved removal binds.',
+ user_message: `Your gbrain brain at ${dataDir} still carries a lock left by an older gbrain version, and gbrain cannot prove that process has stopped, so it will not open the brain. `
+ + 'If no older gbrain is still running on this computer or on any other computer that shares this folder, I can check what is still using it (read-only) and then, with your OK, move the stale lock aside. Should I?',
+ };
+ }
+}
export class LiveServeLockError extends PgliteBusyError {
/** The live serve holding the lock, for the two-step recovery plan (A7 `exclusiveFix`). */
readonly ownerPid?: number;
@@ -45,7 +68,7 @@ export interface LockHandle {
acquiredAt?: number;
}
-interface LockMetadata {
+export interface LockMetadata {
pid?: number;
acquired_at?: number;
refreshed_at?: number;
@@ -58,6 +81,8 @@ interface LockMetadata {
boot_id?: string | null;
}
const protocol = 'kernel-v1';
+/** The protocol the kernel-v1 marker (`<data-dir>.gbrain-owner.json`) and current metadata record. */
+export const PGLITE_LOCK_PROTOCOL = protocol;
function tokenOf(metadata: LockMetadata): string {
return metadata.owner_token ?? `${metadata.pid}:${metadata.acquired_at}`;
}
@@ -66,7 +91,7 @@ function isServeCommand(metadata: LockMetadata): boolean {
const parts = typeof metadata.command === 'string' ? metadata.command.trim().split(/\s+/) : [];
return parts[0] === 'serve' || parts[1] === 'serve';
}
-function readMetadata(lockDir: string): LockMetadata | null {
+export function readMetadata(lockDir: string): LockMetadata | null {
try { return JSON.parse(readFileSync(join(lockDir, LOCK_FILE), 'utf8')); } catch { return null; }
}
export function readPidNs(): string | null {
@@ -114,7 +139,7 @@ export function isProcessAlive(pid: number): boolean {
}
/** Compatibility process diagnostics; never an ownership or takeover authority. */
-function readProcessArgs(pid: number, deps?: ProcessCommandProbeDeps): string | null {
+export function readProcessArgs(pid: number, deps?: ProcessCommandProbeDeps): string | null {
if ((deps?.platform ?? process.platform) === 'win32') return readProcessCommand(pid, deps);
const exec = deps?.execFile ?? execFileSync;
try {
@@ -264,6 +289,27 @@ function busy(lockDir: string): PgliteBusyError {
return new PgliteBusyError(`GBrain: Timed out waiting for PGLite data-dir lock at ${lockDir}. Retry after the holder finishes. Stop all older GBrain processes before upgrading this datastore's lock protocol; unreadable legacy ownership is never stolen. Never remove a live holder's lock. This lock is separate from \`gbrain sync --break-lock\`.`);
}
+/**
+ * Why a legacy owner cannot be proven dead, or null when its PID is
+ * comparable. Legacy death requires matching namespace evidence on Linux:
+ * ESRCH from another container's PID namespace, or after a reboot, proves
+ * nothing.
+ */
+export function legacyOwnerUnverified(metadata: LockMetadata | null, lockDir: string): LegacyUnverifiedReason | null {
+ if (!metadata) return existsSync(join(lockDir, LOCK_FILE)) ? 'metadata_unreadable' : 'metadata_missing';
+ if (!Number.isInteger(metadata.pid) || metadata.pid! <= 0) return 'no_pid';
+ if (process.platform !== 'linux') return null;
+ const comparable = metadata.pid_ns != null && metadata.boot_id != null && metadata.pid_ns === readPidNs() && metadata.boot_id === readBootId();
+ return comparable ? null : 'namespace_unverified';
+}
+export type LegacyUnverifiedReason = 'metadata_unreadable' | 'metadata_missing' | 'no_pid' | 'namespace_unverified';
+export const LEGACY_UNVERIFIED_WHY: Readonly<Record<LegacyUnverifiedReason, string>> = {
+ metadata_unreadable: 'its lock metadata is unreadable',
+ metadata_missing: 'its lock metadata is missing',
+ no_pid: 'its lock metadata records no process id',
+ namespace_unverified: 'its lock metadata does not prove the process ran in this PID namespace since the last boot',
+};
+
/**
* First kernel acquisition also claims the legacy mkdir lock. A live or
* unreadable legacy holder blocks migration. After migration, pid/mtime/
@@ -279,6 +325,7 @@ export async function acquireLock(dataDir: string | undefined, opts: { timeoutMs
const markerPath = `${canonical}.gbrain-owner.json`;
const lockDir = getLockDir(canonical);
const deadline = performance.now() + timeoutMs;
+ let refusal: PgliteBusyError = busy(lockDir), unverifiedSince: number | undefined;
for (;;) {
opts.signal?.throwIfAborted();
const nativeLock = await tryAcquireNativeLock(kernelPath);
@@ -294,11 +341,12 @@ export async function acquireLock(dataDir: string | undefined, opts: { timeoutMs
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
const metadata = readMetadata(lockDir);
if (!migrated || (metadata && metadata.protocol !== protocol)) {
- // Legacy death requires matching namespace evidence on Linux;
- // ESRCH from another container's PID namespace proves nothing.
- const comparable = process.platform !== 'linux' || (metadata?.pid_ns === readPidNs()
- && metadata?.boot_id === readBootId() && metadata?.pid_ns != null && metadata?.boot_id != null);
- if (!metadata || !comparable || isProcessAlive(metadata.pid!)) throw busy(lockDir);
+ const unverified = legacyOwnerUnverified(metadata, lockDir);
+ if (unverified) {
+ const error = busy(lockDir);
+ throw error instanceof LiveServeLockError ? error : new LegacyOwnerUnverifiedError(canonical, typeof metadata?.pid === 'number' ? metadata.pid : null, LEGACY_UNVERIFIED_WHY[unverified]);
+ }
+ if (isProcessAlive(metadata!.pid!)) throw busy(lockDir);
reaped = true;
}
}
@@ -315,12 +363,15 @@ export async function acquireLock(dataDir: string | undefined, opts: { timeoutMs
return result;
} catch (error) {
if (!(error instanceof PgliteBusyError) || error instanceof LiveServeLockError || performance.now() >= deadline) throw error;
+ if (error instanceof LegacyOwnerUnverifiedError && performance.now() - (unverifiedSince ??= performance.now()) >= LEGACY_UNVERIFIED_GRACE_MS) throw error;
+ refusal = error;
} finally { if (!accepted) await nativeLock.release(); }
} else {
const error = busy(lockDir);
if (error instanceof LiveServeLockError) throw error;
+ refusal = error;
}
- if (performance.now() >= deadline) throw busy(lockDir);
+ if (performance.now() >= deadline) throw refusal;
await delay(Math.min(25, deadline - performance.now()), undefined, { signal: opts.signal });
}
}