Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Persistence
Subsystem index. Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
The page operations that submit through this layer are in Core Services (2/3).
Connector ingestion, item holds, checkpoint validation and the single-write fast path (switches.ts) continue in Core Persistence (continued).
Managed facts extraction (withdrawn-candidate skip and recovery, conversation facts batches, the unmanaged derived index) is in Core Persistence (managed facts).
src/core/persistence/authority.ts— durable write authority.submissionAuthorityrecords the caller's grant ceiling on every write request (scopes, operations, slug prefixes, delegated namespace and, for a delegated job, its nativesubagentIdwhen a positive safe integer);authorizeWritere-checks it against the CURRENT principal at publication and replay. For a delegated OAuth client the current namespace is the storeddelegated_slug_prefixesinprefixesmode, or onlywiki/agents/<retained subagentId>/*for the nativejobform (prefixes NULL); anything else allows nothing, and it always intersects the original accepted prefixes, bound tools, scope and source, so a revoked, narrowed or switched grant or a foreign or invalid job id denies (test/persistence-page-authority.test.ts, Postgres:test/e2e/minions-authority-parity.test.ts). #5994: a context carryingreplayAuthority(set only bygbrain repair failed-writes) gets that stored authority back fromsubmissionAuthority(replayedAuthority): same source incarnation or refused,databaseOnlyReason/takeHoldersUseddropped for admission to recompute, thenauthorizeWriteand page visibility against the live grant.src/core/persistence/activation.ts— private CLIsources writer activate --confirm-quiescedboundary. Verifies native capability and filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested--cleanup-dead-local-locksremoves exact dead same-host holders under the lease lock. Dry-run deletes nothing. Never silently claims a source. Tests:test/persistence-activation.test.ts,test/persistence-onboarding.test.ts. Unbound Google/GitHub API sources may activate as reviewedconnector_databasewithout fabricating a Git root, while bound sources still need physical-root checks. Activation incrementspersistence_brain.mode_epoch(migration 183), which the writer admin-state hash includes. A non-connector source whose recordedlocal_pathno longer exists or is relative (unclaimed, or claimed by this host) refusessource_changedwith detailsource_path_missing, naming the source, the path and thesources set-path/sources removeexits (the claimed checkout filled in), in--dry-runtoo (#5206,test/activation-missing-source-path.test.ts). The report'swarnings[](dry run and real run) carries onegit_durability_not_enabledentry per filesystem source the effect runner's policy (gitDurabilityPolicy) would leave non-durable, withenable_command, a read-onlygit-durability --enable --dry-runfix and the note that enabling re-queues skipped Git effects;persistence-admin.tsalso prints them to stderr without--json, and activation proceeds (#5182,test/writer-activate-durability-warnings-5182.test.ts).src/core/persistence/git-durability-policy.ts+git-durability-administration.ts— whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182):persistence_host_bindings.git_durability(enabled|disabled| NULL, migration v234, column SQL kept out of the replayed schema blob asPERSISTENCE_GIT_DURABILITY_COLUMN_SQL).gitDurabilityPolicy(binding, root)is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it;effects.tstakes its per-root verdict from it.gitDurabilityStaterenderson/off/unknownforwriter statusandwriter activate'sgit_durabilitylisting.planGitDurabilityCatchUp/requeueGitDurabilityCatchUpre-queue the Git effects completeddurability_not_enabledwhile the setting was off by resetting the existing rows, never inserting underUNIQUE(request_id, kind). The verbwriter_git_durability(gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run], administration-gated like the other writer verbs; a non-preview checks its approval before any side effect, #7634) runs a read-onlygit push --dry-runprobe before enabling (codesgit_branch_unborn,git_checkout_required,git_detached_head), wires the repo-scoped credential undergbrain.durability.managedcredentialfrom a 0600--pat-file(pat_file_unreadableotherwise) and retries the worktree's parked pushes (codes inGIT_PUSH_CODES;retry-effects <source> --parked-pushesdoes the same without a credential; a per-request refusal such aspage_not_foundis listed inrefusedand the run endspartial, #7110).sources push(managedPushRefusalinworkspace-push.ts),bootstrap verify'scheckPushProbeand the skill-pack writer guard name this route on a managed worktree (#5606). Pinned bytest/persistence-admin-git-durability.test.ts,test/managed-push-remedy.serial.test.ts.src/core/persistence/effect-git.ts(pushGitRoot) +git-push-holds.ts— a Git effect reads the remote tip (ls-remote), scans<tip>..HEADand pushes HEAD as a fast-forward leased on it (a missing branch: whole history first). A non-ancestor tip or a moved remote runsgbrain git commit-push --push-only --keep-checkout --scan-secretsas a child (off the event loop, never PATHgbrain): it merges in memory and pushes without moving the checkout or running pre-push hooks, sosources refreshstays the only importer. Holds:publish_secret_found,publish_scan_unreadable, orintegrate_conflict(the user picks--resolve).readGitPushHoldscounts each source's effects retrying or parked on a push code, with conflict state and one fix, for doctorparked_effectsandsync statusgit_push_holds(nextfalls back to a held fix). A hold in an unbound worktree isformer_worktree(fix: settle preview, #7378). Pinned bytest/pathological/h2-git-effect-moved-remote.test.ts.src/core/persistence/deactivation.ts— private CLIsources writer deactivate(#5455/#5628), brain-wide and trusted-local.deactivationBlockerslists the admin lock, queued/running/recovering requests, recovering topology changes, queued, running or recovering effects (the predicate activation uses; each exit says what clears it, and a failing links or facts-backstop effect settles after five attempts), held connector items (managed holds that classic mode would not read) and livegbrain_cycle_locksleases, each with its CLI exit;failedEffectHistorylists terminally failed effects as history (failed_effectson the dry run and the applied report, never blockers), each with its code and the exit that retries it: retry-effects for parked targets and failed Git, withdrawal, links and facts-backstop effects,repair embedding-effectsfor a failed embedding effect, none forembedding_zero_normor an effect whose source was archived, replaced or removed (test/pathological/a15-deactivate-exits.test.tsruns every printed exit and checks it clears its entry);physicalRootBlockers(engine, mode)(#5914 [R9a]) addsphysical_rootfor this host's owned checkouts, probed as the mode's real run will: strictassertPhysicalRootfor managed,assertPhysicalRootReservationfor the classic pre-activation release, so each preview lists exactly what its real operation refuses on;--dry-runreturns them plus the worktrees that would retire, the kept shared-skill settings and, when clean,apply_commandbound to the admin state read before the preview.deactivatePersistencetakes the local native worktree locks, then in one transaction lockspersistence_brain FOR UPDATE, checks the expected admin state and the admin lock, locks worktrees then sourcesFOR UPDATE(admission's order), rechecks the blockers, setsenabled=false, incrementsmode_epoch, retires every worktree, deletes source and host bindings and records a committedwriter_deactivatetopology change (brain id, retired epoch, retired worktree ids and roots, source roots).cleanupRetiredManagedMarkersruns on CLI connect, after deactivate and fromwriter status: it removes this brain's registry records,.gbrain-managed/ Gitgbrain-managed.json,.gbrain-owner.jsonand reservations only when theirmode_epochis a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reportedpending, each file is re-read before unlinking and other brains' files are never touched.root-registry.tswritesmode_epochinto new registry records and managed markers. Tests:test/persistence-deactivate.test.ts(PGLite and Postgres),test/e2e/persistence-deactivate-race.test.ts. See persistence stalls.src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts—admin-lock.tsowns the opt-in brain-level writer admin lock: reserved config keypersistence.writer_admin_lock({locked, set_at, host_id, generation}), written only by localgbrain sources writer lock|unlockunder thepersistence_brainrowFOR UPDATE; lock refuses while a prepared transfer is unaccepted.assertWriterAdminUnlockedruns inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses withwriter_admin_locked; only the ordinary first-write auto-claim (claimWorktree(..., { automatic: true })from page and memory mutations) is exempt. Genericconfig set/unset/unset --patternrefuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it.blocking-effects.tslists queued, running or recovering effects (listBlockingEffects) and buildswriter_not_quiescedsuggestions naming the first blocking request or effect withgbrain sources writer status <source> --json.writer-versions.tsstamps admitter version/host at admission and consumer version/host/published_atonly on committed publication (migration 178, cutoffpersistence_brain.writer_version_cutoffon the database clock); replay and compaction keep stamps.sources writer statusreportsadmin_lock,local_host_id,blocking_effectsandwriter_versions;src/commands/doctor/checks/writer-version.tsis the seven-daywriter_versionadvisory.SEGMENTED_WRITER_FLOOR(page-body/writer-floor.ts): a seven-day writer below it or unmarked keepspages.segmented_storageoff (page-body/limits.ts, doctorsegmented_storage); marked rows of any role meet the floor (ingest log: two partial indexes, v254/v259). Tests:test/persistence-writer-admin-lock.test.ts,test/persistence-writer-versions.test.ts,test/persistence-blocking-effects.test.ts,test/e2e/persistence-writer-{admin-lock,stamps}.test.ts.src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts— resident dispatch for durable atom publication/completion, explicit atom retry (retryManagedAtomBatchtakes the job's signal and deadline, stops between stages on caller cancel, deadline or cycle-lock loss, shares one deadline-boundMaintenanceWriteWaitwith the model rerun, and reports a stop after admission aswrite_pendingor anAbortErrorcarrying the receipts, nevercancelled; #6622; a transcript item that does not resolve to the retry's source is refusedtranscript_source_mismatchbefore anything starts, #7869), authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (runLintCorepublishes each fix throughmaintenancePreflight+publishMaintenancePage; #5180,test/managed-lint.test.ts).page-prepare.tskeeps the stored provenance stamps on every remote page write, repo or not (keepStoredProvenance,provenanceWriteTrust: tier by the lower of caller and published frontmatter; #7873); it exportsfileMatchesSnapshot, the canonical file-versus-page comparisonprepareFileTargetapplies, so lint can bind a repair to the revision it read (it takes the importer's path for the file: a frontmatter-less file under a directory-inference rule also matches whenreadCanonicalAsImported(BOM strip +applyInferenceatscannerSourcePath) reproduces the stored row, with an inferred type treated as undeclared, #6605; reconcile reads the file side throughreconcileFileReadinginreconcile-state.ts); the uncoordinated-local-edit refusal carries detailfile_database_driftand asources reconcile <src> <slug> --brain host --previewfix; a shared-origin delete: canonical-reconciliation.md. InprepareFileTarget, a live page whose canonical file is missing refusessource_changedunless it is declared or derive-phase database-only, or it is adelete_page(deleting, no content) of a page with no recordedsource_pathand no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (test/persistence-captured-file-target.test.ts,test/persistence-never-published-delete.test.ts).atomOwnerTargetis the one owner decision for an atom session and foratomDrainOwnerRefusal, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through theconnector_databasetarget (itslocal_pathis connector state, not a checkout) and the publication refuses withsource_changedwhen the source gained an owner after preflight.submitMaintenancescans every content-carrying intent withscanCanonicalFences(the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline;replaceOrInsertFactsFencereplaces only the first) is refused with its fence reason, sofenceManagedreports the page infailed_pagesand the others still adopt, while a repair whose postimage is clean passes.prepareFactFenceAdoptionnames its steps forenterClaimStep, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back intofacts.factin the sameUPDATEthat setsrow_num(so the projection keeps the fact's id), and throws the registeredfence_unrenderable(classserver) as its last-line defence.maintenancePreflightcreates the job'sMaintenanceWriteWait(optionaldeadlineAtMs) andsubmitMaintenanceuses it for new and replayed requests; its owner check goes throughcheckOwner/ownerUnavailableError(owner-refusal.ts), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuseowner_unavailablewith their ownreason, and nothing claims or transfers ownership to get past them. #6325:resumeManagedAtomsreturnsrun | done | held. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key isdigest([drainKey, failedRequestId, 'automatic'])(one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (attempts); atMAX_DETERMINISTIC_FAILURESit setsheld, whichMANAGED_ATOM_DISCOVERY_SQLexcludes from discovery and the backlog andlistHeldManagedAtomsreports (doctorextract_atoms_held_failed, codeheld_failed). Reading a held or failed checkpoint never strikes; storage and authority errors fail the attempt without completing it, so they never strike either. #7514 write-failure strikes and hold: continued. A content change is a new drain key, so the count starts over. An explicit retry (session.retry) ignoresheld, and its failure refusal (extraction_failed) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paidfix(gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}') with a read-onlygbrain write-requestverify; the drain raises it only for a failed batch whose checkpoint is gone. Tests:test/managed-atoms-retry.test.ts. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in Core Persistence (managed facts). Atom completion admits replacement and revision-pinned stale-atom deletion children together. A failed, partial-input or zero-yield batch admits no retirement, and each retirement child refusesrevision_conflictuntil every replacement page of its run is committed (replacementPublished), so a partly published batch leaves the prior generation live. Each retirement stampsretired_by/retired_atinto the tombstone in the same publication;publishManagedAtomsrestores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (op_checkpointsopmanaged-atoms-generation, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's olderextract_atoms_page_staterows and completedmanaged-atomscheckpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order. Derived atom pages may regenerate or retire when their canonical file is already absent, while ordinary page writes retain missing-file refusal. Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronologicalvalid_untilwriteback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority.submitMaintenanceIntentadmits a maintenance request with its own intent kind keyed by the intent;prepareMaintenanceMutationalso handlesmanaged_maintenance_phantom_mergeandmanaged_maintenance_phantom_delete(both delegated tocycle/phantom-redirect-managed.ts).publishMaintenancePageaccepts an optionaleventProjection(Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.src/core/persistence/canonical-projections.ts— installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (cli:extract-conversation-facts*) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes:editing(revision-boundput_page, reconcile with an approved body decision),preserving(put_pagewithout a revision, reconcile, connectors),file(managed sync of file edits and managed import) andimmutable(company-brain imports). One pure decision table (timelineRowAction) maps each row state (in_body,drifted,removed,removed_marked,database_only) torefresh_detail,delete,keepormaterialize: database-only rows are materialized byeditingandpreservingwriters and kept by the others; #6226 rows the older citation reading filed for either body aresuperseded(deleted by every writer) or, carrying their own detail,superseded_annotated(kept, never materialized); a materialized bullet the new body drops is deleted byediting/file, rendered again bypreservingand kept DB-side byimmutable.materializeTimelineruns during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (timeline-marker.ts);renderMaterializedBulletrequires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered.pendingTimelineRowscounts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typedinvalid_fence(fence-repair/refusal.ts):compileCanonicalProjections, the validation-only entry, refuses the first defectscanCanonicalFencesfinds (repeated marker, any strict-parser warning, a row number used twice on the page) with wireinvalid_params; a new fence row whose number belongs to a database-only take refuses asstored_row_collisionwith wiretake_row_collision. When the prior takes fence does not parse, the page's storedtakes.row_numcount as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding.unrecordedCanonicalTimelinereturns the body's canonical tuples with no stored row under the normalized key (managedextract --staleinserts only these), andmaterializedHistoryRangeslocates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests:test/canonical-projection-history.test.ts,test/timeline-materialize.test.ts(PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused asinvalid_fence/quoted_fence_rowsinstead of deleting them. Pinned bytest/fence-marker-projection.test.ts. #8819: seefence-evidence.ts. #5969 (D3): an ordinaryput_page/put_pagesintent carries aTimelineWritePolicy(timeline-omission.ts) that changes only the rows the writer saw (removed,removed_marked): an explicitly empty section deletes them for every writer class; an omitted section keeps them for a local preserving writer (materialize) and deletes them withdrop_timeline; maintenance, reconcile and file writers pass no policy. The pinned timelineDELETEreturns what it removed, and the projection closure returns{ timelineRowsRemoved: { count, earliest, latest } }counting onlyremoved/removed_markedrows it actually deleted (a row changed after preparation is neither deleted nor counted);timelineRowsToRemovejudges the same set ahead of publication. #6259: a quarantined page (gatequarantinemarker) projects no facts or takes (timeline rows still project); rows projected before it was quarantined stay as they are.src/core/persistence/timeline-omission.ts— #5969 (D3):timelineSectionOfreads a put_page body's Timeline section from the caller's raw content before normalization (omitted: no timeline sentinel and no## Timeline/## Historyheading outside code;emptied: a section with no entries;present). Admission (page-mutations.ts) records it on the intent astimeline_section(a caller-sent value is stripped; failed-writes replay passes the stored one throughsubmitPageMutation'stimelineSection).assertTimelineNotOmittedrefuses a remote omission that would delete rows withtimeline_rows_would_be_removed(fix:get_page include_content:true, then thedrop_timeline: trueretry) before admission and again during preparation;timelineWritePolicybuilds the projection policy. Successful deletes surface as the receipt'stimeline_rows_removedadvisory (page-advisories.ts, dates only), copied ontoput_pagesentries (page-batch.ts, which acceptsdrop_timelineper entry).src/core/persistence/health.ts— pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live intest/e2e/persistence-http-liveness.test.ts.src/core/persistence/effect-facts.ts+page-advisories.ts+derived-extraction-gate.ts— bounded writer-lint/facts-backstop outbox.dispatchFactsBackstopEffectstamps the job'snotabilityFilterfromfacts.page_write_notability_filter(defaultall;facts/notability-filter.ts), read inside the dispatch transaction so retries keep one filter (#6231). The job also carries the stable sessionput_page:<slug>(mirrors sync'ssync:<slug>), so a re-extraction of the page feeds the #6333would_dedup_same_pageshadow counter and the facts it writes record thatsource_session(visible torecall --session).derivedExtractionSkipis the writer-confinement rule facts and Life Chronicle share (slug-bound/delegated/restricted →slug_bound_client; an operation-bound grant withoutextract_facts→operation_bound_client). Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling; a write that keeps thecompiled_truth(the only text extraction reads) of a live, already-eligible page skips withbody_unchangedonly when a facts-absorb job bound to that page id has completed and no facts-backstop effect or startable facts-absorb job for it is still pending (the new revision would supersede it), so a timeline or frontmatter-only republish such asrepair timelinequeues no extraction for an extracted page, while a page no extraction ever completed for still queues one. Wave B PR 2: a segmented page queues the effect like an inline one (bodyAlreadyOfferedis false for a segmented prior or an unread body); the facts-absorb job hands the backstop the page's boundedtruthLeadand its id, andrunPipelineplans the extraction text withplanSegmentedExtraction(extraction-watermark.ts: one streamed pass over the stored truth, head plus the newest tail window), so the job never reads the throwing body (test/large-pages/segmented-derived-work.test.ts). Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests:test/persistence-facts-backstop.test.ts,test/managed-facts-backstop.test.ts.src/core/persistence/effect-recovery-scan.ts— bounded owner-scoped recovery selection rotates through durable effect IDs even when an earlier root has no available native lock, and wraps to retry prior roots. It never changes recovery authority or releases reservations.test/persistence-effect-recovery-fairness.test.tsholds two real native roots, recovers a later mirror, then verifies wraparound cleanup and exact counters on both engines.src/core/persistence/page-input.ts— freezes scoped subagent type normalization at durable admission, after existing-request replay. An explicit undeclared model-authored type becomesnotewithlegacy_typeretained using the then-active schema pack; a replay keeps its original normalized payload when the pack changes. Caller intent remains unchanged for idempotency checks. Raw input size is checked before normalization and malformed Markdown is left to the importer’s sanitized error contract.test/brain-allowlist.test.tspins changed-pack replay, raw-size refusal, and private parse-error redaction.undeclaredPageTypeWarningcovers every otherput_page(not managed file imports): a type the write source's pack neither declares nor aliases is stored as written and the committed result carriestype_warning(code: page_type_undeclared, cause, fix, docs), also logged; pinned bytest/put-page-type-warning.test.ts.src/core/persistence/params.ts— runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle.preconditions.tsvalidates UUID/revision/force syntax.purge-params.tsvalidates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans.test/persistence-cold-import.test.tsloads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.CAPTURE_EVENT_PARAMSare full-surface-only.src/core/persistence/write-wait.ts— the CLI write-wait and exit contract (#5232).resolveCliWriteWaitMs(--waitseconds >GBRAIN_WRITE_WAIT_MS> file-planepersistence.write_wait_ms> 30 s; agents keepAGENT_WRITE_WAIT_MS);writeExchangeBudget(transport deadline = wait + 15 s admission headroom; an explicit--timeoutshortens the requested owner wait instead);replayWhilePending(replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-suppliedsleepdecides how each pause ends, which is how subagent tool writes stop on abort);writeErrorExitCodekeys on an admitted non-terminal receipt (admittedPendingReceiptintypes.ts): pending →PENDING_WRITE_EXIT_CODE(0 with--accept-pending/GBRAIN_ACCEPT_PENDING=1whenacceptPendingCoversholds: nodiagnostic.ownerstale-owner block, GBRA-248), anything else → 1. Pinned bytest/pending-write-exit.serial.test.tsandtest/pending-write-exit-owner.test.ts.pollCommand(#6255) renders the envelope's receiptfix.argv(gbrain write-request --brain <id> -- <request_id>), else pins that argv to the CLI routing; each argument is shell-quoted (src/core/shell-quote.ts, fix wave 13 P1.15).src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts— bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors.effect-targets.tsconverts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (claimCoalescedGitEffects, same readiness, recovery and withdrawal-mirror ordering predicates,SKIP LOCKED); the runner validates each path under the worktree lock, makes onecommit-treeper group (commitGitTargets: onels-files,status,addanddifffor the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (pushGitRoot). A page file target's optionalcommitnote (GitCommitNote, set only by trusted local preparers: a fence repair'sfenceRepairCommit) is queued ascommit_subject/commit_linein the Git effect's data and passed by the runner tocommitGitTargets/publishGitEffect: a noted path committing alone takes its subject; a group keepsgbrain: persist N canonical memory updatesand lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (test/fence-repair-receipts.test.ts). A group yields to publications still queued or running for its worktree (one update requeues it withpublication_pending, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait).claimCoalescedGitEffectschecks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walkspersistence_effects_pendingin order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued withgit_push_unavailable, and the next pass finds nothing to commit and pushes once. Every path listing compares relative to the source root, which may sit below the Git toplevel (#7091: status prefix stripped,diff --relative). That holds for a removal too (#7089): its retry finds the path untracked and absent (target_absent), and it joins the push while the root is ahead of its upstream (gitRootAhead, a localrev-list @{upstream}..HEAD, no upstream is not ahead), as doespublishGitEffect, recordingtarget_absentwith the push result; on a root that is not ahead it completes without a push, so a down remote never parks it. A Git page walk that ends while its durable root is ahead pushes before completing (test/persistence-git-removal-push-7089.test.ts+ Postgres wrapper). In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records thedurability_not_enabledoutcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests:persistence-git-coalescing-5530.slow.test.ts+ Postgres wrapper). A Git effect for a declared db_only page completes as skipped (reason: db_only), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (data.target_failuresfordata.failing_target, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits), transient database failures and raw errorsclassifyItemFailurecalls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). Alinksorfacts-backstopeffect counts its failures the same way (data.target_failures, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts asstatement_timeout): at five a links effect completes as skipped with the code (outcome: { links: 'skipped', reason }; the edges are derived andgbrain extract --stalerecovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under anItemRun(effects.derived_retry_budget), and a pass where most of them failed counts none (each retries asitem_failures_systemic) (GBRA-130 A-11,test/pathological/a11-effect-retry-budget.test.ts). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (MAX_RATE_LIMIT_RETRIES) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (isEmbedRetriableError), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13,a13-embedding-target-park.test.ts): a scan records it indata.parkedand moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes asfailed/targets_parked, never committed. A mirror or Git scan never parks on a sync-skip metafile page (RESOLVER.mdcarries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (file_database_drift): the mirror materializes the withdrawal in the database without touching the file, both scans record the page indata.skipped(at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). A page stored in segments is mirrored and committed too, streamed (see the segmented withdrawal mirror entry incore-persistence-request-indexes.md). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (mirrorGates, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (withdrawal_mirror_pending); otherwise the mirror's recovery records each page whose file it rewrote (data.published) and its cursor is never proof: a Git page walk commits a page the mirror passed only when the file's raw bytes hash-equal the mirror rendering of the current snapshot (the serializationmirrorPagewrites; this also covers a mirror from before publications were recorded and a published file later reverted by hand) and otherwise skips it (withdrawal_not_mirrored), a single-file Git effect needs the recorded publication, embedding behind a failed mirror needs the recorded publication, and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked withwithdrawal_mirror_failed, so Git never commits a file that may still hold withdrawn text. When the mirror commits, the same transaction re-arms its request's Git and embedding targets parkedwithdrawal_mirror_failed(rearmWithheldTargets: a scan revisits them throughdata.retry_slugs; other parks stay), and each effect pass repeats it for the requests it touched, so no second retry-effects is needed. Lifecycle settlement (topology-locks.ts) waits on a queued mirror, not a failed one (A-12,a12-withdrawal-mirror-gate.test.ts). Migration 170 indexes parked effects for theparked_effectsdoctor check.retryParkedEffects(theretry-effectsadmin path) previews parked targets or authorizes one more attempt per target (data.retry_slugs, visited before the cursor); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failedsource_changedreruns from its cursor once the source is back) and an embedding effect that failedsource_changed, so one call reruns a failed mirror and re-arms the pages it withheld;parkedOnlykeeps the credential-change retry (retryParkedPushes) to parked Git and withdrawal effects; tests:persistence-effect-parking.test.ts.repair embedding-effectsskips failed embedding effects with parked targets and zero-norm refusals. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests:persistence-effects.test.ts,persistence-git-publication.test.ts,persistence-publication-native.serial.test.ts. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly.retry-effectsis an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) isgit_index_lockedcontention (retried, not counted toward parking) while the lock is younger than 10 minutes, andgit_index_stale(counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lockindex-lock-reclaim.tsproves abandoned (its header lists the proof), with a receipt doctorparked_effectsreports, then retries the step and the effects that lock parked; otherwisegit_index_stalecarries anask_userfix. Steps run withGIT_OPTIONAL_LOCKS=0, an index-scaled deadline (gitStepTimeoutMs) and a 10 s SIGTERM grace (#6932). #9227:gitReceiptStatemaps a classic write's Git effect to the receiptpublicReceipt(ops/persistence.ts) returns in place of the storedgit_state: queued:committedwithgit_commit, orsuperseded,skipped,failedorretryingwithgit_reason(test/persistence-receipt-git-state.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:maybeDelegateLocalOperationreturns unhandled and the engine path waits for the PGLite lock instead of answeringowner_unavailable; a serve holder or an answering socket keeps every failure final. Owner-sideresolveSourceId(..., { skipLocalSignals: true })prevents serve env/dotfiles from overriding client routing. For an op that owns asourceparam (opOwnsSource,src/core/ops/contract.ts),params.sourcestays 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 trustedlocal_cliprincipal's allow-listed skill-administration ops with the'stdio'locality marker, so the fourlocalOnlyones (get_skill_retention,prune_skill_revisions,retain_skill_revision,import_skill_proposal) work while a serve owns the brain, as dotakes_removeandtakes_rebuild(LOCAL_CLI_LOCAL_ONLY_OPS) for thelocal_cliprincipal (write scope still checked;gbrain takes removeandgbrain takes rebuilddefer their engine like the other takes verbs); other local calls keep no marker (test/persistence-local-only-ops.test.ts).bindResolveIpcForServeaccepts the provider as its third argument and closes the dedicated listener with hook IPC.residentPersistenceConfigresolves 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-onlyprojection_statusrequest (likecapabilities) returns the resident's projection backlog counts (PersistenceProjectionStatus, no identifiers) so doctor'stext_projection_readinesscan 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 asraw_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-onlyfile://URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under astorage.db_onlydir declared ingbrain.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 receiptwrite_through.skipped: db_only; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never readgbrain.yml.gbrain.ymlis read from the source root, like doctor, export and backup, not the git rootmanageGitignoreuses, which differs for a monorepo-subdir source.source-storage.tscaches 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 reportsstorage_error, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicittype:(the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses withdetail: file_database_drift(over 24 MiB:body-digests.ts) and a filledsources reconcilecommand; when sync holds the page's file (sync-holds.ts), the drift and occupied-path refusals name the hold instead (location-free message fromverb-errors.tsheldFileMessage, mapped back byheldFileDiagnosticin receipts andservice.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 withrevision_conflict), so later pages cannot flip the inference. A new page captured from a file inside the source (capture_path, resolved from the trusted CLIlocal_fileinpage-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 recordssource_uri: cli-file, never a host path.acquireWorktree(binding, waitMs, signal, engine)re-stamps a device-only physical-root change under the native lock (seephysical-root.ts); without an engine, or when birth time is zero, it refuses withdetail: physical_root_device_changedand the filled self-transfer commands. Version snapshots retain nullableis_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.tsreads everypersistence.limits.*cap andpersistence.receipt_retention_days(default 30) from the database config table (JOURNAL_CONFIG_KEYS, registered forgbrain 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 cumulativequeue_capacityrefusal names its key indetailand suggests agbrain config setvalue 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.tsexercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery;test/persistence-capacity.test.tscovers retention, the compaction filter, capacity hints and default sizing.service.tsalso dispatches operationdecide_proposal(S9 proposal accept/undo) tofacts/proposal-supersede.ts. FENCE REPAIR RECEIPT:fence_repairis a reservedput_pageparam;preparePageAdmissionrefuses it (invalid_params) on every operation unless the call is a trusted local (ctx.remote === false)put_pagewhose valueparseFenceRepairReceiptaccepts;page-prepare.tsre-parses it from the stored intent, returns it in the outcome asfence_repairand gives the page's file target thefenceRepairCommitnote for its source-relative path. GOOGLE PUBLISH MODE: a page target is aPageMutationFile(MutationFileplus optionalpublishModeandcommit). The Google callers setpublishMode: 0o600at prepare time from the stored connector (prepareConnectorMutationinconnector-sync.tswhenp.connector === 'google', andprepareGoogleReceiptPatch); it is never part of the submitted intent, so request ids are unchanged.publishFilethen creates missing directories withmkdirPrivate(dirname(path), root)(0700) instead ofmkdirSyncand opens the stage withmode ?? publishModethroughAtomicWriteOpts.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: thepersistence_brainrow, then worktree rows (id order), then source rows (id order), thenpersistence_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, thensettleTopologyRequestslocks thebraincounter) and activation hold it FOR UPDATE before their worktrees, sources and counters. SodeclarePersistenceProtocolanddeclareDurablePersistencetake the brain row FOR SHARE in the same statement as their settings (afterlock_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 slock_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'sbrain_before_rowsrule (scripts/persistence/lock-order.ts,test/persistence-crash-robot.test.ts).isPersistenceDeclarationand the BEGIN pipelining built on it: Core Persistence (continued).src/core/persistence/{semantic,semantic-pages}.ts— revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot (mayReprepare:revision_conflictor, #5385 [R13],revision_required, both only when the caller named noexpected_revision); exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. Theadd_timeline_entryreceipt carriesbullet, the rendered Markdown line (#5970): there is no update/remove verb because the page is the system of record, so the caller corrects an entry by editing that line withedit_pageand the row follows the page (both timeline op descriptions say so;test/timeline-correction-path-5970.test.ts). #5251:add_tag/remove_tagprepare withdeferEmbedding: true(a tag change leaves every chunk's text as it was, so noembeddingeffect is queued andembedding_statereadsdeferred; the stale sweep still covers any chunk the republication left without a vector); the full page republication they ride stays, so the issue stays open. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics.page-state/projections.tscompletes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests:persistence-semantic-pages.test.ts,page-projection-concurrency.test.ts.src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts— migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards;withTopologyLocks(..., { relocation: true })(rebind only, #5914 P1.3c) verifies a recorded root that now resolves through a symlink to the rebind target withinspectRelocatedPhysicalRootinstead of the realpath check, and the rebind transaction then callsrelocatePhysicalRootand moveslocal_path, the host binding andrelative_pathin place of a new worktree; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. A managed add by a remote caller recordsadded_by_remote_callerin the source config (managedSourceAddInput), and an add or reclone of such a source passesskipLfstocloneTopologyCheckout, which writesLFS_OFF_CLONE_CONFIG(git-remote.ts) into the clone ascloneRepodoes. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keepdigest,file_count,canonical_stampandself_transferbut no per-file map (#5790), so their size is independent of the worktree;compactStoredManifestdrops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. #5200 (W14 P1.4): only a lifecycle operation that compares or records checkout bytes (addat an existing root,claim,rebind,restore;recloneintopology-clone.ts) walks and hashes the checkout;archive,removeandpurgeskip the walk when every binding of the source already carries a verifieddigestand refresh the stored manifest'scanonical_stampin place (manifest = COALESCE(manifest,'{}') || {canonical_stamp}), so a symlink that appeared after the claim no longer refuses a retire (a binding claimed before activation has no digest yet, and the retire records that first manifest because clone recovery needs it), and every dry run reportsmanifest_requiredso preview and real run agree (test/source-retire-symlink-manifest.test.ts). Thewriter_manifest_unsafetext names the manifest, not a transfer, since claim and rebind raise it too. Large-repo tests:test/persistence-large-manifest.test.ts(12k files, both engines viatest/e2e/persistence-large-manifest-postgres.test.ts) andtest/e2e/persistence-large-manifest-50k.test.ts. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests:test/persistence-source-lifecycle.test.tson PGLite and guarded isolated Postgres. #6099: manifests are Git-scoped for Git checkouts; seeworktree-manifest.tsin managed sync and persistence stalls.