Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Persistence (request indexes, fault seams, stuck recovery)
Subsystem index · Core Persistence · continued. Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
The online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index, dream postprocessing's request-id index, the write claims' foreground-commit index, the gbrain repair failed-writes preview's replay-id and page-sequence indexes, whose absence or INVALID state its repair_preview_timeout refusal names), the checkpoint validation they serve, the named fault seams the persistence gate and the purge tests inject at, and the stuck-recovery resolution (gbrain repair stuck-recovery) that uses them.
src/core/persistence/checkpoint-validation.ts— the managed sync checkpoint's incomplete-receipt validation (#5762):INCOMPLETE_SYNC_RECEIPT_SQLis threeLIMIT 1probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served bypersistence_requests_recovery,persistence_requests_sync_run_openandpersistence_requests_sync_run_committed, with the same result as the former single predicate.findIncompleteSyncReceiptreturns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transientcheckpoint_validation_timeout.readRequestIndexStatesreads each index ofPERSISTENCE_REQUEST_ONLINE_INDEXES(or the list passed) as valid, missing, INVALID or building (Postgrespg_stat_progress_create_index);formatCheckpointTimeoutHint/checkpointTimeoutHintis the one formatter for the three-state hint and the filled retry (gbrain sync --source <id> --no-pull --retry-failedplus the cursor-selecting options the checkpoint intent records insyncOptionsand the saved processing flags), used by the sync summary andget_write_request. Tests:test/persistence-sync-checkpoint-validation.test.ts,test/e2e/persistence-request-indexes-postgres.test.ts.src/core/persistence/fault-points.ts— named crash seams for the persistence gate.faultPoint(point, detail)is a no-op unless a gate worker installed a hook withinstallFaultHook; production never does. Seams:publication:<boundary>(the fivePublicationHooks.boundarynames, routed throughwithFaultPointsinpublishMutation),effect:<kind>:midfor everyEffectKindincompleteEffect(after the side effect, before its completion is recorded;EFFECT_FAULT_POINTSis aRecord<EffectKind, FaultPoint>),effect_recovery:before_clear(effect-recovery.ts),large_file:stage_streaming(after each piecestageStreamedContentwrites to a stage's in-progress name),effect_recovery:before_stage/effect_recovery:staged(a streamed, version 2 withdrawal mirror: once its record is durable, before its file is streamed into the publication stage, and after that step, before the recovery transaction renames the stage),publication_recovery:before_clear(recoverPublication),sync:mid_checkpoint(after each committed cursor step insync-run.tssaveCursor),sync:after_freeze(#6712 PR 0: at the end offreezeEntryfor an import entry, after its bytes are read and before the request is admitted; detail carriesslugandpath),consumer:prepared(between preparing a claimed request and publishing it),stuck_recovery:*(between the steps ofrecovery-resolve.ts) and the purge lookupspurge:*(page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used byscripts/persistence/crash-robot.ts, the #6511 tests andtest/sync-convergence.serial.test.ts, which installs it in realserve/syncprocesses through thetest/fixtures/convergence-fault-kill.tspreload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).src/core/persistence/recovery-resolve.ts+src/core/repair/stuck-recovery.ts—gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>](#6650 §1.10; GBRA-130 C-1, C-4), explicit-only, preview-bound and destructive (registryconsentText;--apply --expect <hash> --keep prior|disk|withdrawn --yes, a non-interactive apply without--yesexits 3; a--keepsome approved record does not offer refusesrecovery_choice_refusedin the kind's plan before anything runs).scanStuckRecoveries(owner host only, elseowner_unavailablefor a named source) reads the source's queued head blocker (readHeadBlockers; itsrequest_recoveryids select the records) and every non-terminal recovery record on the worktree blocked onunexpected_file_bytesor whose file matches neither recorded version: a page record (target: 'page') or a v2 shared-skill bundle record (target: 'skill_bundle', every file of the bundle; a file matches a recorded version only whenbundleFileHashalso accepts its mode and shape). A bundle recordrecoveryFilescannot read is listed inrefusedasrecovery_bundle_unsupported(residualbundle_refused; named with--request-idit throws with the same ask_user fix). Every withdrawal-mirror effect recovery on the worktree whose file is not a regular file holding its pre-withdrawal or withdrawn bytes is an item too (target: 'withdrawal_mirror', ideffect:<id>,effect_id, the forget'srequest_id; its file view addswithdrawn, the recorded post-withdrawal fingerprint, and its only choice iswithdrawn); a record without usable withdrawn bytes, or bound to another owner epoch, root or incarnation, is listed inrefusedasrecovery_effect_unsupported(residualeffect_recovery) withfix{ ask_user, argv: gbrain repair stuck-recovery --source <id> --request-id <request> }and auser_message, and named with--request-idit throws with that fix; a blocked terminal request is listed inrefused(residualterminal_refused; named with--request-idit refusesrecovery_choice_refused, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior (an effect'swithdrawn), disk and unified-diff files 0600 under~/.gbrain/backups/stuck-recovery/<request>/<digest>/(a private directory outside every checkout) and prints thediff -ucommand. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page'sknowledge_revision.resolveStuckRecoveryruns underacquireWorktreewith a bounded wait (10 s, thenwriter_lock_unavailable; so the resident recovery pass returns unchanged), re-verifies the digest (preview_changed) and journals inop_checkpointsopstuck-recovery-resolutionkeyed<request row id>:<preview hash>(exempt from the checkpoint purge; the finished row is the audit entry):backed_up(disk and prior bytes durable, always), thenwritten(--keep prior:upgradeRecoveryStagingreserves an older record's restoration stage within the recovery budget,queue_capacityotherwise, then the prior bytes are published throughpublishPersistenceFileat that stage aftercleanupRecoveryStaging, an absent prior unlinked) orabandoned(--keep disk, #6640's drop:completeWriteends the live requestconflictsource_changed, orfinishUnpublishedFailurewith its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path'sclearResolvedRecovery), thenrecoverPublication(…, alreadyLocked)finishes by its unchanged rule and the journal recordsdonewith the result. A step refusesunexpected_file_byteswhen the file changed again; a different--keepfor the same hash refusesidempotency_conflict; an identical apply afterdonereplays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reportsfinished_by: another_pass.--keep prioron a request with no recorded failure requeues it (the accepted write publishes again).--keep diskhands off togbrain sources reconcile <source> <slug> --brain host --previewand never reports the page repaired; on a git-canonical source (binding.canonical_git) a page's follow-up is commit (gbrain git commit-push --path <checkout>) orgit restore, then sync, with anask_userfixin the item detail (strictKeptEdit, #7715). A record whose prior file is over the single-string ceiling (staging.before) resolves the same way in bounded memory: the disk file and the staged copy are hashed in pieces (the copy's state,verified,missingormismatched, is in the prior view and the digest), backups are kernel copies checked by streamed hash, the diff file is a summary (both fingerprints, the first differing byte, a window of at most 1 KiB;cmpreproduces it),--keep priorruns recovery'srestoreBeforeStageaftercleanupRecoveryStaging(keepBefore), and--keep diskbacks up a mismatched copy (<index>.prior-stage) and removes it before abandoning.--keep priorwithout a verified copy refusesrecovery_prior_stage_unavailable(registry entry; its fix is the--keep diskapply under the same hash). An effect item resolves throughresolveEffectRecoveryunder the same lock and journal (keyeffect:<id>:<preview hash>):backed_up(the edited bytes beside the withdrawn bytes and their diff),written(firstrebaseStaleEffectRecovery(effect-recovery.ts): when a later withdrawal moved the page past the record, the record is rebased under its page lock on the latest snapshot'smirrorContentbytes (the renderingmirrorPageitself writes), its publication stage and reserved bytes following them, and the journal stores the rebasedidentityin the same transaction, so the recorded bytes never put a later-withdrawn fact back on disk and a rerun resumes; a page deleted, replaced or segmented meanwhile refusesrecovery_effect_unsupportedwith nothing written; thenupgradeRecoveryStagingforwardand the record'safterbytes published at its publication stage, mode restored), thenclaimAndRecoverEffect(effects.ts, the resident pass's own claim +recoverEffectPublication+ failure recording) materializes the page, clears the record and advances the effect's cursor, andtrueUpRequestssettles the forget's receipt;--keep disk/prioron it refuserecovery_choice_refused, since keeping the edited or pre-withdrawal bytes would let the next sync re-import the forgotten fact. A bundle's--keep priorwrites the prior bytes of its edited files andrecoverPublicationrestores the rest;--keep diskkeeps every file and abandons the publication; both back up every file first. Fault seamsstuck_recovery:{backed_up,written,abandoned,recovered}. Tests:test/repair-stuck-recovery.test.ts,test/e2e/repair-stuck-recovery-postgres.test.ts,test/pathological/c1-effect-stuck-recovery.test.tsandtest/pathological/c4-bundle-stuck-recovery.test.ts(both engines; the effect probe asserts the forgotten fact stays forgotten after the resolution, a commit and a sync).src/core/persistence/native-file-target.ts— shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032:isWindowsColonTarget(rel)andcolonSlugWindowsRefusal(slug, sourceId)name the one Windows-only refusal (colon_slug_windows_write_through::names an NTFS alternate data stream);submitPageMutationraises it before admission when this host publishes the file,prepareFileTargetat publication, and managed (fileRefusals) and unmanaged (failedFiles) sync skip each such path by name (test/colon-slug-windows-5032.test.ts). A path segment over 255 bytes, orENAMETOOLONGfrom the lookup, refusesinvalid_paramswith detailfile_name_too_longand a fix naming a slug whose segments fit 240 bytes (test/pathological/b12-slug-segment-bytes.test.ts).src/core/persistence/admission-retry.ts— bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. #6355: a session that drops under the attempt (isConnectionLossinretry-matcher.ts: connection-class SQLSTATEs, postgres.js's connection codes,57P01/57P02/57P03, the socket errnos) re-runs the attempt afterCONNECTION_LOSS_RETRY_MS(100/300/900 ms), which is safe because every attempt reads the retained request id first and replays an admitted row; when the session keeps dropping the caller getswriteOutcomeUnknown(write_outcome_unknown,reason: connection_lost, fix: read the request by id), never the raw socket error the crash robot's receipt oracle took for a refusal while the write committed (test/persistence-admission-connection-loss.test.ts, forced probes: a lost COMMIT acknowledgment; a dead lent transaction used once with the pool finishing the write). The optionalrecover(error)hook runs before each re-run;admitWriteuses it to rebuild the pool (engine.reconnect) and to move the re-run from a lent transaction (the consumer's lane,onPersistenceLane) toengine.transaction, since a dropped reservation fails every later use the same way ("Connection is no longer owned"). Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live intest/persistence-journal.test.ts. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy;admitWriteInTransactionnever backs off inside an existing unit of work.test/persistence-withdrawal-retry.test.tsverifies guard release, complete rollback and bounded contention. #6278 (B7): also the outstanding-request cap'sdetailformat (outstandingCapacityDetail,outstanding=N limit=M, stamped byjournal.tscapacityError) and its readersisWriteCapacityWait/outstandingCapacityOf, which the managed drain andsync-run.ts's failure ledger use to tell a refusal that clears by itself from a cumulative cap. #8621:waitOutRefreshFencere-runs an interactive write's whole admission while a refresh fence refuses it (worktree_refreshing; 250 ms to 2 s backoff,REFRESH_FENCE_WAIT_MS= 10 s cap shared by every item of arememberbatch viawithRefreshFenceBudget, lowered by an explicitwait_ms); background writes and the managed sync are not waited for (test/write-refusal-refresh-fence-8621.test.ts).src/core/persistence/unbound-source.ts— #5254 policy for a Postgres page write to a filesystem source (local_path, orsync.repo_pathfordefault) with default write-through and no worktree binding.submitPageMutationrefusesowner_unavailablewithdetail: unbound_source, adocspointer towrite-refusals.md#unbound-sources-on-postgres, and a hint naming the filledsources writer status/writer claim ... --admin-intent writer_claim --expected-state <admin_state>bind command (host path only for trusted local callers) and, forput_pageto a page withoutsource_path,gbrain config set persistence.unbound_write database_only. That key (refusedefault, validated byconfig set; any other stored value refuses) lets such aput_pageadmit withdatabaseOnlyReason: 'unbound_source'.decideUnboundWriteis the one rule page writers and fact writers (remember, loop-fact retirement and relink throughfact-write-target.ts, #6608) apply to a rooted source with no binding: connector →connector_database; PGLite not activation-listed database-only (#6449) → automatic claim; otherwise a page with a recorded canonical file, or the key unset, refuses and the rest is database-only.rememberkeeps its frozenunavailablecode and carries the refusal's detail, docs and fix (verb-errors.ts). On a classic brain (managed persistence not activated) the hint leads with the classic write path: write<checkout>/<slug>.md, commit it,gbrain sync --source <id>(a remote caller is told to ask the user to). The refusal isretryable: falsewith afixofnext: ask_userand auser_message(classic or managed wording), because every way out is the user's choice (test/unbound-source-hint.test.ts). Publication rechecks inside its transaction, afterauthorizeStoredRequestshare-locks the source row, that the source is still unbound and the page still has nosource_path(elseowner_unavailable/unbound_source, hint rebuilt from the persisted message bywriteResponse), then stampspages.database_only_reason='unbound_source'(migration 177). After binding,prepareFileTargetkeeps a stamped page with no file database-only (receiptwrite_through.skipped: unbound_sourcewith a warning) and managed sync refuses to import a file at its path (source_changed, diagnostic reasonunbound_source). PGLite keeps auto-claiming. Tests:test/e2e/unbound-source-postgres.test.ts,test/persistence-unbound-source.test.ts. See persistence stalls.- Segmented withdrawal mirror (
src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it withpage_body_segmented).mirrorPagerenders its file from the segments (page-prepare.tsunreadPageFile, aStreamedFileContent) and reserves a version 2EffectRecovery(after: null;staging.publicationnames the streamed file by path and SHA-256; the reservation counts the file once).recoverEffectPublicationwrites that stage before its transaction (stageStreamedMirror: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seamseffect_recovery:before_stage/effect_recovery:staged), then renames the verified stage (staging.tspublishStreamedStage). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. v0.60.290.0 reads a version 2 record as version 1 (Buffer.from(null), untypedeffect_unavailableon every attempt, never parks) but never deletes it or its stage, somirrorPagewrites none while that binary could claim it (next entry). Test:test/large-pages/segmented-withdrawal-mirror.test.ts(purge and forget twins, Git commits, two interruption seams, both engines). src/core/persistence/{recovery-version,segmented-mirror-gate,segmented-gate-hold}.ts— forward compatibility of recovery records.recovery-version.tslists the record versions this binary reads (EFFECT_RECOVERY_VERSIONS,REQUEST_RECOVERY_VERSIONS);assertRecoveryVersionrefuses any otherrecovery_version_unsupported(fixgbrain upgrade,host_admin) before a reader touches the record:recoverEffectPublication,reserveEffectRecovery,rebaseStaleEffectRecovery(the--keep withdrawnrebase),upgradeRecoveryStaging(both tables) andmodel.tsrecoveryFiles(request recovery, clearing, stuck-recovery); the stuck-recovery preview (recovery-resolve.tsscanStuckRecoveries) lists such a record refused with that code and fix;head-blocker.tsreports such a record as an intervention with the same fix.segmented-mirror-gate.ts:mirrorPagecallsassertSegmentedMirrorGatebefore streaming a segmented page's file; whilemirrorGateBlockerssees a live writer below SEGMENTED_WRITER_FLOOR (the switch's TTL-cachedsegmentedWriterBlockers, filtered bysegmented-gate-hold.tsliveSegmentedBlockers, the classification doctorsegmented_storageuses: this host's own pre-upgrade writes superseded by the same kind of write from this build are not live; cached per gate read and host) it refusessegmented_mirror_writer_gatewithout reserving a record, and the target retries and parks as usual.resumeGatedMirrors(each effect pass, at most once per gate TTL per engine) requeues, viaretryParkedEffects, requests whose parked targets all carry that code, orwithdrawal_mirror_failedfor the Git/embedding siblings parked behind the mirror (re-armed once it commits), once the gate is clear. No version 1 fallback: it would hold the file whole, and v0.60.290.0's recovery of it refuses to materialize a segmented page forever. Tests:test/pathological/lp-d-recovery-version.test.ts,test/pathological/lp-d-segmented-mirror-gate.test.ts(both engines).src/core/persistence/effect-links.ts— thelinkseffect of a remote page write (mcp.remote_auto_links, link_sourcemcp-remote-mention).runLinksEffectreconciles a put_page/capture/edit_page page's plain mention edges against its whole compiled truth at the published revision (a later revision skips it assuperseded), keeping targets that exist in the source, are visible to the writer (writableTargets) and sit inside its slug grant, and records missing targets as wanted pages. #7122: an effect withdata.range(a remote append_page to the compiled truth) isrunAppendLinksEffect: it reads only those stored truth bytes with the writer's audience (readBodyRangewith the remote audience on a segmented page, loading only the segments the range overlaps; on an inline page the raw stored truth (inlineRegions) with its protected regions cut out of the range, thensanitizeRemoteBody), applies the same target filter and adds edges only, never removing one or replacing wanted rows. At a later revision it still runs when the range's trusted bytes hash todata.range.sha256(two appends whose effects run after both link both) and is skipped assupersededotherwise (an inline range is hash-checked at its own revision too); a write that lands between its read and its page lock is decided the same way under the lock, by reading the range again at the live revision, so a busy page never makes it retry. Tests:test/persistence-links-effect.test.ts,test/large-pages/append-mention-links.test.ts(both engines; readSegmentTexts spy).src/core/persistence/pending-import.tslandedCommitwithrecoverPublication(coordinator.ts) andcompleteWrite(journal.ts) — G7b: on a strict source, a request whose door commit landed before its row is requeued withoutcome.persistence = {git_state: committed, git_commit, landed_before_row: true}(the newest commit in the record'sdoor.head..HEADthat touched its path; none in that range stamps nothing).completeWritekeeps it on a receipt that ends without committing (a grant revoked before the replay, a charged interruption), so the caller sees the bytes are in Git and will be indexed; a committed replay writes the ordinary door receipt. GST-2517: a door commit that landed in the attempt requeues the request even when the attempt ended on a terminal error (an owner exception after the commit, before the row; agit_*refusal the door raised after landing keeps its failed receipt), with its error columns cleared, so aforgetcaught there still records its withdrawal; the replay makes no second commit, so a failure of its own is final, andfrozenVerbWriteError(verb-errors.ts) then names the landed commit on theremember/forgetreply instead of "nothing was saved". Tests:test/git-door-remote-g7b.test.ts(both engines; remote OAuth and legacy-token callers, owner down, revoked grant, group commit),test/forget-door-landed-gst2517.test.ts(both engines; shared and member-page forgets, remember and put_page, a SIGKILLed worker on Postgres).src/core/persistence/hosted-repo.tswithsrc/commands/sources-host-repo.ts— G7b-2,gbrain sources host-repo <id> --dir <path> [--push-remote <url>] [--dry-run | --expect <plan_hash>]: a hosted brain gives an empty, unbound source a bare repository (<dir>/repo.git, branchmain, one commit holding an empty.gitignore, repository-local identitygbrain) and checks it out as a linked worktree (<dir>/worktree) claimed throughrunManagedSourceLifecycle(addorclaim, every physical-root and manifest check), withconfig.canonical = "git"andconfig.hosted_reposet in the claim's own transaction. The door then commits there unchanged. A pre-receive hook (core.hooksPathpinned to the repository'shooks/) refuses every push, since Git's checked-out-branch refusal ends once the worktree is pruned. The preview (the default without--expect) prints the plan in words and aplan_hashover the source incarnation, canonical setting, directory state, push remote and hook; the apply refusespreview_changedwhen it moved. Refusesstrict_requires_managedon an unmanaged brain,hosted_repo_refused(source_bound,source_has_path,source_has_pages,source_archived,dir_not_empty) andoverlapping_path(a directory in a checkout or a source's directory). On a hosted source the preview reports the hook (ok/missing/changed) and the worktree link, and the apply reinstalls the hook. Trusted local CLI only; no operation. Tests:test/hosted-repo-g7b2.test.ts(both engines).src/core/persistence/worktree-link.tslinkedWorktreeProblem/assertLinkedWorktreeIntact— a claim (localRootinsource-lifecycle.ts) refusesgit_worktree_link_brokenfor a linked worktree whose.gitfile names a repository entry that is gone (pruned) or whose entry names another path (the checkout moved); a submodule's.gitfile is checked for existence only. Tests:test/hosted-repo-g7b2.test.ts.src/core/persistence/sync-receipt-wait.ts— how long a managed sync pass waits on its own admitted write, in one place:syncReceiptWait()returnspass(5 s),checkpoint(8 s),held(30 s, while this process's consumer still holds the write) anddrain(30 s, a drain's re-entry).sync-run.tsreads every wait from it.__setSyncReceiptWaitForTests(partial | null)is the test seam (returns a restore function), so a test outlasts a wait in milliseconds instead of sleeping past 30 s.src/core/persistence/local-edit-adoption.ts— GST-1601 part 2: withpersistence.adopt_local_edits.source.<id>on,finishUnpublishedFailure(coordinator.ts) hands aremember/capture/add_timeline_entryrefusedfile_database_drifttoadoptLocalEdit, which reads the drifted file the refusal carries (localEdit, set inpage-prepare.tscompareFileTarget), waits until it is quiet (persistence.adopt_quiet_ms, empty reads as the 5000 default, at most three windows and never past 30 s: the caller's claim holds its worktree queue meanwhile), and adopts only a one-sided, safe edit (#8755: a file overPAGE_MAX_BYTES, checked by stat before reading, a segmented page, an unmerged path or an operation in progress (pending-import.tsunmergedPath/operationMarkerPaths; #8826 addsBISECT_LOGandSQUASH_MSGand reads--absolute-git-diras bytes, answering null unless it is one absolute, existing directory in valid UTF-8), and a stale editor save (staleEditorSave: the file equals an earlierpage_versionsbody, or lacks a list or table row the current revision has and its newest archived version had not) keep the refusal; the repo-less test walks up for.git): HEAD's blob matches the database copy (fileMatchesSnapshot; a repo-less brain skips this),protectedLocalEditfinds no title, type or protected-key change, andprepareRepairPublicationisready. The adoption is amanaged_file_repair(file-repair.ts) carryingadoptLocalEdit({ blob, replaced_revision }), admitted under the CLI writer with a request id derived from the caller's (one adoption per write), claimed and published inline (publishMutation, retrying a busy worktree lock for 10 s) so it lands before the caller: it publishes the file's unchanged bytes with thelocalEditAdoptionCommitnote, stamps the archived replaced revisionchange_reason = 'adopted_local_edit', and commits that one file inside its publication transaction (afterEffects→commitAdoptedLocalEdit; a strict source's door commits it instead). #8755: a publication that fails after that commit is requeued by recovery andpublishAdoptionpublishes it again (it retries any release within its 10 s):adoptedHeadHoldsaccepts HEAD holding the adopted blob and the replay names the landed commit (landed_before_row). The intent names the caller's claim (adoptLocalEdit.caller);assertAdoptionCaller(file-repair.tspreparation) refuseswrite_claim_lostonce that claim is gone, so an adoption orphaned by a crash publishes nothing; its own claim carries the owner stamp. #8824: the check runs only until the adoption's commit lands: once HEAD holds it (landedAdoptionCommit: the newest commit on the path has the adoption's subject, trailer and commit-ledger line, its parent holds the pre-adoption blob and HEAD the adopted one; the commit line is written aftergit commitand can be missing, so the ledger's intent line also proves the commit when itshead_beforeis the commit's parent and its message digest is the commit's), a replay publishes it whatever became of its caller, andsettleAdoptionleaves such a requeued adoption to the consumer instead of cancelling it. #8767:recoverPublication(coordinator.ts) stamps that commit (adoptionCommitLanded, read byadoptionRecoveryEvidenceunder the worktree lock before the recovery transaction; #8869: the transaction refusesrecovery_requiredbefore touching a file, leaving the recovery pending, when the request or the checkout's HEAD changed since) asoutcome.persistence = {git_state: committed, git_commit, landed_before_row: true}on the requeued or failed receipt, whichcompleteWritekeeps on any later end without committing.settleAdoptionwaits up to 120 s more on an adoption whose publication already started; a caller whose claim was lost is returned asclaimLost, neverreleased; an admission failure logs[persistence] phase=adoption. The caller is then released withintent.adopted_local_editand prepared again;withAdoptedLocalEdit(service.tspreparePersistedMutation) putsadoptedon its receipt. A file changed under the adoption ends bothraw_file_changed. Commit-ledger lines carryadopted(adoptedBy,effect-model.ts). Doctorlocal_edit_adoptions(src/commands/doctor/checks/local-edit-adoptions.ts) lists adoptions of the last 24 h per source fromoutcome.adopted_local_edit(kept by compaction), always ok. Tests:test/adopt-local-edit.test.ts,test/operation-marker-paths.test.ts.src/core/schema-migrations/v220-persistence-request-preparation-attempts.ts— #6278:persistence_requests.preparation_attempts integer NOT NULL DEFAULT 0 CHECK (preparation_attempts >= 0), the count of cut-offs of a request's preparation. Existing rows start at 0; a commit resets it. It is a migration-created column (also in thepersistence_requestsCREATE TABLE ofsrc/schema.sql, with no index) so a fresh install and an upgraded brain keep the same column order. Tests:test/persistence-preparation-attempts-migration.test.ts,test/e2e/persistence-preparation-attempts-postgres.test.ts.