Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(takes): gbrain takes remove works while gbrain serve owns a PGLite brain
time-attackb406f68100d3
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex d4d1942c8c..96496db7fe 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -46,7 +46,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).-- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain; other local calls keep no marker. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).+- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as does `takes_remove` for the `local_cli` principal (its write scope still checked; `gbrain takes remove` defers its engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`).diff --git a/src/cli.ts b/src/cli.tsindex 43f4ef080d..d4e3364b76 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2009,7 +2009,7 @@ async function routeCliOnlyBeforeTable(command: string, args: string[]): Promise}// Local deferred connections must not bypass the remote installation route.- if (command === 'capture' || command === 'forget' || command === 'call' || command === 'sources' && ['writer', 'reconcile', 'add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'].includes(args[0]) || command === 'takes' && ['add', 'update', 'supersede', 'resolve'].includes(args[0]) && !hasHelpFlag(args)) {+ if (command === 'capture' || command === 'forget' || command === 'call' || command === 'sources' && ['writer', 'reconcile', 'add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'].includes(args[0]) || command === 'takes' && ['add', 'update', 'supersede', 'resolve', 'remove'].includes(args[0]) && !hasHelpFlag(args)) {const { runDeferredPersistenceCommand } = await import('./commands/persistence-delegate.ts');await runDeferredPersistenceCommand(command, args, connectEngine);return true;diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.tsindex 33fba8c479..24141acd7f 100644--- a/src/core/persistence/provider.ts+++ b/src/core/persistence/provider.ts@@ -70,9 +70,10 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:return (await import('../transcripts.ts')).listRecentTranscripts(engine, { days: typeof p.days === 'number' ? p.days : undefined,summary: typeof p.summary === 'boolean' ? p.summary : undefined, limit: typeof p.limit === 'number' ? p.limit : undefined });}+ const localCliLocalOnly = !verified.remote && verified.principal.kind === 'local_cli' && request.operation === 'takes_remove';const writeWaitMs = boundedWriteWaitMs(request.write_wait_ms);const result = await dispatchToolCall(engine, request.operation, params, {- config, remote: verified.remote, transport: verified.remote || localSkillAdministration ? 'stdio' : undefined, sourceId, auth,+ config, remote: verified.remote, transport: verified.remote || localSkillAdministration || localCliLocalOnly ? 'stdio' : undefined, sourceId, auth,...(writeWaitMs !== undefined ? { writeWaitMs } : {}),...(unrestricted ? {} : { localFederatedSourceIds: verified.grant.sourceIds }),});diff --git a/test/persistence-local-only-ops.test.ts b/test/persistence-local-only-ops.test.tsindex 4c0d2257dd..ff39318d13 100644--- a/test/persistence-local-only-ops.test.ts+++ b/test/persistence-local-only-ops.test.ts@@ -1,6 +1,7 @@/*** #5864: the trusted local CLI reaches the four localOnly skill-administration- * operations while a serve owns the PGLite brain. Authoring gate: (1) protects+ * operations, and `gbrain takes remove` (#5167), while a serve owns the PGLite+ * brain. Authoring gate: (1) protects* the delegated route for get_skill_retention, prune_skill_revisions,* retain_skill_revision and import_skill_proposal, and keeps remote callers* refused; (2) fails when the resident owner answers `unknown_tool` to the@@ -27,9 +28,9 @@ import { withEnv } from './helpers/with-env.ts';const LOCAL_ONLY_IPC = ['get_skill_retention', 'import_skill_proposal', 'prune_skill_revisions', 'retain_skill_revision'];-test('the localOnly operations on persistence IPC are the four skill-admin ops plus the provider-served transcript read', () => {+test('the localOnly operations on persistence IPC are the four skill-admin ops, takes_remove and the provider-served transcript read', () => {const ipc = new Set<string>(PERSISTENCE_IPC_OPERATIONS);- expect(operations.filter(op => op.localOnly && ipc.has(op.name)).map(op => op.name).sort()).toEqual([...LOCAL_ONLY_IPC, 'get_recent_transcripts'].sort());+ expect(operations.filter(op => op.localOnly && ipc.has(op.name)).map(op => op.name).sort()).toEqual([...LOCAL_ONLY_IPC, 'takes_remove', 'get_recent_transcripts'].sort());});describe('localOnly skill administration through a resident owner', () => {@@ -91,8 +92,37 @@ describe('localOnly skill administration through a resident owner', () => {}, 60_000);}+ const cli = async (args: string[]) => {+ const child = Bun.spawn([process.execPath, join(import.meta.dir, '../src/cli.ts'), ...args], {+ cwd: dir,+ env: { ...process.env, GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_SKIP_UPGRADE_CHECK: '1',+ GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },+ stdout: 'pipe', stderr: 'pipe',+ });+ const timeout = setTimeout(() => child.kill('SIGKILL'), 30_000);+ try {+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ return { stdout, stderr, code, output: stdout + stderr };+ } finally { clearTimeout(timeout); }+ };++ test('gbrain takes remove (#5167) removes a row through the resident owner', async () => {+ const slug = 'notes/ipc-takes-remove';+ expect((await call('put_page', { slug, content: '---\ntitle: IPC takes remove\ntype: note\n---\nAbout the remove path.\n' })).code).toBe(0);+ for (const claim of ['Keep one', 'Drop two']) {+ expect((await call('takes_add', { slug, claim, kind: 'take', holder: 'world' })).code).toBe(0);+ }+ const removed = await cli(['takes', 'remove', slug, '--row', '2', '--json']);+ expect(removed.output).not.toContain('unknown_tool');+ expect(removed.code).toBe(0);+ expect(JSON.parse(removed.stdout)).toMatchObject({ row_num: 2, removed: true });+ const indexed = await engine.executeRaw<{ row_num: number; claim: string }>(+ 'SELECT t.row_num, t.claim FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.slug=$1 ORDER BY t.row_num', [slug]);+ expect(indexed.map(row => [row.row_num, row.claim])).toEqual([[1, 'Keep one']]);+ }, 120_000);+test('remote callers are still refused', async () => {- for (const operation of LOCAL_ONLY_IPC) {+ for (const operation of [...LOCAL_ONLY_IPC, 'takes_remove']) {const http = await dispatchToolCall(engine, operation, {}, { remote: true, transport: 'http' });expect(http.isError).toBe(true);expect(http.content[0]!.text).toContain('unknown_tool');