Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Commands (6/6)
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/commands/sync.ts—gbrain syncCLI + theperformSync/performFullSynclibrary entrypoints (consumed by the autopilot cycle and the Minion sync handler).performSyncInnerresolves the source's persistedconfig.strategy(markdown/code/auto) when the caller passes nostrategy— the autopilot lane, the dream cycle, the MCPsyncop and the single-source CLI path all omit it, and without this the walk fell back tomarkdown, importing nothing from a code source while still advancing the anchor and soft-deleting its modified code pages; an explicit--strategystill wins, so the--allfan-out is unchanged. Pinned bytest/sync-index-matches-tree.serial.test.ts(index == working tree across first/incremental/full sync). Six pure-function clusters live insrc/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts(see the grouped entry below) and are re-exported through this façade, so the full import surface is unchanged.performSyncruns under a writer lock: per-sourcegbrain-sync:<sourceId>wheneveropts.sourceIdis set, wrapped inwithRefreshingLockfromsrc/core/db-lock.tsso long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock;SyncOpts.lockId?: stringis the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (EMAXCONNSESSION) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whoselast_refreshed_atis withinGBRAIN_LOCK_STEAL_GRACE_SECONDS, defending an alive-but-starved holder); the import loop yields the event loop everyGBRAIN_SYNC_YIELD_EVERYfiles (setTimeout(0), notsetImmediate— Bun starves the timers phase) so the refreshsetIntervalheartbeat fires mid-import. This lock-identity invariant prevents async --allper-source worker racingsync --source fooon the global lock from corrupting the same source.performSyncthrows a typedSyncLockBusyErrorwhen the writer lock is held; the Minionsynchandler (src/commands/jobs.ts) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics.performSyncInneris RESUMABLE (incremental path): it drains a PINNED target commit (lastCommit..pin), banking drained file paths viaappendCompleted(append-only delta into theop_checkpoint_pathschild table, migration v115 — one row per path, O(delta) rather than an O(N²) full-array rewrite), keyed bysyncFingerprint({sourceId, lastCommit})fromsrc/core/op-checkpoint.ts(paths underop:'sync'; the pinned target underop:'sync-target'), and advanceslast_commit/last_sync_atONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they surviveEMAXCONNSESSION; the flush cadence is first-file then everyGBRAIN_SYNC_CHECKPOINT_EVERY(default 1000) files ORGBRAIN_SYNC_CHECKPOINT_SECONDS(default 10s), with a race-safependingCheckpointPathsdelta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (appendCompletedOnce, ordered before lock release throughregisterCleanup); and sustained flush failure aborts the run withreason:'checkpoint_unavailable'afterGBRAIN_SYNC_MAX_CHECKPOINT_FAILURESconsecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler —last_sync_atis never bumped on a partial), and the next runresumeFilters the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff and there is no cross-run staleness window. After import a pin-reachability gate (git merge-base --is-ancestor pin HEAD) decides: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and do not block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added inlastCommit..pinbut gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only fortotalChanges <= 100; large syncs defer to the resumableextract --stalewatermark +embed --stale/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Single-source and--alldeliver that intrinsic >100-file embed deferral the same way: a queuedembed-backfillon a worker-backed engine with federated v2 on, a manual-drain outcome without a worker; an explicit--no-embedsingle-source run submits nothing. Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites useengine.kind === 'pglite'. CLI accepts--workers N(alias--concurrency N) validated viaparseWorkers(explicit bypasses the file-count floor; auto path defers toautoConcurrency()). The newest-first descending-lex order usessortNewestFirst(addsAndMods)fromsrc/core/sort-newest-first.ts(shared withgbrain import).gbrain sync --allruns a continuous worker pool:parseWorkers-validated--parallel N(defaultmin(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-sourcewithSourcePrefix(src.id, ...)so everyslog/serrline carries[<source-id>];--skip-failed/--retry-failedare scoped per source (acknowledgeFailures(sourceId);--allacks every source, single-source acks only its own) and run UNDER parallel — the failure ledger is per-(source_id, path)and serialized throughwithLedgerLock, so recovery syncs never need--serial; a connection-budget stderr warning fires whenparallel × workers × 2 > 16(the× 2 per-file poolfactor: each per-file worker opens its ownPostgresEnginewithpoolSize=2). ExportsresolveParallelism,syncOneSource,buildSyncStatusReport,printSyncStatusReport,SyncStatusReportback thegbrain sources statusdashboard.--jsonenvelope{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}on stdout; human banners route to stderr viahumanSinksojqparses cleanly. Exit matrix: 0 all ok (sources skipped by--missing-path skipcount as ok), 1 any error.--missing-path <fail|skip>(default fail) handles sources whoselocal_pathdoes not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run;skipclassifies themskipped_missing_path(⊘ line, envelope entry withlocal_path, excluded fromerror_countand the rc gate) via the exported pure helpersparseMissingPathMode+partitionMissingPathSources, pinned bytest/sync-all-missing-path.test.ts; defaultfailstays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate does not exit 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job.) The dashboard SQL iscontent_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULLwitharchived = falseat the caller; embedding column resolved viaresolveEmbeddingColumn(undefined, cfg)fromsrc/core/search/embedding-column.tsso Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). Every sync delete lane (removed-file drain, full-sync reconcile, un-syncable-page cleanup, rename-stale reconcile) SOFT-deletes viaengine.softDeletePages:deleted_atis set for a 72h recovery window, the autopilot purge phase owns the eventual hard delete, the un-syncable-page sweep counts the rows it actually transitioned intoresult.deleted(a sweep-only run reportssynced, neverup_to_date; #4786), and a re-import within the window revives the page throughputPage's upsert (lanes without a threadedsourceIdfall back toDEFAULT_SOURCE_ID, matchingdeletePage's'default'scope). The removed-file drain is interleaved per-batch resolve+soft-delete usingengine.resolveSlugsByPaths+engine.softDeletePagesfromsrc/core/engine.ts(a 73K-delete commit takes ~292 SQL round-trips instead of ~146K, so one big-delete commit cannot jam every other source's sync); per-batch try-catch decomposes batch failures to one-elementsoftDeletePagesbatches per slug (same primitive, per-slug isolation), unrecoverable per-slug failures land infailedFilesand the run continues;pagesAffectedfilters to slugs that actually transitioned (phantom slugs and already-soft-deleted rows are excluded by the primitive'sdeleted_at IS NULLpredicate). The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan. An entry-time bookmark-reachability guard distinguishes a gc'd anchor (cat-filefails →performFullSync) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (git diff lastCommit..pinis an endpoint-tree compare, ancestry not required) so a force-push /master→mainconsolidation imports only the real delta instead of re-walking the whole tree forever; an oversized or failed diff degrades toperformFullSync.performFullSyncis itself authoritative for deletes — after an advancing full import it soft-deletes file-backed pages (source_path != nullAND strategy-awareisSyncable) whose source file no longer exists (samesoftDeletePages+ 72h-window semantics as the incremental lanes; already-soft-deleted rows don't inflate the reconcile count), sparingput_page/manual pages (nullsource_path) and metafiles. The stale-file decision routes through the pure, exportedplanReconcileDeletes(rows, currentFiles, isSyncablePath): it normalizes path separators on both sides of the membership test (a Windowspath.relativebackslash path vs a git-derived forward-slashsource_pathwould otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more thanMASS_RECONCILE_RATIO(50%) of the file-backed pages the strategy manages, on a source holding more thanMASS_RECONCILE_MIN_PAGES(20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion);GBRAIN_ALLOW_MASS_RECONCILE=1restores the unguarded delete for genuinely intended bulk removals. Pinned bytest/sync-reconcile-mass-delete.test.ts. Below the valve, stale pages are partitioned by git history via exportedlistEverCommittedPaths(repoPath)(onegit log --all --no-renames --diff-filter=A --name-onlypass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree viawritePageThrough, with a stderr hint to commit it ("absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned bytest/sync-reconcile-db-only.test.ts.resolveSlugByPathOrSourcePath(insrc/core/sync-git.ts— see its dedicated entry below) delegates toengine.resolveSlugsByPathswhensourceIdis set, keeping the legacyexecuteRawfallback for the no-sourceId path.failedFilesis hoisted to the top ofperformSyncInnerso both delete-decompose and import loops feed the same bookmark gate. The cost gate is the sharedrunInlineCostGate(one implementation on BOTH the--alland single-source paths; runs at the command layer, never insideperformSync), mode-aware viaresolveWorkerBackedSyncEmbedMode+ posture-awareshouldBlockSyncfromsrc/core/embedding.ts. The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not--serial; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-sourceembed-backfilljobs with their own$X/source/24hcap, default $25 viaSPEND_CAP_CONFIG_KEYfromembed-backfill-submit.ts; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off,--serial, or PGLite/unknown engine) gates on the DELTA estimate vssync.cost_gate_min_usd(default $0.50): below floor proceeds; above floor in a TTY prompts[y/N]; above floor in a non-TTY/--jsonsession auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reportsmanual_drain_requiredwith reasonno_worker_surface, and emits one exactgbrain embed --stale --source <id>command per source; a worker-backed runtime with--no-auto-embedreports the distinctauto_submit_disabledpolicy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes;spend.posture=tokenmaxmakes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree:estimateInlineNewTokensroutes through the sharedcomputeSyncDelta(src/core/sync-delta.ts) — fetch-first againstorigin/<branch>, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled;--fulladds the stale backlog (full sync sweeps it inline). Return shape carriesestimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'+ceilingReasons. HelpersresolveCostGateFloorUsd(engine)+resolveBackfillCapUsd(engine)resolve viaparseUsdLimit(off/unlimited→Infinity; floor accepts0= block-on-any-spend). The gate's--jsonstatus object carriesmode+gatediscriminators (dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax) + a paste-readyhint; on every proceed path it is RETURNED (CostGateOutcome.notice), never printed, and nested ascost_gateinside the ONE terminal envelope (stop paths — dry-run, cancelled — print their object as the only document); terminal single-source and--allenvelopes carry per-sourceembed_backfilloutcomes so machine readers see queued/manual/skipped state;Infinityfloors/caps render as the string'unlimited'(never raw, which JSON-serializes tonull);SyncStatusReportSourcegainsbackfill_queued/backfill_active/backfill_last_completed_at; cost previews readgetEmbeddingModelName()(no hardcoded OpenAI). Format splits on the explicit--jsonflag only (human text otherwise).SyncOpts.noSchemaPack(CLI--no-schema-pack, threaded throughperformSyncANDsyncOneSource) skipsloadActivePackso pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeatif (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')fires BEFOREimportFile(theprogress.tickfires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc:docs/architecture/serve-sync-concurrency.md(serve-delegated sync + theGBRAIN_SYNC_TRACE+--no-schema-packrecipes). On a PGLite host brain with a livegbrain serve, the cli.ts pre-connect hook routesgbrain syncthroughsrc/commands/sync-delegate.ts(delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C →sync_abort; embeds always deferred to the serve's drain) —SyncOpts.onProgressis the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress;printSyncResultis exported for the delegated result path. Pinned bytest/e2e/sync-status-pglite.test.ts(IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column),test/sync-cost-gate.serial.test.ts,test/sync-cost-preview.test.ts. Runaway-sync protection:resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})resolves a wall-clock hard deadline (precedence--no-hard-deadline>--hard-deadline <s>>--timeout <s>(non---all, which auto-arms the backstop) >GBRAIN_SYNC_MAX_RUNTIME_SECONDSenv > non-TTY default 3600s > none;HARD_DEADLINE_GRACE_SEC=30).src/cli.tsinstalls the out-of-band watchdog (seesrc/core/process-watchdog.ts) for the sync command BEFOREconnectEngineand disposes it in the dispatchfinally, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron.runSyncregisters a SIGINT handler that aborts an interruptAbortControllercomposed viacomposeAbortSignals(...)(anAbortSignal.anywrapper over the defined signals) with the per-source--timeoutsignal, so Ctrl-C returns a cleanpartialand releases the lock through the normalfinally(process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill).withRefreshingLockunref()s its refreshsetInterval. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing[gbrain phase]breadcrumbs are the diagnosis surface. Pinned bytest/sync-hard-deadline.test.ts(resolution precedence +composeAbortSignals). Monorepo subdir sources:--src-subpath <dir>(or a repo path that IS a subdir — auto-discovery viadiscoverGitRoot, i.e.git rev-parse --show-toplevel) splits the repo path intogitContextRoot(all git ops: pull/diff/rev-parse/cat-file) andsyncScopeRoot(walk/import/delete/rename scope); scoped syncs use git-root-relative slugs +source_path(full sync threadsslugRootintorunImport) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects../-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (isPathSafe: a non-symlink leaf resolves through its parent directory, since Bun's realpathSync fails on a name containing a backslash) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed intofailedFiles, so the bookmark can't advance past an escape); ahead of it, with holds active, the drain holds a symlink, a permission error or a committed file absent from the working tree (classic-file-holds.ts, re-classified each run byplanHoldRescreeninsync/holds.ts); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages.--exclude <glob>(repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the metafile posture); an all-excluded run warns loudly (NAV-4). The persistedsync.excludeconfig key (comma- or newline-separated patterns; a trailing/normalizes to a<dir>/**subtree glob) is UNIONED with per-call--excludeon EVERY sync path — union, not override, so an ad-hoc flag narrows further but never silently re-opens a scope the operator persisted, and internal callers with no flag surface (autopilot, minion sync jobs, dream cycle) inherit the same indexing scope. The persistedsync.include_hiddenkey is the dot-directory WAIVER's twin, read at the same spot with the same dialect and trailing-/normalization and unioned with per-call--include-hidden— the only way to express the waiver onsync --all(which refuses the flag), autopilot and the dream cycle; unset admits nothing, so the dot-directory default does not move. CAVEAT: both keys are BRAIN-GLOBAL — one exclude (or admit) list scopes EVERY source, includingsync --all(where the per-call flags are forbidden), so a pattern meant for repo A silently narrows (or widens) repo B; admission is the riskier direction; per-source scoping is a filed follow-up. The union resolves at the top ofperformSyncInner, ABOVE theperformFullSyncearly returns — position is load-bearing: the first sync's full walk is exactly where ignoring the persisted scope would permanently import excluded files that no later incremental revisits. Best-effort config read (an unreadable config never breaks a sync). A warn-and-continue internalgit pullfailure (non-timeout class — e.g. a local-path origin rejected byprotocol.file.allow=never) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returnspartialwithreason: 'pull_failed'instead ofup_to_date:last_commitAND thelast_sync_atheartbeat stay frozen (so doctorsync_freshness/sources statusstaleness fires), the single-source CLI exits non-zero,sync --allexits non-zero if any source hit it (JSON envelope carries the per-sourcereason), and the autopilot cycle's sync phase maps it towarn. Timeout-class partials keep their pre-existing exit-0 / phase-oksemantics (they converge on retry; a failing pull does not). Pinned bytest/sync-pull-failed-anchor.serial.test.ts.resolveSlugByPathOrSourcePathis threaded into all 4 delete/rename call sites — see its dedicatedsrc/core/sync-git.tsentry below for the resolution contract. Above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits anextractMinion job{stale: true, sourceId?, deferred_commit: pin}keyedextract-stale:<sourceId|default>:<pin>(repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep),timeout_msderived from extract.ts's exportedSTALE_TIME_BUDGET_MS+ headroom. The returned row is verified to be a live{stale:true}job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned bytest/sync-deferred-extract-queue.test.ts. Unscoped default-write guard: when the resolver lands on tierseed_defaultfor a single-source sync (not--all) andGBRAIN_ALLOW_DEFAULT_WRITEis unset,assessDefaultWriteGuard(src/core/source-resolver.ts) decides whether the brain's pages overwhelmingly live outsidedefault; if so the run printsformatDefaultWriteRefusal('sync', …)and exits 1 — except under--dry-run, which prints the same text prefixed[dry-run] a real run would be refused:and still previews (a dry run writes nothing; refusing it only hides information). Escapes:--source default(tierflag),--all, orGBRAIN_ALLOW_DEFAULT_WRITE=1; a failed assessment is fail-open. Pinned bytest/sync-default-write-guard.serial.test.ts+test/sync-default-write-guard-dry-run.test.ts. Managed single-source and--allCLI envelopes retain structuredfailures,failure_codes,run_id,target_commit, andcounts_scope: run_cumulative; blocked results exit nonzero.--retry-failedrequires explicit idle ordinary-source fresh admission with the same options; no managed--skip-failed. Google/GitHub API source kinds route before the managed Git cursor. Managed connector--retry-failedexplicitly admits a linked replacement after authority, source/owner, cursor and idle-state checks; pending work and old terminal receipts are not replaced. Unsupported connector dry-run, Git filtering/working-tree/code and--skip-failedoptions refuse before credentials/network; bound sources keep file publication and unbound sources use explicit connector database authority. On a managed source--skip-failedand--include-gitignoredrefuse at parse (refuseManagedForbiddenFlagsinsync/managed-no-pull.ts, codemanaged_sync_flag_refused);--retry-failedcounts every managed failure of the source (one cursor key per source since #6712 PR 1, so no failure sits under another key). Refactor wave 1 (W4 sync):src/commands/sync.tsis now the façade — it keeps theSyncResult/SyncOptstypes,runSync,resolveParallelism,syncOneSourceand re-exports every moved symbol, so importers need no change. The implementation described above lives insrc/commands/sync/(next entry). Size ceiling:scripts/module-size-limits.tsv(per-change raise history:git log -pon that file); the façade's ceiling dropped from 6,022 to 468 lines when the implementation moved.src/commands/sync/— thegbrain syncimplementation behind thesync.tsfaçade (refactor wave 1, W4 sync).perform.tsisperformSync(dispatch, filesystem lock, writer lock).incremental.tsisperformSyncInner, a short orchestrator that runs the phases in order and returns the firstpartiala drain produces:preflight.ts(repo, git root and scope, pull and HEAD — an abort of the sync signal or a process cleanup pass (SIGTERM/SIGHUP) stops the pull and returns partialpull_timeout, persistedsync.exclude/sync.include_hiddenunions, gc'd-bookmark / first-sync /--include-gitignoredfull-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is{ done }, otherwise an immutableSyncPlan),deletes.ts(un-syncable-modified sweep, batched removed-file drain),renames.ts(rename drain, per-rename apply, reconcile fallback; #5431 W14 P1.8: the cheap rename goes throughrename-collision.tsrenamePageOntoSlug, which repairssource_pathinside the rename transaction and classifies a unique violation: a tombstone at the destination is merged in onemaintenanceTransaction(the tombstone re-keyed<slug>~purged-<id>with its history, the page moves with its id), a live destination falls through to the add fallback, any other error fails the file without a checkpoint; the fallback's reconcile carries the stale row's identity onto the destination row first (carryRenameIdentity:recordRenameAlias,moveSlugBindings,movePageIdReferences);test/sync-rename-collision.test.tson both engines),imports.ts(concurrency and connection clamp, pacer, stall watchdog,importOnePath, serial / worker-pool drain whose pools connect withretryConnectTimeout, #5946; the #132 rule — never wrap the drain or its call inengine.transaction()— is pinned intest/sync.test.tsfor both files) andfinalize.ts(zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed).sync-run.tsdefinesSyncRun, the state the phases share across awaits, andSyncPlan; mutable fields are accessed only asrun.<field>and@checkpointfields are written only bysync-run.ts(createSyncRun,flushCheckpoint,markCompleted,maybeYield,registerCheckpointCleanup,partial,abortUnpersistedPin) — enforced byscripts/check-sync-run-state.ts(docs/TESTING.md#syncrun-state-guard).full.tsisperformFullSync(dry run, import, shared failure gate, reconcile of deleted files, stale embed); its DB-only reconcile (#2426) writes each page with no file back throughwritePageThrough(a page stored in segments is streamed) and returns every page whose re-export failed inreexport_failures(slug, path, code, message, fix;over_push_scan_capcarries a fix that does not send the agent back into the same full sync) while the run completes; the hold settle and the delete reconcile reuse runImport's walk only whenreusableWalkaccepts it (complete, same root, identical strategy / include-gitignored / --include-hidden / --exclude), and a reconcile whose reused walk names any page stale decides deletions on a fresh walk, because the import walk can miss a file restored since.run.tsis the CLI bodyrunSyncInner(break-lock, source resolution,--skip-failedpre-ack,runSyncAllfan-out,runSingleSourceSync/ watch), with flag parsing and usage text inargs.ts(parseSyncFlagsbefore the--break-lockbranch,parseSyncFanoutFlagsafter it,printSyncHelp). Helpers:checkpoint.ts(checkpoint keys, cadence env knobs),rename-reconcile.ts(tracked-slug liveness index, orphaned<rename:…>sentinel sweep),connector.ts,plain-directory.ts(a registered root with no.gitat or above it syncs throughrunImporton both modes: no deletes, no commit bookmark,last_sync_atstamped on a clean run, a--timeoutstop returned as atimeoutpartial; #8620: on a managed brain the reserved skill-bundle paths,skills/andskillpack.json(src/core/skill-reserved-paths.ts), stay with the shared skill publisher, passed torunImportasheldPathsand left out of the dry-run count, so the pack the 0.53.0 DB-only export installs cannot block the source),trigger.ts(gbrain sync trigger),report.ts(printSyncResult, nudges),missing-path.ts,gitignore.ts. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart:test/sync-run-ordering.serial.test.ts; parallel worker completion on Postgres:test/e2e/sync-run-workers-postgres.test.ts. Adding a sync phase: add a module that takes(run, Pick<SyncPlan, ...>, ...)and returnsSyncResult | undefined, and call it fromperformSyncInnerin order. #6712 PR 3 (L7):printSyncHelplists the "Managed brains" flags first, then "Classic brains / advanced";noteRetryFailedDeprecatedprints thesync_retry_failed_deprecatednotice once per process (the CLI pipeline andrunSyncInnerboth call it).src/commands/takes-mutation.ts— one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent.--sourceremains claim provenance,--source-idselects the logical source, and--dirbecomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting;runTakesRebuild(W9F item 8) isgbrain takes rebuild's parser and renderer, runningtakes_rebuildthrough a resident owner or the local engine (thin clients refused); queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON.test/persistence-cli-delegation.test.tsdrives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.src/commands/transcripts.ts— the transcripts command family, all local-only (ctx.remote=falseby construction).archive run|backfill|status|adopt-legacy|on|offdispatches tosrc/commands/transcripts-archive.ts(humanstatusadds a line naminggbrain transcripts archive runwhen the archive is on andmaintenance.autois false;--jsonis unchanged) (coresrc/core/transcripts/archive.ts, see core-services-3; no MCP operation).recent: raw.txtcorpus reads vialistRecentTranscripts(same library as the gatedget_recent_transcriptsop).ingest <path-or-glob>: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phasetranscripts.ingest), and callsrunTranscriptsIngestwith the CLI'smakeContextcontext, so on a writer-claimed brain each rendered part is submitted as aput_pagewrite request naming the page's current revision (a part whose publication would change nothing is screened request-free first and takes no admission; unmanaged brains and dry runs keep the direct importer;recover codex --applypasses the same context; pinned bytest/transcripts-managed-ingest.test.ts); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g.4gb) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (optranscripts-ingest, fingerprint = source + pathspec + format + adapter version + any explicit byte cap viaingestCheckpointFingerprintInput— a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan (a Codex sub-agent rollout,session_metapayload.source.subagent, has no user turn by design: the adapter reportssubagentRollout, the scan counts it insubagentRolloutsand printsN sub-agent rollouts (no user turns by design), and it keeps the scan clean; an ordinary assistant-only rollout is stilluserTurnsMissingdrift); no-arg = confined discovery table, the all flag imports the discovered set.status: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query —executeRaw, both engines — insrc/core/transcripts/discover.ts) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) tosrc/core/transcripts/ingest-facts.ts; a page that fails extraction counts infacts.pagesFailed, stays unfinished, and makes the command exit 1; a pass that stopped at its budget reportsfacts.budgetExhaustedandfacts.budgetReason, and pages skipped as too large or held by another run count infacts.pagesSkippedTooLargeandfacts.pagesLockSkipped(#8722). Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help).expandTilde(raw)(bare~, leading~/or~\\→ home dir;~userforms and a mid-string~stay literal) is the one tilde expansionexpandPathsapplies to every path spec.recover codex(src/commands/transcripts-recover.ts, logicsrc/core/transcripts/recover.ts; D15 for #5163): finds codex conversation pages in one source with no**User**anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default,--applyre-imports only the recoverable rollouts throughrunTranscriptsIngest(content-hash dedup, no facts, no watermark write). Pinned bytest/transcripts-recover-codex.test.ts.audit-secrets [--source-id S] [--json](src/commands/transcripts-audit.ts, logicsrc/core/transcripts/secret-audit.ts): the read-only installed-base audit that streams imported conversation pages (type = 'conversation'withtranscript_importfrontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config rowtranscripts.secret_auditfor the doctor checktranscript_secret_exposure(src/commands/doctor/checks/transcript-secrets.ts, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an olderTRANSCRIPT_SECRET_AUDIT_VERSIONor a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned bytest/transcripts-secret-audit.test.ts.src/commands/upgrade.ts— self-update CLI. The package has no postinstall, so the install step runs no migrations; post-upgrade owns them (GBRAIN_UPGRADE_OWNS_MIGRATIONS=1is still set for the install step). An install step that fails or times out aftergbrain --versionalready reports a newer version counts as installed. The run ends with aBinary:line (installed version, or upgrade failed) and aMigrations:line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (--force-retry <v>for wedged versions).runPostUpgrade()enumerates migrations from the TS registry (src/commands/migrations/index.ts) and tail-callsrunApplyMigrations(['--yes', '--non-interactive'])so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on[AGENT]notice (core/chronicle/upgrade-notice.ts). Install methods are bun, bun-link and binary (a compiled binary is found by Bun's/$bunfs/entrypoint, so a release asset keeps its published name); anything else isunknownand prints manual steps. It never runsclawhub update gbrain, which would install whatever skill anyone publishes under that name (#8464;test/upgrade.serial.test.ts). Before the swap of a bun-link or package install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (--no-bun-floor-checkoverrides, manual only;src/core/bun-floor.ts); after the swap it runsgbrain --helpas a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leafsrc/commands/movement-step.ts; guard:test/upgrade-post-swap-imports.test.ts). A tag-pinned reinstall hint (bunReinstallCommand,reinstallHintLines) probesgit ls-remote --exit-code --tags … refs/tags/v<x>beforebun remove -g gbrain, prints a restore line, and on Windows prints one step per line;planPinnedReinstallprobes the tag itself (published / not published / unknown) and falls back to the newest publishedv<x>tag (latestPublishedVersion) when the requested one is missing (#6662, D24;test/upgrade-release-tag-hint.test.ts). A verified version equal to the running one after the install step is no swap (#6828): it printsNo newer version was installed, skipslast_upgrade,JUST_UPGRADED, the cache reset and the smoke, and on a tag pin with no newer published tag the hint moves the install off the pin withto_version: latest, never a cached unpublished version (#6718). WithGBRAIN_SWAP_RECEIPTset it writes aSwapReceipt(installed/not_installed/installed_broken) for the autopilot channel (test/autopilot-unpublished-target-6828.test.ts). Tests:upgrade-migration-outcome.test.ts,upgrade-no-autopilot.serial.test.ts,upgrade-bun-link-arc.serial.test.ts.post-upgrade --json(D2,json: 'document'): human lines go to stderr and stdout is one report{status, apply_migrations:{exit_code}, schema, warnings[]}; it callsapplyMigrations()and still ends on any status apply-migrations returns (a failure is one envelope leading with the report). GBRA-175:--channel stable|alpha(latestis an alias ofalpha; resolution order in the Release channels entry below):resolveStableReleasemaps the commitrefs/tags/stablepeels to onto itsv<version>tag throughgit ls-remote, andinstallStableReleaseinstalls exactly that release (bun: remove then add#v<version>, restoring the previous release on failure; bun-link: fast-forward only; binary:fetchReleaseByTag), never downgrading. Before the swappreflightHostRestartrefuses (restart_refused, exit 3) when a running process could not be restarted; after post-upgrade the new build runsgbrain upgrade --restart-only(--no-restartskips it). Tests:upgrade-stable-channel.test.ts. A global install pinned to a tag or commit (bunGlobalExactTagPin(root, true)) is replaced with the newest published release the same way instead ofbun update, which keeps the pin.parseChannelArgandresolveStableReleaselive insrc/core/stable-channel.ts(re-exported).Release channels:
src/core/self-upgrade.tsresolves the channel (resolveReleaseChannel:--channel,GBRAIN_RELEASE_CHANNEL,self_upgrade.channel, defaultstable;latestnormalizes toalpha; an invalid value at the first present source is an error) and keeps the update cache (update-check.<channel>.json, tagged with the evidence policy; an older answer never overwrites a newer one, unless the stored check time is more than 5 minutes ahead of the clock, and a cache file dated more than 5 minutes ahead is stale, so a clock that moved back never freezes the cache (#8795)) and the time-based snooze (update-snoozed.<channel>.json) per channel;offeredVersionnever offers a downgrade except to move off aknown_badversion.src/core/stable-channel.tsreads and strictly parses the evidence record (stable.jsononstable-record;requiredEvidenceKeys:soak_run, plusmatrix_runfromMATRIX_REQUIRED_FROM), maps failures tostable_missing/stable_invalid/stable_unreadablewith sanitized causes, andresolveStableReleasechecks thestableandv<version>tags against the record commit.src/commands/upgrade-channel.tsplans an upgrade's target (channelTarget,runUpgradeDryRunforgbrain upgrade --dry-run --json) and refuses with the typed code.src/commands/check-update.tsrefreshUpdateCachenever reads a bare VERSION for stable and never falls back to alpha.src/core/release-channel-notice.tsprints the one-time[gbrain notice release_channel]line on stderr (marker file undernotices/; not under--json,serveormcp; only when no channel is set).src/core/install-ref.tsis the one ref every install surface names, linted byscripts/check-install-ref.ts. Tests:test/release-channel-w1.serial.test.ts,test/upgrade-stable-channel.test.ts,test/install-ref.test.ts. Docs:docs/guides/upgrades-auto-update.md#stable-channel.src/commands/upgrade-restart.ts— GBRA-175: the host side of the upgrade restart. Real process sources (consumer heartbeat rows on Postgres, the supervisor PID file, the worker registry,ps -U <uid> -ww -o pid=,ppid=,etime=,command=with/proc/<pid>/environGBRAIN_HOME matching on Linux; the install version above each entry point), the installed serve and autopilot services with the pid each manager runs (hostServices:systemctl --user show -p MainPID,launchctl list),terminateIfUnchanged(SIGTERM an MCP pid only whilepsstill shows the same server and start time),restartRefusal(ask_user +--stop-mcpwhen only MCP servers block, else the first manual step for the user),preflightHostRestart(pre-swap, every process stale) andrunHostRestart(gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]: plan, run, verify for up to 180 s (360 s after an autopilot hand-off) with the warm-socket probeprobeCliSocket). #7475:restartServeAfterSelfUpgrade, called each autopilot-daemon tick, restarts the serve the serve service runs once it is on an older build than the relaunched autopilot. It runs once per installed build (#8013:serve-restart-attempt.jsonsurvives autopilot relaunches), skips a serve service whose wrapper belongs to another brain (serveServiceRunsWrapper), runs the restart without blocking the daemon (hostExecutorspawns asynchronously, 120 s cap), only in auto mode, in quiet hours and when the brain is idle (computeAutopilotIdle), and audits asrestart_serve. #8776:autopilotLauncher(this brain's gbrain cron line fromcrontab -l, elseself_upgrade.autopilot_launcher external) feeds the planner's hand-off;upgradeRestartReadinessis the preflight plan from the process table alone, which doctor'sself_upgrade_healthreads (local doctor only).planServeRestartreports a serve the service does not run, or one on another install, asmanualand never restarts it. A serve counts as older only on evidence (a recorded build below this one, or no recorded build and a start before the install'spackage.jsonwas written); a newer or unknown serve, or an install on disk that is not this build, is left alone. Tests:upgrade-restart.test.ts,autopilot-serve-restart-7475.test.ts,autopilot-serve-restart-8013.test.ts.src/core/upgrade-restart.ts— GBRA-175: the pure half of the upgrade restart.collectHostProcesses(the process table is the authority: a heartbeat, PID-file or registry record whose pidpsdoes not show as gbrain is dropped;gbrainEntryskips wrappers such as tini,bunx,bun xandbun run <bin>, skips interpreter flags that take a value, resolves a relative entry against the process's/proc/<pid>/cwdand accepts asrc/cli.tswhose package two levels up is named gbrain (#8723); a process's parent is its nearest gbrain ancestor, and a worker with none is refused naming its parent's pid and executable, never its command line),planRestart(a service restarts only processes under its manager's pid;supervisorRestartArgvkeeps the launch options and PID file, read from--pid-file <path>, and drops a--flag=valuetoken that is neither a global flag nor--job-isolation=, because the supervisor that holds it ignored it and this build's=gate refuses it (#7619); an autopilot under no installed service gets ahandoffstep whenctx.autopilotLauncheris known (#8776: SIGTERM while the pid is unchanged, then the launcher must bring autopilot back), else a manual step naminggbrain autopilot --install; anything else is aManualStep),runRestartSteps,restartProblems(old pids gone, one build, roles and the supervised worker back, warm socket accepts) andunverifiedBuilds. A stale process whoseinstall_rootis another install than the one being upgraded gets areplace_copystep first when it is a Bun global copy (bunGlobalCopyOf: probe the tag,bun remove -gthenbun add -gunder itsBUN_INSTALL, restore on failure), else a manual step fromcopyFix; after the restartmismatchedBuildsnames any process back on another build, and the host'smismatchFixchains that replacement withgbrain upgrade --restart-only.src/commands/watch.ts—gbrain watch: the push transport. Reads turns from stdin as they arrive (user:/assistant:prefixes; unprefixed = user turn), keeps a rolling in-process window (--window-turns, default 4), callsvolunteerContextper turn, streams pointers to stdout (--jsonfor JSONL with turn attribution), logschannel: 'watch'events with a per-session id. Session dedupe feeds already-pushed slugs back as priorContext so the core's slug-only suppression dedupes. Blocks in the stdin iteration (interactive alive until Ctrl-C/Ctrl-D; piped ends at EOF) — deliberately NOT in DAEMON_COMMANDS; SIGINT closes the stream so teardown flows through finishCliTeardown. Per-turn resolution failures are fail-open. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + THIN_CLIENT_REFUSED_COMMANDS (thin clients use thevolunteer_contextMCP op). Pinned bytest/watch-command.test.ts.src/commands/whoknows.ts—gbrain whoknows <topic>and MCPfind_experts: expertise and relationship routing.findExperts()threads source, page-privacy and holder policy through hybrid retrieval and enrichment, then requires an authorized effective-date read after optional salience work for every caller, including trusted local callers. Candidates absent from that exact(source_id, slug)map are omitted; required admission failures propagate. Optional salience failures retain the existing neutral factor.rankCandidates()usesscore = log(1 + raw_match) × max(0.1, exp(-days/180)) × (0.5 + 0.5 × salience), with salience normalized before ranking and alphabetical slug tie-breaking. Hybrid salience/recency boosts are disabled here to avoid applying them twice. Expert types are filtered in SQL and resolved from the pack byops/insights.ts; a failed pack load supplies an empty type list. CLI supports--explain,--limit,--jsonand thin-client routing. Math is pinned bytest/whoknows.test.ts; exact final admission, mutation races and SQL-failure behavior run on both engines intest/e2e/read-enrichment-privacy.test.ts.