Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): settle a forget's queued work before follow-up writes (N5-3, N5-2)
garrytan9eaab73f0ba4
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex db8701f350..5ab1b97d43 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -57,7 +57,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `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; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `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.serial.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. 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. 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`.+- `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. 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`.- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex bf51486e41..b9ffff2065 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -9,7 +9,7 @@- `src/core/serve-service.ts` — the persistent-service half of `mcp expose`, everything under `gbrainPath('serve')` (`serveDir`, `adminTokenPath`, `wrapperPath`, `receiptPath`, `serveLogPath`, `serveErrPath`) so `GBRAIN_HOME` is honored. `SERVE_LAUNCHD_LABEL = 'com.gbrain.serve'`, `SERVE_SYSTEMD_UNIT = 'gbrain-serve.service'`, `detectServiceTarget(signals)` → `'macos' | 'linux-systemd' | 'none'` (a working user bus is required for systemd; cloud sandboxes and ephemeral containers fall to `none`). `renderServeWrapper` produces the 0755 launcher that sources the shell profiles and `~/.gbrain/env`, prepends the Bun dir to `PATH`, reads the admin token from its file at run time into `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` (the token is never written into the wrapper, plist or unit), resolves `gbrain` the way autopilot's wrapper does (baked installer path, `type -P gbrain` fallback) and `exec`s `serve --http --port N --public-url URL [--surface] [--enable-dcr]`. `resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists })` picks the baked program: a `gbrain` on PATH wins; a COMPILED binary — `import.meta.url` (or the injected `metaUrl`) under `/$bunfs/`, or an `execPath` that is not the bun runtime while `argv[1]` is absent/virtual — is `[execPath]` whatever its basename (release assets are renamed); otherwise the `[bun, <cli.ts>]` dev form only when that `cli.ts` exists on disk, else `[execPath]` rather than a path that cannot run; `renderServeLaunchdPlist` (RunAtLoad, KeepAlive, ThrottleInterval 30, logs to `serve.log` / `serve.err`, local `escapeXml`) and `renderServeSystemdUnit` (After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped — `%` → `%%` in `ExecStart` and both `append:` log paths, `$` → `$$` in `ExecStart`). `ensureAdminToken` (0700 dir, 0600 file created with `wx` semantics, 64 hex chars; reuse a file matching the exported `ADMIN_TOKEN_SHAPE` = `^[A-Za-z0-9_-]{32,}$` — the same regex `serve-http.ts`'s `resolveBootstrapToken` accepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise), `installServeService` (launchd: domain-explicit `launchctl bootout gui/<uid> <plist>` — failure ignored — then `launchctl bootstrap gui/<uid> <plist>`, both through the one `launchctl(run, uid, plist, { modern, legacy })` helper whose legacy `launchctl unload` / `load` fallback is used ONLY when the modern verb exits non-zero with stderr matching `/Unknown command|unrecognized|not found/i`, never on a genuine failure or a killed call, and which reports the `verb` whose result it returns; a bootstrap that fails with stderr matching `LAUNCHCTL_SETTLE_RE` (`Input/output error`, `already in progress`, `\b5\b`, `\b37\b` — launchd still unloading the previous job) is retried up to `LAUNCHCTL_SETTLE_RETRIES` (5) times, `LAUNCHCTL_SETTLE_MS` (1s) apart through the injectable `sleep` param (default `setTimeout`; `mcp-expose.ts` passes `d.sleep`), a success after retries is a note and an exhausted retry appends "(after N settle retries)" to `error`; systemd: `daemon-reload` → `enable` → `restart` so a regenerated wrapper takes effect; `loginctl enable-linger` best effort) / `uninstallServeService` (launchd: the same `bootout gui/<uid>` with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matching `LAUNCHCTL_NOT_LOADED_RE` (`No such process|not loaded|Could not find|not find service`) pushes `launchctl <verb> failed: <describeFailure>` into `notes`, and the exported `launchdBootoutFailed(result)` recognizes that note so `mcp-expose.ts` can say the job may still be loaded) / `serveServiceState` (`launchctl print gui/<uid>/<label>` / `systemctl --user is-active`); all three take `uid?: number` defaulting to `process.getuid?.() ?? 501`, threaded from `mcp-expose.ts`. Every supervisor subprocess carries a timeout — 60s for `launchctl bootstrap/bootout` (and the legacy `load/unload`) and `systemctl --user enable/restart/disable`, 15s for `launchctl print`, `daemon-reload`, `is-active` and `loginctl enable-linger` — and a `status: null` (killed) result counts as a failure (`error` / note) or `unknown` state; a failed call is described by `describeFailure` (its stderr, else stdout, else `exit <status>`). `readExposeReceipt` / `writeExposeReceipt` (`expose.json`, 0600, version 1, no secrets): the reader is a structural shape guard, not just `version`/`port`/`public_url` — it also requires `mode` in `tailnet|funnel`, a `service` object with a string `wrapper_path`, a `target` in `macos|linux-systemd|none`, a string `state` and string-or-null `plist_path` / `unit_path`, a `tailscale` object whose `binary` / `dns_name` are string-or-null, and string `mcp_url` / `admin_url` / `admin_token_file`; anything less is null (absent), so `--status` / `--remove` never dereference a half-written receipt. The token, receipt, wrapper, plist and unit writers refuse (clear error) when the target path is a symlink (`lstatSync`) before any supervisor call runs. Uses `shellQuote` from `src/core/mcp-registration.ts`; every filesystem/exec effect is behind injectable deps.- `src/core/harness/verify.ts` — Randomized server-side memory verification with revision-conditional cleanup and retained mutation UUIDs, with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.-- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work. `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL.+- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL; `test/withdrawal-followup-writes.test.ts` covers writes after a forget whose effects stay queued.- `src/core/page-state/import-guard.ts` — imported canonical bytes publish only after source/page identity and knowledge-revision CAS, including unchanged-file and legacy hash-repair paths. Prepared same-hash imports compare full canonical metadata and additive tags, since captured timestamps are excluded from content hashes. Tests: `import-revision-concurrency.test.ts`.- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex bec7493e28..8a9dc9d0db 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -324,6 +324,8 @@ export interface ProjectionRebuildOptions {notAfter?: string;/** Skip failed rows inside their retry window (PROJECTION_RETRY_READY_SQL). */retryCooldown?: boolean;+ /** Only these pages of one source. */+ pages?: { sourceId: string; slugs: readonly string[] };/** Receives each failed page; without it a generic stderr line is printed. */onFailure?: (failure: ProjectionRebuildFailure) => void;}@@ -346,11 +348,13 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =const filters: string[] = [];if (opts.retryCooldown) filters.push(PROJECTION_RETRY_READY_SQL);if (opts.notAfter !== undefined) { params.push(opts.notAfter); filters.push(`j.updated_at<=$${params.length}::text::timestamptz`); }+ if (opts.pages) { params.push(opts.pages.slugs); filters.push(`j.slug=ANY($${params.length}::text[])`); }+ const sourceFilter = opts.pages ? `WHERE s.id=$${params.push(opts.pages.sourceId)}` : '';const jobs = await engine.executeRaw<{ source_id: string; source_incarnation: string; slug: string; revision: string; page_kind: string }>(`SELECT s.id AS source_id,j.source_incarnation,j.slug,j.revision,p.page_kindFROM (SELECT source_incarnation,slug,revision,updated_at FROM page_projection_jobs j${filters.length ? `WHERE ${filters.join(' AND ')}` : ''}ORDER BY updated_at,source_incarnation,slug OFFSET 0) j- ${PROJECTION_JOB_PROBES}+ ${PROJECTION_JOB_PROBES} ${sourceFilter}ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, params);let rebuilt = 0;let superseded = 0;diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 8ee017187a..6f5d2f8ed6 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -179,6 +179,13 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr},};if (prepared.file.expectedBeforeHash !== undefined && record.beforeHash !== prepared.file.expectedBeforeHash) {+ // A coordinated writer (a withdrawal mirror) also advanced the page:+ // reprepare against it. Bytes changed at an unchanged revision are an+ // uncoordinated edit.+ const current = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ if ((current?.revision ?? null) !== prepared.observedRevision) {+ throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');+ }throw new OperationError('source_changed', 'The canonical file changed after preparation.');}const nextBytes = prepared.file.content === null ? 0 : typeof prepared.file.content === 'string'diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 268d15d482..456d98a88f 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -185,11 +185,16 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over/*** The rows `claimNextWrite` may claim, over `persistence_requests r LEFT JOIN* persistence_worktrees w`, with $1 = host id and $2 = excluded root keys. An- * unresolved head blocks its entire root.+ * unresolved head blocks its entire root. A file write also waits for an+ * unfinished withdrawal mirror of its page (of every page, for an untargeted+ * mirror), so the mirror never rewrites a file under an accepted request.*/export const CLAIMABLE_WRITE_SQL = `r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($2::text[]))AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)+ AND NOT EXISTS (SELECT 1 FROM persistence_effects mirror WHERE mirror.worktree_id=r.worktree_id+ AND mirror.kind='withdrawal-mirror' AND mirror.state IN ('queued','running')+ AND (NOT (mirror.data ? 'targets') OR mirror.data->'targets' @> jsonb_build_array(jsonb_build_object('slug',r.slug))))AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)AND NOT EXISTS (SELECT 1 FROM persistence_requests earlierWHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 1ffe33ec31..92ed720940 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -3,7 +3,8 @@ import type { OperationContext } from '../ops/contract.ts';import { OperationError, verbError } from '../ops/contract.ts';import { enforceClientSlugFence, enforceSubagentSlugFence, validatePageSlug } from '../ops/context.ts';import { isNullLikeEntity } from '../facts/write-single.ts';-import { recordFactWithdrawal } from '../facts/withdrawal.ts';+import { recordFactWithdrawal, type WithdrawalCommit } from '../facts/withdrawal.ts';+import { rebuildPendingPageProjections } from '../page-state/projections.ts';import { initializeLocalPersistence, requestPrincipalForContext } from './page-mutations.ts';import { authorizeStoredRequest, submissionAuthority } from './authority.ts';import { admitWrite, admitWriteInTransaction, assertPageRequestIdentity, assertReplayIntent, completeWrite, getWriteRequest, intentDigest } from './journal.ts';@@ -107,7 +108,9 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo`No fact with id "${rawId}".`, 'Pass the fact id returned by remember or recall.');// Retry the whole withdrawal, so source/principal guards and the connection// are released before backoff. Admission must not retry a nested savepoint.+ let withdrawn: WithdrawalCommit['pages'] = [];const done = await retryWriteAdmission(requestId, remaining => ctx.engine.transaction(async tx => {+ withdrawn = [];await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",[`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);// Source -> current grant -> counters/request -> sorted page keys -> facts.@@ -136,7 +139,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foreturn withCoordinatedWrite(tx, [sourceId], async () => {// Even an expired legacy fact acquires a ledger so a stale import cannot// reactivate it. Internal affected-page identities never enter the receipt.- await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id });+ withdrawn = (await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id })).pages;if (reason) await tx.executeRaw(`UPDATE facts SET context=concat_ws(' | ',NULLIF(context,''),$3::text)WHERE id=$1 AND source_id=$2`, [id, sourceId, `forgotten: ${reason}`]);if (operation === 'forget_fact' && fact.expired_at !== null) {@@ -148,5 +151,12 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foreturn completeWrite(tx, row, 'committed', { ...outcome, persistence: { mode: 'database' } });});}));+ // The commit removed the withdrawn pages' chunks. Rebuild them before+ // acknowledging: a CLI process exits without a resident projection worker.+ // A failed rebuild stays queued as durable projection work.+ const slugs = withdrawn.map(page => page.slug);+ for (let start = 0; start < slugs.length; start += 100) {+ await rebuildPendingPageProjections(ctx.engine, 100, { pages: { sourceId, slugs: slugs.slice(start, start + 100) } }).catch(() => undefined);+ }return writeResponse(done);}diff --git a/test/persistence-memory-mutations.test.ts b/test/persistence-memory-mutations.test.tsindex 46a44dff6e..c4d9baa5af 100644--- a/test/persistence-memory-mutations.test.ts+++ b/test/persistence-memory-mutations.test.ts@@ -283,7 +283,9 @@ describe('journaled memory publication, both engines', () => {const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;expect(snapshot.revision).not.toBe(before.revision);expect(parseFactsFence(snapshot.page.compiled_truth).facts.find(f => f.claim === 'Withdraw this unique memory')?.forgotten).toBe(true);- expect(await engine.getChunks(slug, { sourceId })).toEqual([]);+ const chunks = (await engine.getChunks(slug, { sourceId })).map(chunk => chunk.chunk_text).join('\n');+ expect(chunks).toContain('Existing biography');+ expect(chunks).not.toContain('Withdraw this unique memory');const local = await registerLocalWriter(engine, 'cli');const request = (await getWriteRequest(engine, { kind: 'local_cli', id: local.id }, requestId))!;expect(request.worktree_id).toBeNull();diff --git a/test/withdrawal-followup-writes.test.ts b/test/withdrawal-followup-writes.test.tsnew file mode 100644index 0000000000..e6bb4c1b7b--- /dev/null+++ b/test/withdrawal-followup-writes.test.ts@@ -0,0 +1,130 @@+/**+ * A forget queues its file mirror and rebuild work after it commits; the CLI+ * process that committed it exits without running any of it. These pin what+ * the next caller sees:+ * - a write to the withdrawn page is not prepared while its mirror is queued,+ * so the mirror cannot change the file under an accepted request (N5-3);+ * - a withdrawal that commits while a write is preparing makes that write+ * reprepare instead of failing as an uncoordinated file edit;+ * - the acknowledged forget leaves the page's retained text searchable (N5-2).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { prepareMemoryMutation, submitForgetMutation, submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const engines: BrainEngine[] = [];+const roots: string[] = [];+const hostId = localHostId();+let closePostgres: (() => Promise<void>) | undefined;+const context = (engine: BrainEngine, sourceId: string): OperationContext => ({ engine, sourceId, remote: false, dryRun: false,+ config: { engine: engine.kind, embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} } });++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const engine of engines) await registerLocalWriter(engine, 'cli');+}, 120_000);+afterAll(async () => {+ for (const engine of engines) await disposePersistenceConsumer(engine);+ await engines[0]?.disconnect(); await closePostgres?.();+ for (const root of roots) rmSync(root, { recursive: true, force: true });+});++/** An entity page with a canonical file and two remembered facts; no consumer is left running. */+async function entity(engine: BrainEngine) {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-withdrawal-followup-')); roots.push(root);+ const sourceId = `followup-${randomUUID()}`, slug = 'people/hazel-example';+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ const binding = await claimWorktree(engine, sourceId, root, hostId);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const snapshot = await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {+ await tx.putPage(slug, { type: 'person', title: 'Hazel Example', compiled_truth: 'Fictional.', timeline: '', frontmatter: {} }, { sourceId });+ return (await tx.readPageSnapshot(slug, { sourceId }))!;+ }));+ const file = join(root, `${slug}.md`); mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));+ const ctx = context(engine, sourceId);+ const forgotten = await submitRememberMutation(ctx, { fact: 'Keeps bees followupaaaa', entity: slug, provenance: 'test', visibility: 'world' }, 30_000);+ const retained = await submitRememberMutation(ctx, { fact: 'Plays the oboe followupbbbb', entity: slug, provenance: 'test', visibility: 'world' }, 30_000);+ expect([forgotten.state, retained.state]).toEqual(['committed', 'committed']);+ // The committing process exits: nothing drains queued effects in-process.+ await disposePersistenceConsumer(engine);+ return { ctx, sourceId, slug, binding, forgottenId: String(forgotten.id) };+}++async function admitCorrection(engine: BrainEngine, f: Awaited<ReturnType<typeof entity>>) {+ const snapshot = (await engine.readPageSnapshot(f.slug, { sourceId: f.sourceId }))!;+ const authority = await submissionAuthority(f.ctx, 'remember', f.sourceId, snapshot.sourceIncarnation, f.slug);+ const intent = { fact: 'Gave up beekeeping followupcccc', provenance: 'test', entity_slug: f.slug, visibility: 'world', fence: true,+ valid_from: new Date().toISOString(), valid_until: null };+ return admitWrite(engine, { principal: authority.principal, operation: 'remember', sourceId: f.sourceId, sourceIncarnation: snapshot.sourceIncarnation,+ slug: f.slug, pageId: snapshot.page.id, callerIntent: intent, intent, authority, requestId: randomUUID(),+ worktreeId: f.binding.worktree_id, topologyGeneration: f.binding.topology_generation });+}++async function claimAndPublish(engine: BrainEngine, f: Awaited<ReturnType<typeof entity>>, id: string) {+ const row = await claimNextWrite(engine, hostId);+ expect(row?.id).toBe(id);+ return publishMutation(engine, row!, await prepareMemoryMutation(engine, row!, f.ctx.config), hostId);+}++describe('writes after a forget whose effects stay queued, both engines', () => {+ test('a write to the withdrawn page waits for its queued mirror, then commits first time', async () => {+ for (const engine of engines) {+ const f = await entity(engine);+ expect(await submitForgetMutation(f.ctx, 'forget', { id: f.forgottenId, reason: 'test' })).toMatchObject({ state: 'committed' });+ const admitted = await admitCorrection(engine, f);+ expect(await claimNextWrite(engine, hostId)).toBeNull();+ await runPersistenceEffects(engine, f.ctx.config, { hostId, limit: 20 });+ expect((await claimAndPublish(engine, f, admitted.id)).state).toBe('committed');+ }+ });++ test('a withdrawal committed during preparation makes the write reprepare, not fail as a file edit', async () => {+ for (const engine of engines) {+ const f = await entity(engine);+ const admitted = await admitCorrection(engine, f);+ const row = (await claimNextWrite(engine, hostId))!;+ expect(row.id).toBe(admitted.id);+ const prepared = await prepareMemoryMutation(engine, row, f.ctx.config);+ expect(await submitForgetMutation(f.ctx, 'forget', { id: f.forgottenId, reason: 'test' })).toMatchObject({ state: 'committed' });+ await runPersistenceEffects(engine, f.ctx.config, { hostId, limit: 20 });+ const first = await publishMutation(engine, row, prepared, hostId);+ expect({ state: first.state, error: first.error_code }).toEqual({ state: 'queued', error: null });+ expect((await claimAndPublish(engine, f, admitted.id)).state).toBe('committed');+ expect((await getWriteRequestById(engine, admitted.id))!.state).toBe('committed');+ }+ });++ test('an acknowledged forget leaves the retained facts on its page searchable', async () => {+ for (const engine of engines) {+ const f = await entity(engine);+ expect(await submitForgetMutation(f.ctx, 'forget', { id: f.forgottenId, reason: 'test' })).toMatchObject({ state: 'committed' });+ const text = (await engine.getChunks(f.slug, { sourceId: f.sourceId })).map(chunk => chunk.chunk_text).join('\n');+ expect(text).toContain('followupbbbb');+ expect(text).not.toContain('followupaaaa');+ expect((await engine.searchKeyword('followupbbbb', { sourceId: f.sourceId })).map(hit => hit.slug)).toContain(f.slug);+ expect(await engine.searchKeyword('followupaaaa', { sourceId: f.sourceId })).toEqual([]);+ }+ });+});