Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(pglite-lock): report a serve owner's transport and this process's own hold
garrytan8a1f10f1ef5b
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex 75f473cbaf..8f5ec5c648 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -8,6 +8,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche`BOOTSTRAP_FOR_AGENTS.md` (root; carries a version stamp CI pins to VERSION).- `src/commands/bootstrap.ts` — the `gbrain bootstrap {status,interview,render,repo,hooks,verify,uninstall,attach,cloud-setup-script}` dispatcher (plus the machine-level `harness` subcommand — see the `core/bootstrap/harness.ts` entry below). Engine-free everywhere except `verify` (which opens/closes its own engine — safe because verify runs with no live serve, before host registration). `cloud-setup-script` is a pure printer (prints `templates/bootstrap/cloud-setup-script.sh` for the cloud environment's setup step) and is dispatched entirely BEFORE workspace resolution, so it works from any cwd, including $HOME. Every other subcommand resolves `--workspace` (default: cwd) through `resolveWorkspace`, which refuses with `BootstrapError('HOME_WORKSPACE')` when the resolved path (realpath-compared, so a symlinked $HOME or cwd still matches) IS `process.env.HOME` (falling back to `os.homedir()` only when HOME is unset) — an unqualified run from a freshly-SSH'd shell must not silently stage a home-directory-scale `git add -A` over `~/.ssh/` and friends; the refusal is still appended to `<home>/bootstrap/install.jsonl` (keyed by the rejected candidate path) before returning. `status`, `uninstall`, and `harness` are exempt from this guard (`HOME_WORKSPACE_GUARD_EXEMPT`): `status` only reads and prints a report, `uninstall` removes exactly `receipt.created_paths` (each containment-checked) — never a `git add`/commit/push, never a workspace-wide scan — and `harness` operates only on `home` and never even receives a `ws` argument (`runHarness`, machine-level wiring), so the value `resolveWorkspace` returns for it is used only for `LogCtx.ws` bookkeeping. Exempting `status`/`uninstall` keeps the recovery path reachable for the guard's own victims: someone who bootstrapped into `$HOME` needs `status` to see what's there and `uninstall` to remove it, both run with `--workspace` pointing AT $HOME; the refusal message for the still-guarded subcommands names that recovery path. Known gap: a process already launched with HOME pointed away from the real account home is not caught (Bun's `os.homedir()` mirrors process-start HOME rather than doing an independent uid lookup, so it collapses to the same wrong value). Mutating subcommands run under the workspace bootstrap lock; render is gated on interview `complete && confirmed` and hard-refuses when the workspace origin is a PUBLIC remote (identity files must never land in a public repo — the same template-door gate `status` enforces; unverifiable visibility warns and proceeds, treating the origin as public); the provider key routes to the 0600 config sink and never touches interview state; every MUTATING subcommand appends a line to `<home>/bootstrap/install.jsonl` (the read-only `status` and `cloud-setup-script` do not log). `hooks` on Claude Code writes the committed carrier in a cloud sandbox (`writeCommittedClaudeHooks`) and the gitignored local file otherwise; `uninstall` tears down the durability wiring and removes this workspace's per-root push/debounce state, and its opencode teardown sweeps BOTH merged global filenames (under the opencode config-dir bootstrap lock) plus the project `opencode.json`, expectation-keyed on this workspace's source id (`skipOtherSource`) — a gbrain entry from a different workspace is skipped with a note, never silently deleted. Consent answers resolve FAIL-CLOSED: `consentAnswer` treats a hand-edited/unusable interview value (non-string, empty) as declined — loudly, with a re-record note — never falling through to a permissive bank default; `hooks` on Codex prints a corrective note when a persisted `project` MCP_SCOPE answer is found (raw state read, not the resolver — `codex mcp add` has no scope flag, registrations are always user-global) with safe clear instructions. `GBRAIN_BOOTSTRAP_ABORT_AFTER` is the deterministic kill-mid-phase test seam.+- `src/core/gbrain-bin.ts` — `resolveGbrainBin()`: the absolute gbrain binary for harness registrations and hook commands (`Bun.which('gbrain')` when absolute, else this process's executable when it is the compiled binary, else null). A bare `gbrain` is never registered because GUI hosts inherit no PATH. Used by `bootstrap` and readiness's `harness_wiring` fix.- `src/core/bootstrap/format.ts` — `agent.json` manifest (format_version 1, provisional; `initialized` sentinel distinguishes a template clone from a bootstrapped workspace) + the machine-local install receipt (`<home>/bootstrap/receipt.json`) that proves THIS machine ran bootstrap; uninstall is keyed to the receipt, never the repo manifest. Atomic writes; `readManifest` never throws (typed states incl. conflict markers).- `src/core/bootstrap/assets.ts` — every template + the question bank embedded via Bun `with { type: 'file' }` imports (the chunkers/code.ts pattern) so the compiled binary renders with no repo checkout; `DERIVED_TOKENS` (GITHUB_REPO_URL, CORPUS_RETENTION_DAYS) is the non-bank half of the template token set the CI bijection guard checks.- `templates/bootstrap/` — the ten `{{TOKEN}}` identity templates (AGENTS/CLAUDE/SOUL/USER/MEMORY/HEARTBEAT/ACCESS_POLICY/GITHUB/memory-README/gitignore), `questions.json` (12 asked / 6 required; consent keys; `persist:false` sink keys), and `template-repo/` — the VENDORED deterministic render the release job diffs against before publishing the public template repo. Generic placeholder content only (privacy iron rule; CI-asserted).diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex 1234fd2ead..b0be379efb 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -39,7 +39,7 @@ 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. 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. 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 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. `dropRowTypeArrayParsers` removes composite-row array parsers after connect, since gbrain never selects those arrays. Pinned by `test/pglite-statements.test.ts`.diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.tsindex 7af3e87011..94e69dc2af 100644--- a/src/commands/bootstrap.ts+++ b/src/commands/bootstrap.ts@@ -29,12 +29,13 @@import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';import { homedir, tmpdir } from 'node:os';-import { basename, dirname, isAbsolute, join, resolve } from 'node:path';+import { dirname, join, resolve } from 'node:path';import { VERSION } from '../version.ts';import { loadConfig, loadConfigFileOnly, saveConfig, toEngineConfig, type GBrainConfig } from '../core/config.ts';import { createEngine } from '../core/engine-factory.ts';import { resolveGbrainHome } from '../core/gbrain-home.ts';+import { resolveGbrainBin } from '../core/gbrain-bin.ts';import { detectExecutionEnvironment } from '../core/execution-env.ts';import { realpathOrResolve } from '../core/path-confine.ts';import { loadQuestionBank } from '../core/bootstrap/assets.ts';@@ -374,20 +375,6 @@ export function detectHarness(env: Record<string, string | undefined> = process.return null;}-/** Absolute gbrain binary path for registrations/hook commands [CX-P1.4].- * GUI hosts inherit no PATH, so a bare name is never acceptable. */-function resolveGbrainBin(): string | null {- try {- const which = Bun.which('gbrain');- if (which && isAbsolute(which)) return which;- } catch {- /* fall through */- }- // Compiled-binary case: this process IS the gbrain binary.- if (basename(process.execPath).startsWith('gbrain')) return process.execPath;- return null;-}-/*** [FIX7] Does the host's existing `gbrain` MCP registration target THIS* workspace's serve? An "already exists/registered" error is NOT proof thediff --git a/src/core/gbrain-bin.ts b/src/core/gbrain-bin.tsnew file mode 100644index 0000000000..c8442a74b6--- /dev/null+++ b/src/core/gbrain-bin.ts@@ -0,0 +1,16 @@+/** Absolute gbrain binary resolution for harness registrations and hook commands. */+import { basename, isAbsolute } from 'node:path';++/** Absolute gbrain binary path for registrations/hook commands [CX-P1.4].+ * GUI hosts inherit no PATH, so a bare name is never acceptable. */+export function resolveGbrainBin(): string | null {+ try {+ const which = Bun.which('gbrain');+ if (which && isAbsolute(which)) return which;+ } catch {+ /* fall through */+ }+ // Compiled-binary case: this process IS the gbrain binary.+ if (basename(process.execPath).startsWith('gbrain')) return process.execPath;+ return null;+}diff --git a/src/core/pglite-lock.ts b/src/core/pglite-lock.tsindex d0048ce7a6..600b53b047 100644--- a/src/core/pglite-lock.ts+++ b/src/core/pglite-lock.ts@@ -34,6 +34,8 @@ export interface LockHandle {/** A dead legacy holder was encountered during protocol migration. */reaped?: boolean;nativeLock?: NativeLockHandle;+ /** Epoch ms when this process took the lock (diagnostic). */+ acquiredAt?: number;}interface LockMetadata {@@ -172,19 +174,42 @@ export interface LockHolderInfo {}/** Read-only compatibility seam for engine-free IPC delegation and status. */export function inspectLockHolder(dataDir: string | undefined): LockHolderInfo {+ return inspectHolderMetadata(dataDir).holder;+}+function inspectHolderMetadata(dataDir: string | undefined): { holder: LockHolderInfo; metadata: LockMetadata | null } {const lockDir = getLockDir(dataDir);- if (!lockDir || !existsSync(lockDir)) return { held: false };+ if (!lockDir || !existsSync(lockDir)) return { holder: { held: false }, metadata: null };const metadata = readMetadata(lockDir);- if (!metadata) return { held: true };+ if (!metadata) return { holder: { held: true }, metadata };const pid = typeof metadata.pid === 'number' ? metadata.pid : undefined;- if (pid !== undefined && !isProcessAlive(pid)) return { held: false, pid };- return { held: true, pid, serve: isServeCommand(metadata),- subcommand: typeof metadata.subcommand === 'string' ? metadata.subcommand : undefined };+ if (pid !== undefined && !isProcessAlive(pid)) return { holder: { held: false, pid }, metadata };+ return { holder: { held: true, pid, serve: isServeCommand(metadata),+ subcommand: typeof metadata.subcommand === 'string' ? metadata.subcommand : undefined }, metadata };+}+export interface LockPeekResult {+ held: boolean; isServe?: boolean; pid?: number;+ /** The holder is `gbrain serve --http` (read from its recorded argv). */+ http?: boolean;+ /** Epoch ms the holder recorded at acquisition. */+ acquiredAt?: number;}-export interface LockPeekResult { held: boolean; isServe?: boolean; pid?: number; }export function peekLock(dataDir: string | undefined): LockPeekResult {- const holder = inspectLockHolder(dataDir);- return { held: holder.held, isServe: holder.serve, pid: holder.pid };+ const { holder, metadata } = inspectHolderMetadata(dataDir);+ if (!holder.held || !holder.serve || !metadata) return { held: holder.held, isServe: holder.serve, pid: holder.pid };+ const args = Array.isArray(metadata.argv) ? metadata.argv : (metadata.command ?? '').split(/\s+/);+ return { held: true, isServe: true, pid: holder.pid, http: args.includes('--http'),+ ...(typeof metadata.acquired_at === 'number' ? { acquiredAt: metadata.acquired_at } : {}) };+}+/**+ * The lock this process itself holds on `dataDir`, from in-memory state only+ * (no file access while this process holds no lock at all).+ */+export function heldLockFor(dataDir: string | undefined): LockHandle | null {+ if (!dataDir || retainedOwners.size === 0) return null;+ let lockDir: string;+ try { lockDir = getLockDir(canonicalPath(dataDir)); } catch { return null; }+ for (const owner of retainedOwners) if (owner.acquired && owner.lockDir === lockDir) return owner;+ return null;}/** Compatibility with repair quarantine markers from older releases. */export function msSinceLastReap(dataDir: string | undefined): number | null {@@ -267,7 +292,7 @@ export async function acquireLock(dataDir: string | undefined, opts: { timeoutMscommand: process.argv.slice(1).join(' '), argv: process.argv.slice(1), subcommand: parseGlobalFlags(process.argv.slice(2)).rest[0],owner_token: ownerToken, protocol, pid_ns: readPidNs(), boot_id: readBootId() });const result = { lockDir, acquired: true, lockPath, ownerToken, reaped, nativeLock,- heartbeat: startHeartbeat(lockPath, ownerToken) };+ heartbeat: startHeartbeat(lockPath, ownerToken), acquiredAt: now };retainedOwners.add(result);accepted = true;return result;