Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
58.6 KB
Raw Blame

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> where CommandResult = { status, stdout, stderr } and status: null means killed at the timeout or never spawned; defaultCommandRunner on Bun.spawn — at timeoutMs it sends SIGTERM and, when the child has still not exited SIGKILL_GRACE_MS (3s) later, SIGKILL, so a child that ignores SIGTERM never hangs the caller; both timers are cleared in a finally — also the runner serve-service.ts types against; stdoutToStderr sends an inherited child's stdout to fd 2 so --json stdout stays pure): parseTailscaleStatus (BackendState — Running, NeedsLogin, NeedsMachineAuth, NoState, Stopped; Self.DNSName, CertDomains, and funnelCapable: true/false from Self.CapMap keys or Self.Capabilities entries carrying any Funnel form — funnel (NodeAttrFunnel), https://tailscale.com/cap/funnel-ports with or without its ?ports= query, or the legacy https://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/bin paths; the candidate list doubles as mcp-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.ts puts sudo in 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 flagless sudo <bin> up — a flagged up trips 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 to sudo a non-system binary — sudo <bin> set --operator=$USER && sudo <bin> up with the DISCOVERED path shell-quoted through shellQuote, because a binary outside sudo's secure_path is exactly that case) and TAILSCALE_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 of mcp-expose.ts never sees them, tailscaleServeArgv(port, { funnel }) (serve --bg / funnel --bg) + tailscaleServeOffArgv({ funnel }) (serve|funnel --https=443 --set-path=/ off — --set-path=/ scopes off to OUR / mount; without it the CLI removes every mount under :443 and, when more than one exists, prompts interactively — with stdin ignored the prompt reads EOF and the command exits 0 having removed nothing; never serve reset), parseServeStatusStrict (the only serve-status parser, fail-closed: background Web handlers, Foreground[<session>].Web handlers marked foreground: true, and TCP['443'].TCPForward as a non-proxy root handler; an empty document / {} / null is the legitimately empty view, but non-JSON, an array or a scalar returns null so mcp-expose.ts's readServeView can 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 bare https:// 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 injectable which / fileExists / runner defaults touch existsSync, process.env.PATH and process.platform, and tests replace them. Note tailscale status --json exits 0 in every BackendState (only the human-readable form exits 1 when logged out), and serve/funnel wait interactively rather than failing when HTTPS certificates or the Funnel attribute are off — which is why mcp-expose.ts pre-checks before starting them.

  • src/core/serve-service.ts — the persistent-service half of mcp expose, everything under gbrainPath('serve') (serveDir, adminTokenPath, wrapperPath, receiptPath, serveLogPath, serveErrPath) so GBRAIN_HOME is honored. SERVE_LAUNCHD_LABEL = 'com.gbrain.serve', SERVE_SYSTEMD_UNIT = 'gbrain-serve.service', detectServiceTarget(signals) → 'macos' | 'linux-systemd' | 'none' (a working user bus is required for systemd; cloud sandboxes and ephemeral containers fall to none). renderServeWrapper produces the 0755 launcher that sources the shell profiles and ~/.gbrain/env, prepends the Bun dir to PATH, reads the admin token from its file at run time into GBRAIN_ADMIN_BOOTSTRAP_TOKEN (the token is never written into the wrapper, plist or unit), resolves gbrain the way autopilot's wrapper does (baked installer path, type -P gbrain fallback) and execs serve --http --port N --public-url URL [--surface] [--enable-dcr]. resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists }) picks the baked program: a gbrain on PATH wins; a COMPILED binary — import.meta.url (or the injected metaUrl) under /$bunfs/, or an execPath that is not the bun runtime while argv[1] is absent/virtual — is [execPath] whatever its basename (release assets are renamed); otherwise the [bun, <cli.ts>] dev form only when that cli.ts exists on disk, else [execPath] rather than a path that cannot run; renderServeLaunchdPlist (RunAtLoad, KeepAlive, ThrottleInterval 30, logs to serve.log / serve.err, local escapeXml) and renderServeSystemdUnit (After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped — % → %% in ExecStart and both append: log paths, $ → $$ in ExecStart). ensureAdminToken (0700 dir, 0600 file created with wx semantics, 64 hex chars; reuse a file matching the exported ADMIN_TOKEN_SHAPE = ^[A-Za-z0-9_-]{32,}$ — the same regex serve-http.ts's resolveBootstrapToken accepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise), installServeService (launchd: domain-explicit launchctl bootout gui/<uid> <plist> — failure ignored — then launchctl bootstrap gui/<uid> <plist>, both through the one launchctl(run, uid, plist, { modern, legacy }) helper whose legacy launchctl unload / load fallback is used ONLY when the modern verb exits non-zero with stderr matching /Unknown command|unrecognized|not found/i, never on a genuine failure or a killed call, and which reports the verb whose result it returns; a bootstrap that fails with stderr matching LAUNCHCTL_SETTLE_RE (Input/output error, already in progress, \b5\b, \b37\b — launchd still unloading the previous job) is retried up to LAUNCHCTL_SETTLE_RETRIES (5) times, LAUNCHCTL_SETTLE_MS (1s) apart through the injectable sleep param (default setTimeout; mcp-expose.ts passes d.sleep), a success after retries is a note and an exhausted retry appends "(after N settle retries)" to error; systemd: daemon-reload → enable → restart so a regenerated wrapper takes effect; loginctl enable-linger best effort) / uninstallServeService (launchd: the same bootout gui/<uid> with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matching LAUNCHCTL_NOT_LOADED_RE (No such process|not loaded|Could not find|not find service) pushes launchctl <verb> failed: <describeFailure> into notes, and the exported launchdBootoutFailed(result) recognizes that note so mcp-expose.ts can say the job may still be loaded) / serveServiceState (launchctl print gui/<uid>/<label> / systemctl --user is-active); all three take uid?: number defaulting to process.getuid?.() ?? 501, threaded from mcp-expose.ts. Every supervisor subprocess carries a timeout — 60s for launchctl bootstrap/bootout (and the legacy load/unload) and systemctl --user enable/restart/disable, 15s for launchctl print, daemon-reload, is-active and loginctl enable-linger — and a status: null (killed) result counts as a failure (error / note) or unknown state; a failed call is described by describeFailure (its stderr, else stdout, else exit <status>). readExposeReceipt / writeExposeReceipt (expose.json, 0600, version 1, no secrets): the reader is a structural shape guard, not just version/port/public_url — it also requires mode in tailnet|funnel, a service object with a string wrapper_path, a target in macos|linux-systemd|none, a string state and string-or-null plist_path / unit_path, a tailscale object whose binary / dns_name are string-or-null, and string mcp_url / admin_url / admin_token_file; anything less is null (absent), so --status / --remove never dereference a half-written receipt. The token, receipt, wrapper, plist and unit writers refuse (clear error) when the target path is a symlink (lstatSync) before any supervisor call runs. Uses shellQuote from src/core/mcp-registration.ts; every filesystem/exec effect is behind injectable deps.

  • src/core/harness/verify.ts — Randomized server-side memory verification with revision-conditional cleanup and retained mutation UUIDs, with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.

  • src/core/persistence/memory-mutations.ts + memory-prepare.ts — managed remember, forget, and forget_fact: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). src/core/facts/single-prepare.ts isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: test/persistence-memory-mutations.test.ts runs identical races on PGLite and PostgreSQL; test/withdrawal-followup-writes.test.ts covers writes after a forget whose effects stay queued. #5836: an omitted entity is inferred before admission (inferRememberTarget), and the inferred slug is used only when planRememberTarget's checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed with warnings (NO_ENTITY/ENTITY_LINK_FAILED) + hint. The entity_inferred intent 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 in validate with the target row locked FOR UPDATE, so two replacements of one fact serialize and the second sees target_superseded. Refusals are invalid_params with code prefixes (target_withdrawn, target_superseded naming the chain head, target_expired, replaces_entity_mismatch, replaces_cross_page, replaces_duplicate); remote callers get not_found for private targets; equal text is a duplicate no-op. Every superseded outcome carries superseded_fact_id (plus replaced_by_caller for replaces). forget responses gain similar_active (facts/similar-active.ts) after commit and on replay, and semantic_review: false keeps the claim out of overnight review. Pinned by test/remember-replaces.test.ts. remember's write intent carries the transport-resolved ctx.sessionId (MCP _meta.session_id, clamped to 256 characters), and preparation stores it as the fact's source_session, so recall({session_id}) finds remembered facts; identity only, never an authorization input (test/remember-session.test.ts). #7248: a folder-less entity must resolve strictly or is refused with candidates; pending replies carry write_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.tsv is the finite writer census; canonical-writer-inventory.test.ts rejects unreviewed additions, and persistence-writer-fences.test.ts/pglite-maintenance-fence.test.ts exercise real engines, competing processes and separate homes.

  • src/core/persistence/sync-drain.ts — #5984: drains a managed sync in one invocation. runDrain re-enters the single-pass performManagedSync (which keeps returning partial / 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.ts registerRunDeadline, set by cli.ts when 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 only worktree_refreshing (its retry_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 carries drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }; drainNext builds next for the CLI from the shared syncResumeCommand (sync-reconcile.ts). The CLI (sync/run.ts single source, --all, --watch), serve's delegated runner and the sync job handler (#6706, bounded by SyncOpts.deadlineAtMs) set SyncOpts.drain; the PGLite owner delegate uses runDrain over IPC; the cycle, sync-administration.ts and worktree-refresh.ts keep their own loops. #6706: runDrain takes a caller deadlineAtMs (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), reports resumable / deadline when the deadline lands in a retry backoff, abandons a pass still running DEADLINE_PASS_GRACE_MS after it, and deadlinePassed stops the extra pass and the next stage; jobDisposition classifies a drained result for jobs (synced, continue when drainNext is safe to loop, needs_operator). src/core/minions/handlers/sync-job-drain.ts runs it in the sync job: planJobDrain (drain, lanes: 1, a deadline from job.deadlineAtMs or the row's wall-clock limit via WALL_CLOCK_THRESHOLD_MS_SQL, at most an hour, less 60 s; job-data controls only from trusted submitters; sync.job_drain=false turns it off), throttled progress, and settleJobDrain (the CLI's outcome/drain/next, incomplete, at most one continuation on a worker-backed brain, priority ≥ 5, whose next then observes it). A sync job that finds another live sync job on its source skips sync_in_progress (sync-handler-drain-6706.test.ts). readManagedSyncBacklog reads unfinished cursors' progress window (stamped by sync-run.ts on each advance, reset per drain) for gbrain doctor (managed_sync_backlog) and sources status, with resume_args built by sync-reconcile.ts managedSyncResumeArgs. #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 plus STALL_GRACE_MS (budgets read from persistence.*_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 ends resumable / preparation_abandoned, and SyncResult.breaker ends blocked / preparation_systemic; stall carries phase, step, waiting_on, cause, and a timer prints stalled <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) from StallProbe.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: a queue_capacity whose detail is outstanding=N limit=M) is retried with backoff up to 5 s apart while the drain prints waiting for write capacity (N outstanding of M); past the no-progress window it ends blocked / write_capacity with drain.capacity and writer status as next, 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's group publishes, admitAhead (sync-run.ts) freezes and admits the next group and records it in the cursor's window (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 in intent.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.ts dependencyKeys, 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 cursor FOR KEY SHARE, accepting pending, group and window members, 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 by claimedPredecessorState: a group member follows the member before it in its own group (its after names only the previous group), anything else follows after. 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_MESSAGE and laneFaultCancelMessage stay 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 as intent.lane; closeLaneRun at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by laneTask). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (claimNextLaneHead in 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 (executeClaimedGroup with lane). 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 exclusive acquireWorktree first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after LEASE_TURN_MS of continuous holding. Lane transactions begin in manifest order (awaitLaneBegin) and commit in manifest order (awaitLaneTurn, inside the transaction before the counters: the predecessor intent.after must 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). laneFallback in 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 in resolveBulkSettings (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 only sources.last_sync_at, inside withCoordinatedWrite and 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 freeze noEmbed, noExtract and noSchemaPack. #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 in inherited_options; nothing refuses over processing options, and explicitProcessing is 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. freezeEntry checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in renamed. #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 into legacySkips (printed by sync-diagnostics.ts with gbrain repair contextual-mode). A terminal checkpoint_validation_timeout receipt gets its hint from checkpoint-validation.ts. Content holds (#5988, sync-screen.ts): freezeEntry screens each import (company-profile cursors and sync.holds=fail excepted); a refused file becomes a hold written in the same transaction as the cursor step (saveCursor's inTx), 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 durable error_detail.fence, the message, or an older release's message) holds the same bytes even when the screen admits them (prepareTimeFenceHold, reason prepare_time); a compacted invalid_params / take_row_collision receipt 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 returns partial; it is converted once, gets no failure-ledger row and is logged as a conversion. sync.holds=fail and company-profile cursors keep blocking with the typed refusal. #6278: a preparation_stalled receipt (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_version null), the checkpoint never holds; preparationStalledHold (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through holdUnderGate, 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's breaker counts the run's stalled receipts (identities and streak, saved with each CAS): holdsEscalated's rule over the run's screened imports or BREAKER_STREAK (5) in a row trips it, the run stops blocked_by_failures with SyncResult.breaker (drain preparation_systemic), and the next run's convertBlockedCursor re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. sameContentAtOrigin and the waiver screens race the sync preparer against persistence.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_failed and recovered_frontmatter (buildHoldReport); dry runs list would_hold / screen_skipped. After the checkpoint commits the pass stamps drain step finish and emits managed_sync.finish; then (unless noExtract) the owner derives links for the source's stale pages through links-maintenance.ts under FINISH_BUDGET_MS (pages left over stay stale for gbrain extract --stale), so a PGLite-delegated sync and a Postgres sync take the same path; the result carries links, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while sources retry-held re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns partial / writer_yield instead of synced, so the drain's next pass retires the finished cursor and discovers again, taking them; a queue_capacity refused for outstanding requests (isWriteCapacityWait) is left out of the failure ledger because the drain waits it out. #6696: the cursor key comes from selectManagedCursor (sync-cursor-key.ts), which every managed caller crosses: a run without --strategy and 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 as noEmbed by 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). One op_checkpoints row per held file (sync-hold, fingerprint source:incarnation:path) plus a per-source sync-hold-summary row (count, and stale: holds whose page exists); writeGitHold / clearGitHold lock 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) feeds retry-held and legacy sync, and readGitHoldListing (count from the summary row, rows limited per source in SQL) feeds sources status, never readAllSourceHolds. recordSyncConversion logs each blocked request a managed run converted in place (sync-conversions, newest 20 per source, in the transaction that saves the converted cursor); sources status shows the newest 5. gitHoldItem gives every surface code, reason, key, line, location-only message, fix Action and docs anchor. #6188 invalid_fence holds carry meta.fence (reason, fence, section, rows, columns, section line), the file line of the first bad row (meta.line, from fenceFileLine when the screen holds it), fence_version and the last repair attempt (fence_repair); the summary row counts them (fences), and holdRepairSteps is 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 when FenceAutoRepair.active), other holds preview gbrain repair frontmatter, a mixed source names both; one fence hold's own fix stays that file's gbrain repair fences --only <path> preview (fenceHoldFix). One fence hold's fix (gitHoldFix → fence-repair/hold-fix.ts fenceHoldFix) is that file's --only <path> preview with the step its state calls for, and gitHoldItem carries the D16 fence object (classes, tier, auto_retry, next_attempt_after); callers that can read the maintenance state pass it (fenceAutoRepairFor). holdRescreenDue is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen); a streamed file_too_large hold (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_stalled holds carry meta.stall (request, step, waiting_on, attempts, the writing gbrain version, the sync's resume arguments) and count under stalled in the summary row and HoldRepairRoute; gitHoldFix routes them to gbrain sources writer status --source <id> --json, then sources retry-held, then the option-preserving sync (stalledHoldSteps), never to frontmatter repair, and holdRescreenDue re-screens them on a gbrain version change; buildHoldReport routes the escalation text by code. sync-import-provenance records (recordSyncImportProvenance, batched recordSyncImportProvenances) also carry disk_sha256 / disk_blob_oid (bytes on disk the page holds, #8071), revision and parser (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. screenFrozenImport builds its input with frozenImportScreenInput (rename base, the run's pack, sanity and purge tombstones) and screens it with screenFrozenContent, 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 in would_normalize), turns a refusal into a hold, or throws sync_parser_regression only when sync-import-provenance proves a validating gbrain imported the same bytes. sync-blobs.ts reads blob ids/sizes with chunked ls-tree -l and contents with cat-file --batch; freezeEntry reads each entry's pinned blob and content through readPinnedBlob / readPinnedContent (via sync-screen.ts pinnedBlob / pinnedContent): a miss lists that entry and up to 255 of the next committed imports in one ls-tree and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one cat-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.ts proves identical rows on PGLite and Postgres). held-reads.ts is the read side: get_page.file_held, stale on search/query hits and the held_files retrieval 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); stalled coverage routes a preparation_stalled hold 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 gets fenceHoldRelay: 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, freezeEntry holds each image import as managed_image_sync_unsupported (managedImageHold, dry-run screen too) before any content read, whatever sync.holds says: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), and holdRescreenDue re-screens it on change, removal, multimodal on or sources retry-held. On, freezeEntry freezes the bytes as base64 (pinnedImageBytes, frozenImageIntent), an oversize image takes oversizeHold, identical bytes are a no-op by hash, and sync-prepare.ts routes the entry to sync-image.ts. The summary row counts images; those holds never count toward holds_escalated or git_held_files.

  • src/core/persistence/file-repair.ts — managed_file_repair (#5988), the owner-internal put_page kind gbrain repair frontmatter --apply submits (accepted only from the trusted local CLI with managedFileImport; MCP is refused by the reserved-field gate, remote authority by the preparer). managedRepairRoot resolves the owner through checkOwner (owner-refusal.ts) and refuses owner_unavailable with the condition as its reason; submitManagedFileRepair re-reads the source's RepairBusySet (repair-busy.ts) right before admission and refuses sync_in_progress when 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 (isWriteTargetContained plus a component-wise lstat walk, no symlinks), requires the file's sha256 to equal the previewed beforeHash (changed_since_preview otherwise), recomputes prepareRepairPublication (the screenSyncImport + importFromContent preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as file (expectedBeforeHash = previewed hash; no file_database_drift check), applies the import (a held new file creates its page, a renameFrom moves the page with updateSlug), clears the Git hold (only while it is the holdObservedAt observation when the intent carries one, so a hold a newer sync wrote stays) and records sync-import-provenance in 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 its afterCommit is forwarded. A fence repair (gbrain repair fences) passes its FenceRepairReceipt as fenceRepair: submission and the preparer refuse (invalid_params, nothing written) a receipt parseFenceRepairReceipt rejects or whose before_sha256/after_sha256 are not the previewed and written bytes; the outcome carries it as fence_repair, the file target carries the commit note from fenceRepairCommit (effect-model.ts), and every refusal and fix names gbrain repair fences --source <id> instead of gbrain repair frontmatter (FileRepairKind, also taken by confinedRepairTarget and managedRepairRoot). 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 carries importProvenance (SyncPreparedMutation); its publication writes it in the publish transaction with the page id, revision and the disk half (syncDiskProvenance over the canonical writeback, else syncDiskBytes), 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. noEmbed suppresses the effect itself; noSchemaPack bypasses 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 through checkpoint-validation.ts and, for a run whose entries another cursor imported (overtaken, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass screenSyncImport (the already-published working-tree exemption, then screenImportContent with 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 clears releasedHolds and ignores supersededRequests (failed content refusals the run converted in place), and every Markdown import records sync-import-provenance (raw sha256, blob, gbrain version, quoting recoveries) and reports recovered_frontmatter / comment_value in its outcome. Tests: persistence-sync-origin-native.serial.test.ts, persistence-sync-options.serial.test.ts, persistence-sync-company.serial.test.ts. A same-slug renameFrom accepts 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 with updateSlug (same id, inbound links and history, old -> new in slug_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. syncGitTopLevel answers the checkout's git rev-parse --show-toplevel once per root and sync run, reading it again when the top level's .git entry is replaced or removed or a .git appears between it and the root. #6278: prepareManagedSyncMutation calls enterClaimStep at 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_projections and the rest, each naming git, fs or db where 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 with embedDeferred (#6696) prepares as noEmbed whatever the cursor's stored options say.

  • src/core/persistence/links-maintenance.ts — extractManagedStaleLinks (then the mention pass unless mentions: false, which sync passes) derives links for pages whose extraction watermark is stale with prepareAutomaticLinks (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 same withCoordinatedWrite transaction, 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 by markPagesAttendanceBlocked in engine-sql/pages.ts only while the revision still matches, cleared by markPagesExtractedBatch with the watermark); it is still reconsidered every run, and the links_extraction_lag doctor check counts it apart from lag while the marker equals the page's current revision. GBRA-130 A-1 (site links.extract_stale, one ItemRun per 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 by links-extraction-holds.ts; a page of a deleted source fails unknown_source (PageSourceMissingError). The sync tail inherits this. It is the one managed extraction path: managed sync, extractStaleFromDB on a managed brain, and the owner delegation all run it. runManagedStaleExtraction backs gbrain extract --stale on managed brains, locally or through the writer_extract_stale administration operation inside a PGLite owner (src/commands/extract-stale-delegate.ts, trusted CLI registration only). links-preparation.ts retargets a link written against a renamed page's old slug to the live canonical page through slug_aliases, as get_page does. 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): recordLinkExtractionFailures counts 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-held via clearLinkExtractionHolds); linkExtractionRetryFix is every report's fix. Cleared by markPagesExtractedBatch. 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. partialFenceRuns finds 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.ts on 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; --timeout and --hard-deadline stay strict. Legacy shared-secret sync refuses managed brains. test/persistence-sync-stdio-owner.test.ts starts 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's explicitProcessing list by shape, then ignores it (WIRE_SKEW_WINDOWS.explicitProcessing in src/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 of SYNC_FLAGS (src/core/sync-flags.ts); --lanes N/--no-lanes are accepted and not sent, and a dropped retired field prints retiredWireNotice.

  • 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.ts inferMissingSubjects links facts with no or fallback-only entity via inferFactSubject (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks entity_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 and persistence/facts-maintenance.ts) dates a fact with facts/event-time.ts factEventTime (extractor date, then validFrom, then turnAt, then now) and the extraction prompt's observation date falls back to turnAt; the sweep's corpus pass sets turnAt from the session file's write time, vetted by context/corpus-windows.ts corpusFactTime (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 refuses embedding_configuration naming gbrain 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-light src/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 as fence_refused (nothing written for them). Large pages A7: the page entry (runPipeline) plans with the facts_backstop watermark (src/core/extraction-watermark.ts, cap MAX_TURN_TEXT_CHARS): past a matching watermark the extractor reads only the appended text (PipelineInput.extractText; turnText stays 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 returns input_truncated on the inline result; the plan commits after an extraction that neither failed nor aborted. Test: test/extraction-watermark-facts.test.ts. #6946: fence-write.ts returns legacyFallback: true, databaseOnlyReason: 'url_clone' for a gbrain-owned --url clone on an unmanaged brain, and the backstop does not warn facts:fence-write-unexpected-fallback for it.

  • src/commands/migrations/v0_32_2.ts + src/core/facts/unfenced-facts.ts — Phase B is the shared core pass planUnfencedFacts / fenceUnfencedFacts, which the extract_facts cycle 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 coordinator managed_maintenance_adopt_fact_fence request (database-only pages included; a read-only pre-pass of planManagedPage counts 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 into pages and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as skipped_no_page (a recorded canonical file absent on this host is also listed in missing_files), never materialized as stubs. #6610: an unmanaged database-only page (no source_path/source_uri, no file at its slug path) is fenced in its database body through the coordinator (fenceDatabaseOnlyPage, no file target) when resolveFactWriteTarget makes the write database-only; an unbound source without persistence.unbound_write=database_only leaves its rows in unbound_refused, which extract_facts holds out of reconciliation without gating and doctor fence_integrity reports as unbound_legacy_facts with 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: planFence uses the fence codec as the oracle (adoptableClaim): a legacy row adopts only when parseFactsFence(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 into facts.fact with 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 an UnadoptableFactRecord (source, page, fact id, reason class; never the claim text) and named in failed_pages as FACTS_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, narrow FenceRowInput) 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 --url clone 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: recordGraceVerdict keeps each thread detectThreadLoop grace-held (and loopExtractionEligibility passes) in connector state loop_grace_holds (cap GRACE_HOLDS_CAP 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so connector_held_items and waiting coverage never count them. settleDueGraceHolds opens 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 through processThread (at most GRACE_REFETCH_PER_SWEEP 100 per sweep; a 404 drops the hold, a failure keeps it due). seedGraceBackfill seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets loop_grace_backfill_done after a non-aborted sweep. Catch-up (managed sources only): runLoopsCatchup re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (recordLoopsExtractOutcome, written by the loops_extract handler into op_checkpoints op loops-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 key loops-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 sets loops_catchup.done only 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; recordWithheldVerdict keeps loop_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): runPhaseExtractDatabaseOnly runs the bounded, source-scoped extractStaleFromDB drain (CYCLE_STALE_DRAIN_BUDGET_MS; brain-wide when the cycle has no source id; managed brains route to extractManagedStaleLinks) and reports extract: ok with database_only: true and the stale counters, or warn naming the first failed page, its code and fix (staleDrainFailures, shared with cycle.ts); a dry run reports skipped. Tests: test/connector-cycle-extract.test.ts (+ Postgres twin), no runCycle mock.

  • test/helpers/managed-connector-job-contract.ts (+ test/managed-connector-job-contract.test.ts, its PostgreSQL twin test/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 queued loops_extract (#5961): the two jobs share no lock, so a loops_extract the Gmail sweep queued can commit its commitment fact and republish a page (people/alice-example in the fixture) after the cycle's extract phase stamped links_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_race runs that worst-case order (cycle, then the competing loops_extract, then one more cycle) and asserts the page reads stale after the competing job and zero stale pages after the next cycle; cycle_extract measures one phase run alone. Every case runs its asserted jobs through drainQueue, which first cancels every other claimable (waiting/delayed) job, so a follow-up queued earlier in the case (the sweep's loops_extract) cannot run after the asserted job and land its writes or embedding effects after the case's check.