Garry's Opinionated OpenClaw/Hermes Agent Brain
Google connector + open-loop engine (key files cluster) (continued)
Subsystem index · Previous entries · Account identity and API access.
src/core/tailscale.ts— Tailscale helpers with an injected exec seam (CommandRunner = (argv, { inherit?, timeoutMs?, stdoutToStderr? }) => Promise<CommandResult>whereCommandResult = { status, stdout, stderr }andstatus: nullmeans killed at the timeout or never spawned;defaultCommandRunneronBun.spawn— attimeoutMsit sends SIGTERM and, when the child has still not exitedSIGKILL_GRACE_MS(3s) later, SIGKILL, so a child that ignores SIGTERM never hangs the caller; both timers are cleared in afinally— also the runnerserve-service.tstypes against;stdoutToStderrsends an inherited child's stdout to fd 2 so--jsonstdout stays pure):parseTailscaleStatus(BackendState—Running,NeedsLogin,NeedsMachineAuth,NoState,Stopped;Self.DNSName,CertDomains, andfunnelCapable: true/false fromSelf.CapMapkeys orSelf.Capabilitiesentries carrying any Funnel form —funnel(NodeAttrFunnel),https://tailscale.com/cap/funnel-portswith or without its?ports=query, or the legacyhttps://tailscale.com/cap/funnel— null when both are absent),publicUrlFromDnsName(strip trailing dot, lowercase,https://),TAILSCALE_BINARY_CANDIDATES+findTailscaleBinary(Bun.which, then the macOS app bundle, Homebrew and/usr/binpaths; the candidate list doubles asmcp-expose.ts's allowlist for a binary path recorded in a receipt) +isSystemTailscaleBinary(binary, realpath = realpathSync)(true when the path is a candidate literally or resolves to one through symlinks; an unresolvable path is false —mcp-expose.tsputssudoin front of the binary only when this holds),tailscaleInstallPlan(platform, hasBrew),tailscaleLoginArgv(platform, user, binary)→{ setOperator?, up }(Linux:sudo <bin> set --operator=<user>then a flaglesssudo <bin> up— a flaggeduptrips the CLI's settings-revert check on a node with non-default prefs; macOS:<bin> up),tailscaleManualLoginCommand(binary = 'tailscale')(the Linux login the operator runs themselves when gbrain refuses tosudoa non-system binary —sudo <bin> set --operator=$USER && sudo <bin> upwith the DISCOVERED path shell-quoted throughshellQuote, because a binary outside sudo'ssecure_pathis exactly that case) andTAILSCALE_ACCEPT_DNS_COMMAND(tailscale set --accept-dns=true, the MagicDNS-off remedy) — both keep their tailscale flag literals in this module so the flag-registry scan ofmcp-expose.tsnever sees them,tailscaleServeArgv(port, { funnel })(serve --bg/funnel --bg) +tailscaleServeOffArgv({ funnel })(serve|funnel --https=443 --set-path=/ off—--set-path=/scopesoffto OUR/mount; without it the CLI removes every mount under:443and, when more than one exists, prompts interactively — with stdin ignored the prompt reads EOF and the command exits 0 having removed nothing; neverserve reset),parseServeStatusStrict(the only serve-status parser, fail-closed: backgroundWebhandlers,Foreground[<session>].Webhandlers markedforeground: true, andTCP['443'].TCPForwardas a non-proxy root handler; an empty document /{}/nullis the legitimately empty view, but non-JSON, an array or a scalar returnsnullsomcp-expose.ts'sreadServeViewcan tell "could not read" from "nothing configured") +findProxiedHandler(view, port),classifyTailscaleError(stderr)(Funnel rule before the HTTPS rule; the HTTPS rule matches certificate vocabulary, never a barehttps://URL:funnel_not_enabled|https_not_enabled|needs_operator|needs_login|daemon_not_running|unknown), and the admin/KB URL constants (TAILSCALE_ADMIN_DNS_URL,TAILSCALE_ADMIN_ACL_URL,TAILSCALE_FUNNEL_KB_URL=https://tailscale.com/kb/1223/funnel,TAILSCALE_DOWNLOAD_URL). The parsers and argv builders are pure; the injectablewhich/fileExists/ runner defaults touchexistsSync,process.env.PATHandprocess.platform, and tests replace them. Notetailscale status --jsonexits 0 in everyBackendState(only the human-readable form exits 1 when logged out), andserve/funnelwait interactively rather than failing when HTTPS certificates or the Funnel attribute are off — which is whymcp-expose.tspre-checks before starting them.src/core/serve-service.ts— the persistent-service half ofmcp expose, everything undergbrainPath('serve')(serveDir,adminTokenPath,wrapperPath,receiptPath,serveLogPath,serveErrPath) soGBRAIN_HOMEis 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 tonone).renderServeWrapperproduces the 0755 launcher that sources the shell profiles and~/.gbrain/env, prepends the Bun dir toPATH, reads the admin token from its file at run time intoGBRAIN_ADMIN_BOOTSTRAP_TOKEN(the token is never written into the wrapper, plist or unit), resolvesgbrainthe way autopilot's wrapper does (baked installer path,type -P gbrainfallback) andexecsserve --http --port N --public-url URL [--surface] [--enable-dcr].resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists })picks the baked program: agbrainon PATH wins; a COMPILED binary —import.meta.url(or the injectedmetaUrl) under/$bunfs/, or anexecPaththat is not the bun runtime whileargv[1]is absent/virtual — is[execPath]whatever its basename (release assets are renamed); otherwise the[bun, <cli.ts>]dev form only when thatcli.tsexists on disk, else[execPath]rather than a path that cannot run;renderServeLaunchdPlist(RunAtLoad, KeepAlive, ThrottleInterval 30, logs toserve.log/serve.err, localescapeXml) andrenderServeSystemdUnit(After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped —%→%%inExecStartand bothappend:log paths,$→$$inExecStart).ensureAdminToken(0700 dir, 0600 file created withwxsemantics, 64 hex chars; reuse a file matching the exportedADMIN_TOKEN_SHAPE=^[A-Za-z0-9_-]{32,}$— the same regexserve-http.ts'sresolveBootstrapTokenaccepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise),installServeService(launchd: domain-explicitlaunchctl bootout gui/<uid> <plist>— failure ignored — thenlaunchctl bootstrap gui/<uid> <plist>, both through the onelaunchctl(run, uid, plist, { modern, legacy })helper whose legacylaunchctl unload/loadfallback 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 theverbwhose result it returns; a bootstrap that fails with stderr matchingLAUNCHCTL_SETTLE_RE(Input/output error,already in progress,\b5\b,\b37\b— launchd still unloading the previous job) is retried up toLAUNCHCTL_SETTLE_RETRIES(5) times,LAUNCHCTL_SETTLE_MS(1s) apart through the injectablesleepparam (defaultsetTimeout;mcp-expose.tspassesd.sleep), a success after retries is a note and an exhausted retry appends "(after N settle retries)" toerror; systemd:daemon-reload→enable→restartso a regenerated wrapper takes effect;loginctl enable-lingerbest effort) /uninstallServeService(launchd: the samebootout gui/<uid>with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matchingLAUNCHCTL_NOT_LOADED_RE(No such process|not loaded|Could not find|not find service) pusheslaunchctl <verb> failed: <describeFailure>intonotes, and the exportedlaunchdBootoutFailed(result)recognizes that note somcp-expose.tscan say the job may still be loaded) /serveServiceState(launchctl print gui/<uid>/<label>/systemctl --user is-active); all three takeuid?: numberdefaulting toprocess.getuid?.() ?? 501, threaded frommcp-expose.ts. Every supervisor subprocess carries a timeout — 60s forlaunchctl bootstrap/bootout(and the legacyload/unload) andsystemctl --user enable/restart/disable, 15s forlaunchctl print,daemon-reload,is-activeandloginctl enable-linger— and astatus: null(killed) result counts as a failure (error/ note) orunknownstate; a failed call is described bydescribeFailure(its stderr, else stdout, elseexit <status>).readExposeReceipt/writeExposeReceipt(expose.json, 0600, version 1, no secrets): the reader is a structural shape guard, not justversion/port/public_url— it also requiresmodeintailnet|funnel, aserviceobject with a stringwrapper_path, atargetinmacos|linux-systemd|none, a stringstateand string-or-nullplist_path/unit_path, atailscaleobject whosebinary/dns_nameare string-or-null, and stringmcp_url/admin_url/admin_token_file; anything less is null (absent), so--status/--removenever 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. UsesshellQuotefromsrc/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— managedremember,forget, andforget_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.tsisolates 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.tsruns identical races on PGLite and PostgreSQL;test/withdrawal-followup-writes.test.tscovers writes after a forget whose effects stay queued. #5836: an omittedentityis inferred before admission (inferRememberTarget), and the inferred slug is used only whenplanRememberTarget's checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed withwarnings(NO_ENTITY/ENTITY_LINK_FAILED) +hint. Theentity_inferredintent marker makes preparation dedup exact text only (never supersede) and notes the context;test/remember-entity-inference.test.ts.remember.replaces(caller-directed replacement):decideReplacement(facts/single-prepare.ts) replaces the cosine decision when the intent names a target; it is checked at submission (fail fast) and again invalidatewith the target row lockedFOR UPDATE, so two replacements of one fact serialize and the second seestarget_superseded. Refusals areinvalid_paramswith code prefixes (target_withdrawn,target_supersedednaming the chain head,target_expired,replaces_entity_mismatch,replaces_cross_page,replaces_duplicate); remote callers getnot_foundfor private targets; equal text is aduplicateno-op. Everysupersededoutcome carriessuperseded_fact_id(plusreplaced_by_callerforreplaces).forgetresponses gainsimilar_active(facts/similar-active.ts) after commit and on replay, andsemantic_review: falsekeeps the claim out of overnight review. Pinned bytest/remember-replaces.test.ts. remember's write intent carries the transport-resolvedctx.sessionId(MCP_meta.session_id, clamped to 256 characters), and preparation stores it as the fact'ssource_session, sorecall({session_id})finds remembered facts; identity only, never an authorization input (test/remember-session.test.ts). #7248: a folder-lessentitymust resolve strictly or is refused with candidates; pending replies carrywrite_request.target(test/remember-entity-target-7248.test.ts).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. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (root-registry-idle-chmod-5297.test.ts). 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; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator.docs/architecture/canonical-writers.tsvis the finite writer census;canonical-writer-inventory.test.tsrejects unreviewed additions, andpersistence-writer-fences.test.ts/pglite-maintenance-fence.test.tsexercise real engines, competing processes and separate homes.src/core/persistence/sync-drain.ts— #5984: drains a managed sync in one invocation.runDrainre-enters the single-passperformManagedSync(which keeps returningpartial / writer_pending | writer_yield) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (forward-progress.tsregisterRunDeadline, set bycli.tswhen it arms the sync watchdog), a writer head needs intervention (recovery_required,owner_unavailable, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries onlyworktree_refreshing(itsretry_after_ms),database_contention, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carriesdrain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall };drainNextbuildsnextfor the CLI from the sharedsyncResumeCommand(sync-reconcile.ts). The CLI (sync/run.tssingle source,--all,--watch), serve's delegated runner and thesyncjob handler (#6706, bounded bySyncOpts.deadlineAtMs) setSyncOpts.drain; the PGLite owner delegate usesrunDrainover IPC; the cycle,sync-administration.tsandworktree-refresh.tskeep their own loops. #6706:runDraintakes a callerdeadlineAtMs(the earlier of it and the strict run deadline wins; a past deadline makes zero passes; a far one re-arms past the 2^31−1 ms timer limit), reportsresumable / deadlinewhen the deadline lands in a retry backoff, abandons a pass still runningDEADLINE_PASS_GRACE_MSafter it, anddeadlinePassedstops the extra pass and the next stage;jobDispositionclassifies a drained result for jobs (synced,continuewhendrainNextis safe to loop,needs_operator).src/core/minions/handlers/sync-job-drain.tsruns it in thesyncjob:planJobDrain(drain,lanes: 1, a deadline fromjob.deadlineAtMsor the row's wall-clock limit viaWALL_CLOCK_THRESHOLD_MS_SQL, at most an hour, less 60 s; job-data controls only from trusted submitters;sync.job_drain=falseturns it off), throttled progress, andsettleJobDrain(the CLI'soutcome/drain/next,incomplete, at most one continuation on a worker-backed brain, priority ≥ 5, whosenextthen observes it). A sync job that finds another live sync job on its source skipssync_in_progress(sync-handler-drain-6706.test.ts).readManagedSyncBacklogreads unfinished cursors'progresswindow (stamped bysync-run.tson each advance, reset per drain) forgbrain doctor(managed_sync_backlog) andsources status, withresume_argsbuilt bysync-reconcile.tsmanagedSyncResumeArgs. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (drainClaimOf), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plusSTALL_GRACE_MS(budgets read frompersistence.*_preparation_ms/preparation_ceiling_ms), a lapsed claim keeps the plain window (stall.cause: owner_missing), a preparation this process's pid owns past its allowance endsresumable/preparation_abandoned, andSyncResult.breakerendsblocked/preparation_systemic;stallcarriesphase,step,waiting_on,cause, and a timer printsstalled <N>s on <step>while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) fromStallProbe.head, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (isWriteCapacityWait,admission-retry.ts: aqueue_capacitywhosedetailisoutstanding=N limit=M) is retried with backoff up to 5 s apart while the drain printswaiting for write capacity (N outstanding of M); past the no-progress window it endsblocked/write_capacitywithdrain.capacityand writer status asnext, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. Tests:test/sync-drain.test.ts,test/sync-drain-claims.test.ts,test/managed-sync-drain.test.ts,test/sync-drain-write-capacity.test.ts.src/core/persistence/sync-window.ts— #5984 admit-ahead for draining managed Postgres syncs. While the cursor'sgrouppublishes,admitAhead(sync-run.ts) freezes and admits the next group and records it in the cursor'swindow(at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request inintent.after. #6712 (one page, one fate): a window group publishes whatever its predecessor became; nothing is cancelled for another page's failure, and dependency edges (sync-group.tsdependencyKeys,freezeFollowers'taken) keep two changes of one page out of the same group and out of the window while one is in flight. Publication validation (sync-prepare.ts) re-checks the predecessor once per transaction and reads the cursorFOR KEY SHARE, acceptingpending,groupandwindowmembers, so the drain's cursor saves never wait for the publishing group. After a failed page the members after it stay admitted at the head of the window, so every admitted request's identity stays in the cursor until its own receipt is read (groupStep,promoteWindow). Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute,FOREGROUND_RECENT_MS) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered byclaimedPredecessorState: a group member follows the member before it in its own group (itsafternames only the previous group), anything else followsafter.claimedHeadOrder(the consumer, before claiming followers) only orders: under lanes a member whose predecessor member is unfinished releases its claim and waits; a predecessor that ended, committed or not, lets it publish (#6712).WINDOW_CANCEL_MESSAGEandlaneFaultCancelMessagestay only so older receipts still read as legacy knock-ons. Test:test/sync-group-member-order.test.ts.src/core/persistence/sync-lanes.ts+worktree-lease.ts— #5984 lanes. The drain opens a lane policy for its worktree (openLanes, keyed by a per-drain run id that lane groups carry asintent.lane;closeLaneRunat drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim bylaneTask). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (claimNextLaneHeadin journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (laneRoots), and runs it as a lane (executeClaimedGroupwithlane). Lane publications share the worktree's native lock in this process (acquireWorktreeShared/worktree-lease.ts; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusiveacquireWorktreefirst yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims afterLEASE_TURN_MSof continuous holding. Lane transactions begin in manifest order (awaitLaneBegin) and commit in manifest order (awaitLaneTurn, inside the transaction before the counters: the predecessorintent.aftermust have ended, committed or not (#6712); a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (windowPredecessorAllows).laneFallbackin group-publish.ts releases or falls back to the single path (#6712: never cancels), and a lock or statement timeout steps the lane count down (stepDownLanes). Lane settings (--lanes/--no-lanes>GBRAIN_SYNC_LANES>sync.lanes> 6, clamped to the pool's long-hold capacity minus 3) resolve inresolveBulkSettings(sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (admitAhead).src/core/persistence/sync-run.ts+sync-authority.ts— one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (up_to_date) stamps onlysources.last_sync_at, insidewithCoordinatedWriteand guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freezenoEmbed,noExtractandnoSchemaPack. #6712 PR 1: a resume inherits the cursor's processing opt-outs OR-wise (adoptCursor, one CAS that also stamps the resumer's validated authority) and reports a flag it overrode ininherited_options; nothing refuses over processing options, andexplicitProcessingis gone. Admitted requests keep their own intent principal: they are read under it (admittedBy), and a writer change drops only unadmitted frozen entries. Every managed pass runs under the source's drain lease (withDrainLease,src/core/persistence/sync-lease.ts), whose token fences admission, the settled/held CAS, fan-in and the cursor CAS (assertDrainLease). Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol.freezeEntrychecks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts inrenamed. #5522: a new-file entry (pageId: null) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them intolegacySkips(printed bysync-diagnostics.tswithgbrain repair contextual-mode). A terminalcheckpoint_validation_timeoutreceipt gets its hint fromcheckpoint-validation.ts. Content holds (#5988,sync-screen.ts):freezeEntryscreens each import (company-profile cursors andsync.holds=failexcepted); a refused file becomes a hold written in the same transaction as the cursor step (saveCursor'sinTx), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (isContentRefusal, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (converted), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (fenceReceiptLocation: the durableerror_detail.fence, the message, or an older release's message) holds the same bytes even when the screen admits them (prepareTimeFenceHold, reasonprepare_time); a compactedinvalid_params/take_row_collisionreceipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returnspartial; it is converted once, gets no failure-ledger row and is logged as a conversion.sync.holds=failand company-profile cursors keep blocking with the typed refusal. #6278: apreparation_stalledreceipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (meta.deleted,upstream_versionnull), the checkpoint never holds;preparationStalledHold(sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold throughholdUnderGate, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (UNFINISHED_PAGE_REQUEST_SQL, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor'sbreakercounts the run's stalled receipts (identities and streak, saved with each CAS):holdsEscalated's rule over the run's screened imports orBREAKER_STREAK(5) in a row trips it, the run stopsblocked_by_failureswithSyncResult.breaker(drainpreparation_systemic), and the next run'sconvertBlockedCursorre-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak.sameContentAtOriginand the waiver screens race the sync preparer againstpersistence.sync_preparation_ms(raceSyncBudget, sync-waivers.ts) and fail open. Tests:test/managed-sync-preparation-stalled-holds.test.ts,test/sync-waiver-budget.test.ts. Results carry this run's holds, the outstanding total, escalation,converted_from_failedandrecovered_frontmatter(buildHoldReport); dry runs listwould_hold/screen_skipped. After the checkpoint commits the pass stamps drain stepfinishand emitsmanaged_sync.finish; then (unlessnoExtract) the owner derives links for the source's stale pages throughlinks-maintenance.tsunderFINISH_BUDGET_MS(pages left over stay stale forgbrain extract --stale), so a PGLite-delegated sync and a Postgres sync take the same path; the result carrieslinks, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits whilesources retry-heldre-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returnspartial/writer_yieldinstead ofsynced, so the drain's next pass retires the finished cursor and discovers again, taking them; aqueue_capacityrefused for outstanding requests (isWriteCapacityWait) is left out of the failure ledger because the drain waits it out. #6696: the cursor key comes fromselectManagedCursor(sync-cursor-key.ts), which every managed caller crosses: a run without--strategyand without a company plan keys a fresh cursor with the source's configured strategy, while an unfinished cursor under the raw key keeps resuming under it, so its admitted requests keep matching.SyncOpts.embedDeferred(the cost gate's auto-defer) is frozen on the intent and treated asnoEmbedby preparation, never as a processing option a resume adopts or compares (test/persistence-sync-cursor-strategy-6696.test.ts).src/core/persistence/sync-holds.ts+sync-screen.ts+sync-blobs.ts— Git holds (#5988). Oneop_checkpointsrow per held file (sync-hold, fingerprintsource:incarnation:path) plus a per-sourcesync-hold-summaryrow (count, andstale: holds whose page exists);writeGitHold/clearGitHoldlock the summary row and are conditional on the writing run's discovery time (observed_at), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows;readGitSourceHolds(current incarnation only) feedsretry-heldand legacy sync, andreadGitHoldListing(count from the summary row, rows limited per source in SQL) feedssources status, neverreadAllSourceHolds.recordSyncConversionlogs each blocked request a managed run converted in place (sync-conversions, newest 20 per source, in the transaction that saves the converted cursor);sources statusshows the newest 5.gitHoldItemgives every surface code, reason, key, line, location-only message,fixAction anddocsanchor. #6188invalid_fenceholds carrymeta.fence(reason, fence, section, rows, columns, section line), the file line of the first bad row (meta.line, fromfenceFileLinewhen the screen holds it),fence_versionand the last repair attempt (fence_repair); the summary row counts them (fences), andholdRepairStepsis the one router (D6) every surface prints: fence and slug-conflict holds (HoldRepairRoute.fences+slug_conflicts) preview the content-repair lane,gbrain repair content --source <id>(contentRepairArgv, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself whenFenceAutoRepair.active), other holds previewgbrain repair frontmatter, a mixed source names both; one fence hold's own fix stays that file'sgbrain repair fences --only <path>preview (fenceHoldFix). One fence hold's fix (gitHoldFix→fence-repair/hold-fix.tsfenceHoldFix) is that file's--only <path>preview with the step its state calls for, andgitHoldItemcarries the D16fenceobject (classes, tier,auto_retry,next_attempt_after); callers that can read the maintenance state pass it (fenceAutoRepairFor).holdRescreenDueis the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen); a streamedfile_too_largehold (meta.streamed: read whole) re-screens on change, retry or a new gbrain (#8072). Policy keys:sync.holds(hold/fail),sync.hold_cap(detail shown, default 500),sync.hold_escalate_count(50),sync.hold_escalate_pct(5, from 40 screened imports),sync.parser_regression(stop/hold). #6278:preparation_stalledholds carrymeta.stall(request, step,waiting_on, attempts, the writing gbrain version, the sync's resume arguments) and count understalledin the summary row andHoldRepairRoute;gitHoldFixroutes them togbrain sources writer status --source <id> --json, thensources retry-held, then the option-preserving sync (stalledHoldSteps), never to frontmatter repair, andholdRescreenDuere-screens them on a gbrain version change;buildHoldReportroutes the escalation text by code.sync-import-provenancerecords (recordSyncImportProvenance, batchedrecordSyncImportProvenances) also carrydisk_sha256/disk_blob_oid(bytes on disk the page holds, #8071),revisionandparser(syncImportParser:SYNC_IMPORT_PARSER_VERSION, Markdown chunker, schema pack; never the release); records from before them, or from a repair, lack them and readers take them as unknown.screenFrozenImportbuilds its input withfrozenImportScreenInput(rename base, the run's pack, sanity and purge tombstones) and screens it withscreenFrozenContent, both shared with the slug-conflict repair so it judges a held file exactly as the next sync would; it admits a fence Tier 1 fixes (fences.normalize, read once per run only when needed; the dry run lists it inwould_normalize), turns a refusal into a hold, or throwssync_parser_regressiononly whensync-import-provenanceproves a validating gbrain imported the same bytes.sync-blobs.tsreads blob ids/sizes with chunkedls-tree -land contents withcat-file --batch;freezeEntryreads each entry's pinned blob and content throughreadPinnedBlob/readPinnedContent(viasync-screen.tspinnedBlob/pinnedContent): a miss lists that entry and up to 255 of the next committed imports in onels-treeand loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in onecat-file --batch, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window, not two per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (test/managed-sync-pinned-reads.test.tsproves identical rows on PGLite and Postgres).held-reads.tsis the read side:get_page.file_held,staleon search/query hits and theheld_filesretrieval meta and notice, from one summary read per call, cached per request, plus, when the scope holds files and the call returned hits, one read for the hits' holds (by page id,op_checkpoints_sync_hold_page_idx) and the count of holds that could match the query (stampHeldHits; the notice names it, also names embedding-held pages, and escalates);stalledcoverage routes apreparation_stalledhold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page getsfenceHoldRelay: the owner-host command and whether it clears by itself). Tests:test/sync-holds-store.test.ts,test/persistence-sync-holds.test.ts,test/sync-all-hold-notes.test.ts,test/held-read-signals.test.ts. #5493/#6529: managed discovery admits image imports whenever multimodal embedding is on (company plans refuse). Off,freezeEntryholds each image import asmanaged_image_sync_unsupported(managedImageHold, dry-run screen too) before any content read, whateversync.holdssays: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), andholdRescreenDuere-screens it on change, removal, multimodal on orsources retry-held. On,freezeEntryfreezes the bytes as base64 (pinnedImageBytes,frozenImageIntent), an oversize image takesoversizeHold, identical bytes are a no-op by hash, andsync-prepare.tsroutes the entry tosync-image.ts. The summary row countsimages; those holds never count towardholds_escalatedorgit_held_files.src/core/persistence/file-repair.ts—managed_file_repair(#5988), the owner-internalput_pagekindgbrain repair frontmatter --applysubmits (accepted only from the trusted local CLI withmanagedFileImport; MCP is refused by the reserved-field gate, remote authority by the preparer).managedRepairRootresolves the owner throughcheckOwner(owner-refusal.ts) and refusesowner_unavailablewith the condition as its reason;submitManagedFileRepairre-reads the source'sRepairBusySet(repair-busy.ts) right before admission and refusessync_in_progresswhen a write in flight or an unfinished sync's frozen manifest names the path, origin, slug or a rename endpoint (#6278: a sync can start while a fence repair waits on its model call). The preparer confines the path (isWriteTargetContainedplus a component-wiselstatwalk, no symlinks), requires the file's sha256 to equal the previewedbeforeHash(changed_since_previewotherwise), recomputesprepareRepairPublication(thescreenSyncImport+importFromContentpreparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes asfile(expectedBeforeHash= previewed hash; nofile_database_driftcheck), applies the import (a held new file creates its page, arenameFrommoves the page withupdateSlug), clears the Git hold (only while it is theholdObservedAtobservation when the intent carries one, so a hold a newer sync wrote stays) and recordssync-import-provenancein the same transaction; the file write queues the Git target effect. An import of a segmented body seals itself, so the inline text seal is skipped and itsafterCommitis forwarded. A fence repair (gbrain repair fences) passes itsFenceRepairReceiptasfenceRepair: submission and the preparer refuse (invalid_params, nothing written) a receiptparseFenceRepairReceiptrejects or whosebefore_sha256/after_sha256are not the previewed and written bytes; the outcome carries it asfence_repair, the file target carries the commit note fromfenceRepairCommit(effect-model.ts), and every refusal and fix namesgbrain repair fences --source <id>instead ofgbrain repair frontmatter(FileRepairKind, also taken byconfinedRepairTargetandmanagedRepairRoot). Tests:test/repair-frontmatter.test.ts,test/fence-repair-receipts.test.ts.src/core/persistence/sync-prepare.ts— guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. A Markdown import's preparation carriesimportProvenance(SyncPreparedMutation); its publication writes it in the publish transaction with the page id,revisionand the disk half (syncDiskProvenanceover the canonical writeback, elsesyncDiskBytes), and a no-op waiver writes the same record instead. The checkpoint (applyManagedSyncCheckpoint) keeps a repository-root source's pinned slug mode (sync-slug-mode.ts). Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin.noEmbedsuppresses the effect itself;noSchemaPackbypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts throughcheckpoint-validation.tsand, for a run whose entries another cursor imported (overtaken, #5522), also commits when that cursor already checkpointed the same target. Markdown imports passscreenSyncImport(the already-published working-tree exemption, thenscreenImportContentwith the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (holdObservedAt), the checkpoint clearsreleasedHoldsand ignoressupersededRequests(failed content refusals the run converted in place), and every Markdown import recordssync-import-provenance(raw sha256, blob, gbrain version, quoting recoveries) and reportsrecovered_frontmatter/comment_valuein its outcome. Tests:persistence-sync-origin-native.serial.test.ts,persistence-sync-options.serial.test.ts,persistence-sync-company.serial.test.ts. A same-slugrenameFromaccepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page withupdateSlug(same id, inbound links and history,old -> newinslug_aliases, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests:persistence-managed-lifecycle.test.ts.syncGitTopLevelanswers the checkout'sgit rev-parse --show-toplevelonce per root and sync run, reading it again when the top level's.gitentry is replaced or removed or a.gitappears between it and the root. #6278:prepareManagedSyncMutationcallsenterClaimStepat each await boundary (managed_sync_active,authority,worktree_binding,configured_root,knowledge_publication,manifest_entry,git_rev_parse,origin_check,page_snapshot,import_screen,import_content,canonical_projectionsand the rest, each naminggit,fsordbwhere it knows), so a stall reports its step; the consumer's budget and the cancellation reaching those boundaries are in persistence-stalls.md. An intent withembedDeferred(#6696) prepares asnoEmbedwhatever the cursor's stored options say.src/core/persistence/links-maintenance.ts—extractManagedStaleLinks(then the mention pass unlessmentions: false, which sync passes) derives links for pages whose extraction watermark is stale withprepareAutomaticLinks(put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the samewithCoordinatedWritetransaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (pages.links_attendance_blocked_revision/_at, written bymarkPagesAttendanceBlockedinengine-sql/pages.tsonly while the revision still matches, cleared bymarkPagesExtractedBatchwith the watermark); it is still reconsidered every run, and thelinks_extraction_lagdoctor check counts it apart from lag while the marker equals the page's current revision. GBRA-130 A-1 (sitelinks.extract_stale, oneItemRunper source): a failing page is reported (failed,failures) and skipped; a run-scoped error stops the run after in-flight pages settle, recording nothing; a tripped breaker stops a scoped run (item_failures_systemic) or skips that source in a brain-wide run (systemic). Content failures are counted and held bylinks-extraction-holds.ts; a page of a deleted source failsunknown_source(PageSourceMissingError). The sync tail inherits this. It is the one managed extraction path: managed sync,extractStaleFromDBon a managed brain, and the owner delegation all run it.runManagedStaleExtractionbacksgbrain extract --staleon managed brains, locally or through thewriter_extract_staleadministration operation inside a PGLite owner (src/commands/extract-stale-delegate.ts, trusted CLI registration only).links-preparation.tsretargets a link written against a renamed page's old slug to the live canonical page throughslug_aliases, asget_pagedoes. Tests:persistence-managed-lifecycle.test.ts,persistence-sync-stdio-owner.serial.test.ts,test/pathological/a1-links-extract.test.ts(both engines).src/core/persistence/links-extraction-holds.ts—pages.links_extract_failure(v258):recordLinkExtractionFailurescounts a run's content failures (same revision, extractor generation and code add a run; 3 hold the page, which stale extraction then skips until an edit, a generation change or--retry-heldviaclearLinkExtractionHolds);linkExtractionRetryFixis every report's fix. Cleared bymarkPagesExtractedBatch. Test:test/pathological/a1-links-extract.test.ts.src/core/persistence/sync-authority.ts— trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.src/core/facts/withdrawal-overlay.ts— pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation.partialFenceRunsfinds the fence runs a forced segment cut splits. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression:test/withdrawal-overlay-concurrency.test.tson both engines.src/commands/sync-persistence-delegate.ts+src/core/persistence/{sync-wire,sync-administration}.ts— pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (DelegatedSyncDeadline): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window;--timeoutand--hard-deadlinestay strict. Legacy shared-secret sync refuses managed brains.test/persistence-sync-stdio-owner.test.tsstarts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open. #6712 PR 1: the wire still validates an older CLI'sexplicitProcessinglist by shape, then ignores it (WIRE_SKEW_WINDOWS.explicitProcessinginsrc/core/wire-skew.ts, floor 0.60.255.0, accepted until 2026-11-14); the cursor's opt-outs are inherited (test/sync-owner-lane-processing-6696.test.ts). #6712 PR 2: the owner lane's flag tables are views ofSYNC_FLAGS(src/core/sync-flags.ts);--lanes N/--no-lanesare accepted and not sent, and a dropped retired field printsretiredWireNotice.src/core/facts/backstop.ts+src/core/entities/resolve-on-save.ts— saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836:src/core/facts/subject-infer-write.tsinferMissingSubjectslinks facts with no or fallback-only entity viainferFactSubject(remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marksentity_inferred(context note; exact-text dedup only in both writers);test/facts-backstop-entity-inference.test.ts,test/managed-facts-entity-inference.test.ts. #6159: every writer (both backstop buckets, the fence writes andpersistence/facts-maintenance.ts) dates a fact withfacts/event-time.tsfactEventTime(extractor date, thenvalidFrom, thenturnAt, then now) and the extraction prompt's observation date falls back toturnAt; the sweep's corpus pass setsturnAtfrom the session file's write time, vetted bycontext/corpus-windows.tscorpusFactTime(finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (test/sweep-corpus-fact-time.test.ts). #6113:resolveManagedFactsEmbedding(persistence/facts-maintenance.ts) reads the brain's DB-plane model only; a legacy row without a provider refusesembedding_configurationnaminggbrain migrate embeddings --to <gateway provider>:<model> --dry-run(the read-only preview; applying it needs paid authorization). Test:test/facts-embedding-bare-model.serial.test.ts. The notability-filter vocabulary (NOTABILITY_FILTERS,coerceNotabilityFilter) lives in import-lightsrc/core/facts/notability-filter.ts(re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly asfence_refused(nothing written for them). Large pages A7: the page entry (runPipeline) plans with thefacts_backstopwatermark (src/core/extraction-watermark.ts, capMAX_TURN_TEXT_CHARS): past a matching watermark the extractor reads only the appended text (PipelineInput.extractText;turnTextstays the full body, which the managed preparer compares with the page), an unchanged long page makes no model call, and a head or tail-window read returnsinput_truncatedon the inline result; the plan commits after an extraction that neither failed nor aborted. Test:test/extraction-watermark-facts.test.ts. #6946:fence-write.tsreturnslegacyFallback: true, databaseOnlyReason: 'url_clone'for a gbrain-owned--urlclone on an unmanaged brain, and the backstop does not warnfacts:fence-write-unexpected-fallbackfor it.src/commands/migrations/v0_32_2.ts+src/core/facts/unfenced-facts.ts— Phase B is the shared core passplanUnfencedFacts/fenceUnfencedFacts, which theextract_factscycle phase also runs on every cycle (#5299). It fences live unfenced facts (row_num IS NULL) only onto an existing source-scoped page, and never ontology observations (dimension IS NOT NULL, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinatormanaged_maintenance_adopt_fact_fencerequest (database-only pages included; a read-only pre-pass ofplanManagedPagecounts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits;test/fact-fence-adoption-exits.test.ts), and an unmanaged page is written under the source filesystem lock and page lock (.tmp+ parse + rename), mirrored intopagesand stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted asskipped_no_page(a recorded canonical file absent on this host is also listed inmissing_files), never materialized as stubs. #6610: an unmanaged database-only page (nosource_path/source_uri, no file at its slug path) is fenced in its database body through the coordinator (fenceDatabaseOnlyPage, no file target) whenresolveFactWriteTargetmakes the write database-only; an unbound source withoutpersistence.unbound_write=database_onlyleaves its rows inunbound_refused, whichextract_factsholds out of reconciliation without gating and doctorfence_integrityreports asunbound_legacy_factswith the opt-in (ask_user). The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278:planFenceuses the fence codec as the oracle (adoptableClaim): a legacy row adopts only whenparseFactsFence(renderFactsTable([row]))hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written intofacts.factwith the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only,~~x~~, a literal<br>) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as anUnadoptableFactRecord(source, page, fact id, reason class; never the claim text) and named infailed_pagesasFACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)in the cycle and the migration output; the page's other rows still adopt. G4:fenceRowOf(exported, narrowFenceRowInput) is the one fact-to-fence-row renderer; NULL notability/confidence render as column defaults (medium, 1). Tests:test/facts-fence-adoption-roundtrip.test.ts,test/extract-facts-unfenced-rows.test.ts,test/migrations-v0_32_2-managed.test.ts. #6946: a gbrain-owned--urlclone on an unmanaged brain is never fenced (skipped_url_clone); its rows stay database-only.src/core/google/loop-catchup.ts— open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds:recordGraceVerdictkeeps each threaddetectThreadLoopgrace-held (andloopExtractionEligibilitypasses) in connector stateloop_grace_holds(capGRACE_HOLDS_CAP2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, soconnector_held_itemsandwaitingcoverage never count them.settleDueGraceHoldsopens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches throughprocessThread(at mostGRACE_REFETCH_PER_SWEEP100 per sweep; a 404 drops the hold, a failure keeps it due).seedGraceBackfillseeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep setsloop_grace_backfill_doneafter a non-aborted sweep. Catch-up (managed sources only):runLoopsCatchupre-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (recordLoopsExtractOutcome, written by theloops_extracthandler intoop_checkpointsoploops-extract-outcomes, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own keyloops-catchup:<source>:<slug>:<rev>inside the waiting-depth ceiling, retries a dead-lettered job once (:retry) then settles it, honors the kill switch and chat availability, and setsloops_catchup.doneonly when every candidate is settled.seedLoopRechecks(#5012) seeds spec-less due holds for unmute re-checks and once for the newest thread of the top 500 senders with open reply-owed loops;recordWithheldVerdictkeepsloop_withheld_senders(cap 2,000). Tests:test/google-loops-recovery.serial.test.ts(+ Postgres twin).src/core/cycle/connector-extract.ts— the extract phase of a cycle with no on-disk checkout (connector sources, Postgres brains without--dir; #5875):runPhaseExtractDatabaseOnlyruns the bounded, source-scopedextractStaleFromDBdrain (CYCLE_STALE_DRAIN_BUDGET_MS; brain-wide when the cycle has no source id; managed brains route toextractManagedStaleLinks) and reportsextract: okwithdatabase_only: trueand the stale counters, orwarnnaming the first failed page, its code and fix (staleDrainFailures, shared withcycle.ts); a dry run reportsskipped. Tests:test/connector-cycle-extract.test.ts(+ Postgres twin), norunCyclemock.test/helpers/managed-connector-job-contract.ts(+test/managed-connector-job-contract.test.ts, its PostgreSQL twintest/e2e/managed-connector-job-contract.test.ts) — the managed connector-source job contract: every automatic maintenance job on an unbound Google connector source runs its real handler on a real queue and worker, and one detector checks guard refusals, committed-row receipts and dead letters. Staleness bound between the extract phase and a queuedloops_extract(#5961): the two jobs share no lock, so aloops_extractthe Gmail sweep queued can commit its commitment fact and republish a page (people/alice-examplein the fixture) after the cycle's extract phase stampedlinks_extracted_at, and that page reads stale again. The product behavior is eventual consistency with a maximum staleness of one cycle: the next cycle's extract phase re-extracts every page republished since its stamp.cycle_extract_loops_raceruns that worst-case order (cycle, then the competingloops_extract, then one more cycle) and asserts the page reads stale after the competing job and zero stale pages after the next cycle;cycle_extractmeasures one phase run alone. Every case runs its asserted jobs throughdrainQueue, which first cancels every other claimable (waiting/delayed) job, so a follow-up queued earlier in the case (the sweep'sloops_extract) cannot run after the asserted job and land its writes or embedding effects after the case's check.