Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
48.5 KB
Raw Blame

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 sync CLI + the performSync / performFullSync library entrypoints (consumed by the autopilot cycle and the Minion sync handler). performSyncInner resolves the source's persisted config.strategy (markdown/code/auto) when the caller passes no strategy — the autopilot lane, the dream cycle, the MCP sync op and the single-source CLI path all omit it, and without this the walk fell back to markdown, importing nothing from a code source while still advancing the anchor and soft-deleting its modified code pages; an explicit --strategy still wins, so the --all fan-out is unchanged. Pinned by test/sync-index-matches-tree.serial.test.ts (index == working tree across first/incremental/full sync). Six pure-function clusters live in src/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. performSync runs under a writer lock: per-source gbrain-sync:<sourceId> whenever opts.sourceId is set, wrapped in withRefreshingLock from src/core/db-lock.ts so 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?: string is 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 whose last_refreshed_at is within GBRAIN_LOCK_STEAL_GRACE_SECONDS, defending an alive-but-starved holder); the import loop yields the event loop every GBRAIN_SYNC_YIELD_EVERY files (setTimeout(0), not setImmediate — Bun starves the timers phase) so the refresh setInterval heartbeat fires mid-import. This lock-identity invariant prevents a sync --all per-source worker racing sync --source foo on the global lock from corrupting the same source. performSync throws a typed SyncLockBusyError when the writer lock is held; the Minion sync handler (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. performSyncInner is RESUMABLE (incremental path): it drains a PINNED target commit (lastCommit..pin), banking drained file paths via appendCompleted (append-only delta into the op_checkpoint_paths child table, migration v115 — one row per path, O(delta) rather than an O(N²) full-array rewrite), keyed by syncFingerprint({sourceId, lastCommit}) from src/core/op-checkpoint.ts (paths under op:'sync'; the pinned target under op:'sync-target'), and advances last_commit/last_sync_at ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive EMAXCONNSESSION; the flush cadence is first-file then every GBRAIN_SYNC_CHECKPOINT_EVERY (default 1000) files OR GBRAIN_SYNC_CHECKPOINT_SECONDS (default 10s), with a race-safe pendingCheckpointPaths delta (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 through registerCleanup); and sustained flush failure aborts the run with reason:'checkpoint_unavailable' after GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES consecutive 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_at is never bumped on a partial), and the next run resumeFilters 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 in lastCommit..pin but 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 for totalChanges <= 100; large syncs defer to the resumable extract --stale watermark + 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 --all deliver that intrinsic >100-file embed deferral the same way: a queued embed-backfill on a worker-backed engine with federated v2 on, a manual-drain outcome without a worker; an explicit --no-embed single-source run submits nothing. Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use engine.kind === 'pglite'. CLI accepts --workers N (alias --concurrency N) validated via parseWorkers (explicit bypasses the file-count floor; auto path defers to autoConcurrency()). The newest-first descending-lex order uses sortNewestFirst(addsAndMods) from src/core/sort-newest-first.ts (shared with gbrain import). gbrain sync --all runs a continuous worker pool: parseWorkers-validated --parallel N (default min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source withSourcePrefix(src.id, ...) so every slog/serr line carries [<source-id>]; --skip-failed/--retry-failed are scoped per source (acknowledgeFailures(sourceId); --all acks every source, single-source acks only its own) and run UNDER parallel — the failure ledger is per-(source_id, path) and serialized through withLedgerLock, so recovery syncs never need --serial; a connection-budget stderr warning fires when parallel × workers × 2 > 16 (the × 2 per-file pool factor: each per-file worker opens its own PostgresEngine with poolSize=2). Exports resolveParallelism, syncOneSource, buildSyncStatusReport, printSyncStatusReport, SyncStatusReport back the gbrain sources status dashboard. --json envelope {schema_version: 1, sources, parallel, ok_count, error_count, skipped_count} on stdout; human banners route to stderr via humanSink so jq parses cleanly. Exit matrix: 0 all ok (sources skipped by --missing-path skip count as ok), 1 any error. --missing-path <fail|skip> (default fail) handles sources whose local_path does 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; skip classifies them skipped_missing_path (⊘ line, envelope entry with local_path, excluded from error_count and the rc gate) via the exported pure helpers parseMissingPathMode + partitionMissingPathSources, pinned by test/sync-all-missing-path.test.ts; default fail stays 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 is content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL with archived = false at the caller; embedding column resolved via resolveEmbeddingColumn(undefined, cfg) from src/core/search/embedding-column.ts so 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 via engine.softDeletePages: deleted_at is 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 into result.deleted (a sweep-only run reports synced, never up_to_date; #4786), and a re-import within the window revives the page through putPage's upsert (lanes without a threaded sourceId fall back to DEFAULT_SOURCE_ID, matching deletePage's 'default' scope). The removed-file drain is interleaved per-batch resolve+soft-delete using engine.resolveSlugsByPaths + engine.softDeletePages from src/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-element softDeletePages batches per slug (same primitive, per-slug isolation), unrecoverable per-slug failures land in failedFiles and the run continues; pagesAffected filters to slugs that actually transitioned (phantom slugs and already-soft-deleted rows are excluded by the primitive's deleted_at IS NULL predicate). 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-file fails → 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..pin is an endpoint-tree compare, ancestry not required) so a force-push / master→main consolidation imports only the real delta instead of re-walking the whole tree forever; an oversized or failed diff degrades to performFullSync. performFullSync is itself authoritative for deletes — after an advancing full import it soft-deletes file-backed pages (source_path != null AND strategy-aware isSyncable) whose source file no longer exists (same softDeletePages + 72h-window semantics as the incremental lanes; already-soft-deleted rows don't inflate the reconcile count), sparing put_page/manual pages (null source_path) and metafiles. The stale-file decision routes through the pure, exported planReconcileDeletes(rows, currentFiles, isSyncablePath): it normalizes path separators on both sides of the membership test (a Windows path.relative backslash path vs a git-derived forward-slash source_path would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than MASS_RECONCILE_RATIO (50%) of the file-backed pages the strategy manages, on a source holding more than MASS_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=1 restores the unguarded delete for genuinely intended bulk removals. Pinned by test/sync-reconcile-mass-delete.test.ts. Below the valve, stale pages are partitioned by git history via exported listEverCommittedPaths(repoPath) (one git log --all --no-renames --diff-filter=A --name-only pass; 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 via writePageThrough, 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 by test/sync-reconcile-db-only.test.ts. resolveSlugByPathOrSourcePath (in src/core/sync-git.ts — see its dedicated entry below) delegates to engine.resolveSlugsByPaths when sourceId is set, keeping the legacy executeRaw fallback for the no-sourceId path. failedFiles is hoisted to the top of performSyncInner so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared runInlineCostGate (one implementation on BOTH the --all and single-source paths; runs at the command layer, never inside performSync), mode-aware via resolveWorkerBackedSyncEmbedMode + posture-aware shouldBlockSync from src/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-source embed-backfill jobs with their own $X/source/24h cap, default $25 via SPEND_CAP_CONFIG_KEY from embed-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 vs sync.cost_gate_min_usd (default $0.50): below floor proceeds; above floor in a TTY prompts [y/N]; above floor in a non-TTY/--json session 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, reports manual_drain_required with reason no_worker_surface, and emits one exact gbrain embed --stale --source <id> command per source; a worker-backed runtime with --no-auto-embed reports the distinct auto_submit_disabled policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; spend.posture=tokenmax makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: estimateInlineNewTokens routes through the shared computeSyncDelta (src/core/sync-delta.ts) — fetch-first against origin/<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; --full adds the stale backlog (full sync sweeps it inline). Return shape carries estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged' + ceilingReasons. Helpers resolveCostGateFloorUsd(engine) + resolveBackfillCapUsd(engine) resolve via parseUsdLimit (off/unlimited → Infinity; floor accepts 0 = block-on-any-spend). The gate's --json status object carries mode + gate discriminators (dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax) + a paste-ready hint; on every proceed path it is RETURNED (CostGateOutcome.notice), never printed, and nested as cost_gate inside the ONE terminal envelope (stop paths — dry-run, cancelled — print their object as the only document); terminal single-source and --all envelopes carry per-source embed_backfill outcomes so machine readers see queued/manual/skipped state; Infinity floors/caps render as the string 'unlimited' (never raw, which JSON-serializes to null); SyncStatusReportSource gains backfill_queued/backfill_active/backfill_last_completed_at; cost previews read getEmbeddingModelName() (no hardcoded OpenAI). Format splits on the explicit --json flag only (human text otherwise). SyncOpts.noSchemaPack (CLI --no-schema-pack, threaded through performSync AND syncOneSource) skips loadActivePack so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>') fires BEFORE importFile (the progress.tick fires 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 + the GBRAIN_SYNC_TRACE + --no-schema-pack recipes). On a PGLite host brain with a live gbrain serve, the cli.ts pre-connect hook routes gbrain sync through src/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.onProgress is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; printSyncResult is exported for the delegated result path. Pinned by test/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_SECONDS env > non-TTY default 3600s > none; HARD_DEADLINE_GRACE_SEC=30). src/cli.ts installs the out-of-band watchdog (see src/core/process-watchdog.ts) for the sync command BEFORE connectEngine and disposes it in the dispatch finally, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. runSync registers a SIGINT handler that aborts an interrupt AbortController composed via composeAbortSignals(...) (an AbortSignal.any wrapper over the defined signals) with the per-source --timeout signal, so Ctrl-C returns a clean partial and releases the lock through the normal finally (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). withRefreshingLock unref()s its refresh setInterval. 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 by test/sync-hard-deadline.test.ts (resolution precedence + composeAbortSignals). Monorepo subdir sources: --src-subpath <dir> (or a repo path that IS a subdir — auto-discovery via discoverGitRoot, i.e. git rev-parse --show-toplevel) splits the repo path into gitContextRoot (all git ops: pull/diff/rev-parse/cat-file) and syncScopeRoot (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + source_path (full sync threads slugRoot into runImport) 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 into failedFiles, 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 by planHoldRescreen in sync/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 persisted sync.exclude config key (comma- or newline-separated patterns; a trailing / normalizes to a <dir>/** subtree glob) is UNIONED with per-call --exclude on 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 persisted sync.include_hidden key 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 on sync --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, including sync --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 of performSyncInner, ABOVE the performFullSync early 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 internal git pull failure (non-timeout class — e.g. a local-path origin rejected by protocol.file.allow=never) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns partial with reason: 'pull_failed' instead of up_to_date: last_commit AND the last_sync_at heartbeat stay frozen (so doctor sync_freshness / sources status staleness fires), the single-source CLI exits non-zero, sync --all exits non-zero if any source hit it (JSON envelope carries the per-source reason), and the autopilot cycle's sync phase maps it to warn. Timeout-class partials keep their pre-existing exit-0 / phase-ok semantics (they converge on retry; a failing pull does not). Pinned by test/sync-pull-failed-anchor.serial.test.ts. resolveSlugByPathOrSourcePath is threaded into all 4 delete/rename call sites — see its dedicated src/core/sync-git.ts entry 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 an extract Minion job {stale: true, sourceId?, deferred_commit: pin} keyed extract-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_ms derived from extract.ts's exported STALE_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 by test/sync-deferred-extract-queue.test.ts. Unscoped default-write guard: when the resolver lands on tier seed_default for a single-source sync (not --all) and GBRAIN_ALLOW_DEFAULT_WRITE is unset, assessDefaultWriteGuard (src/core/source-resolver.ts) decides whether the brain's pages overwhelmingly live outside default; if so the run prints formatDefaultWriteRefusal('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 (tier flag), --all, or GBRAIN_ALLOW_DEFAULT_WRITE=1; a failed assessment is fail-open. Pinned by test/sync-default-write-guard.serial.test.ts + test/sync-default-write-guard-dry-run.test.ts. Managed single-source and --all CLI envelopes retain structured failures, failure_codes, run_id, target_commit, and counts_scope: run_cumulative; blocked results exit nonzero. --retry-failed requires 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-failed explicitly 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-failed options refuse before credentials/network; bound sources keep file publication and unbound sources use explicit connector database authority. On a managed source --skip-failed and --include-gitignored refuse at parse (refuseManagedForbiddenFlags in sync/managed-no-pull.ts, code managed_sync_flag_refused); --retry-failed counts 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.ts is now the façade — it keeps the SyncResult / SyncOpts types, runSync, resolveParallelism, syncOneSource and re-exports every moved symbol, so importers need no change. The implementation described above lives in src/commands/sync/ (next entry). Size ceiling: scripts/module-size-limits.tsv (per-change raise history: git log -p on that file); the façade's ceiling dropped from 6,022 to 468 lines when the implementation moved.

  • src/commands/sync/ — the gbrain sync implementation behind the sync.ts façade (refactor wave 1, W4 sync). perform.ts is performSync (dispatch, filesystem lock, writer lock). incremental.ts is performSyncInner, a short orchestrator that runs the phases in order and returns the first partial a 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 partial pull_timeout, persisted sync.exclude / sync.include_hidden unions, gc'd-bookmark / first-sync / --include-gitignored full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is { done }, otherwise an immutable SyncPlan), 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 through rename-collision.ts renamePageOntoSlug, which repairs source_path inside the rename transaction and classifies a unique violation: a tombstone at the destination is merged in one maintenanceTransaction (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.ts on both engines), imports.ts (concurrency and connection clamp, pacer, stall watchdog, importOnePath, serial / worker-pool drain whose pools connect with retryConnectTimeout, #5946; the #132 rule — never wrap the drain or its call in engine.transaction() — is pinned in test/sync.test.ts for both files) and finalize.ts (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). sync-run.ts defines SyncRun, the state the phases share across awaits, and SyncPlan; mutable fields are accessed only as run.<field> and @checkpoint fields are written only by sync-run.ts (createSyncRun, flushCheckpoint, markCompleted, maybeYield, registerCheckpointCleanup, partial, abortUnpersistedPin) — enforced by scripts/check-sync-run-state.ts (docs/TESTING.md#syncrun-state-guard). full.ts is performFullSync (dry run, import, shared failure gate, reconcile of deleted files, stale embed); its DB-only reconcile (#2426) writes each page with no file back through writePageThrough (a page stored in segments is streamed) and returns every page whose re-export failed in reexport_failures (slug, path, code, message, fix; over_push_scan_cap carries 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 when reusableWalk accepts 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.ts is the CLI body runSyncInner (break-lock, source resolution, --skip-failed pre-ack, runSyncAll fan-out, runSingleSourceSync / watch), with flag parsing and usage text in args.ts (parseSyncFlags before the --break-lock branch, parseSyncFanoutFlags after 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 .git at or above it syncs through runImport on both modes: no deletes, no commit bookmark, last_sync_at stamped on a clean run, a --timeout stop returned as a timeout partial; #8620: on a managed brain the reserved skill-bundle paths, skills/ and skillpack.json (src/core/skill-reserved-paths.ts), stay with the shared skill publisher, passed to runImport as heldPaths and 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 returns SyncResult | undefined, and call it from performSyncInner in order. #6712 PR 3 (L7): printSyncHelp lists the "Managed brains" flags first, then "Classic brains / advanced"; noteRetryFailedDeprecated prints the sync_retry_failed_deprecated notice once per process (the CLI pipeline and runSyncInner both 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. --source remains claim provenance, --source-id selects the logical source, and --dir becomes 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) is gbrain takes rebuild's parser and renderer, running takes_rebuild through 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.ts drives 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=false by construction). archive run|backfill|status|adopt-legacy|on|off dispatches to src/commands/transcripts-archive.ts (human status adds a line naming gbrain transcripts archive run when the archive is on and maintenance.auto is false; --json is unchanged) (core src/core/transcripts/archive.ts, see core-services-3; no MCP operation). recent: raw .txt corpus reads via listRecentTranscripts (same library as the gated get_recent_transcripts op). ingest <path-or-glob>: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase transcripts.ingest), and calls runTranscriptsIngest with the CLI's makeContext context, so on a writer-claimed brain each rendered part is submitted as a put_page write 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 --apply passes the same context; pinned by test/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 (op transcripts-ingest, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via ingestCheckpointFingerprintInput — 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_meta payload.source.subagent, has no user turn by design: the adapter reports subagentRollout, the scan counts it in subagentRollouts and prints N sub-agent rollouts (no user turns by design), and it keeps the scan clean; an ordinary assistant-only rollout is still userTurnsMissing drift); 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 — in src/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) to src/core/transcripts/ingest-facts.ts; a page that fails extraction counts in facts.pagesFailed, stays unfinished, and makes the command exit 1; a pass that stopped at its budget reports facts.budgetExhausted and facts.budgetReason, and pages skipped as too large or held by another run count in facts.pagesSkippedTooLarge and facts.pagesLockSkipped (#8722). Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). expandTilde(raw) (bare ~, leading ~/ or ~\\ → home dir; ~user forms and a mid-string ~ stay literal) is the one tilde expansion expandPaths applies to every path spec. recover codex (src/commands/transcripts-recover.ts, logic src/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, --apply re-imports only the recoverable rollouts through runTranscriptsIngest (content-hash dedup, no facts, no watermark write). Pinned by test/transcripts-recover-codex.test.ts. audit-secrets [--source-id S] [--json] (src/commands/transcripts-audit.ts, logic src/core/transcripts/secret-audit.ts): the read-only installed-base audit that streams imported conversation pages (type = 'conversation' with transcript_import frontmatter) 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 row transcripts.secret_audit for the doctor check transcript_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 older TRANSCRIPT_SECRET_AUDIT_VERSION or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by test/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=1 is still set for the install step). An install step that fails or times out after gbrain --version already reports a newer version counts as installed. The run ends with a Binary: line (installed version, or upgrade failed) and a Migrations: 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-calls runApplyMigrations(['--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 is unknown and prints manual steps. It never runs clawhub 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-check overrides, manual only; src/core/bun-floor.ts); after the swap it runs gbrain --help as 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 leaf src/commands/movement-step.ts; guard: test/upgrade-post-swap-imports.test.ts). A tag-pinned reinstall hint (bunReinstallCommand, reinstallHintLines) probes git ls-remote --exit-code --tags … refs/tags/v<x> before bun remove -g gbrain, prints a restore line, and on Windows prints one step per line; planPinnedReinstall probes the tag itself (published / not published / unknown) and falls back to the newest published v<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 prints No newer version was installed, skips last_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 with to_version: latest, never a cached unpublished version (#6718). With GBRAIN_SWAP_RECEIPT set it writes a SwapReceipt (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 calls applyMigrations() and still ends on any status apply-migrations returns (a failure is one envelope leading with the report). GBRA-175: --channel stable|alpha (latest is an alias of alpha; resolution order in the Release channels entry below): resolveStableRelease maps the commit refs/tags/stable peels to onto its v<version> tag through git ls-remote, and installStableRelease installs 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 swap preflightHostRestart refuses (restart_refused, exit 3) when a running process could not be restarted; after post-upgrade the new build runs gbrain upgrade --restart-only (--no-restart skips 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 of bun update, which keeps the pin. parseChannelArg and resolveStableRelease live in src/core/stable-channel.ts (re-exported).

  • Release channels: src/core/self-upgrade.ts resolves the channel (resolveReleaseChannel: --channel, GBRAIN_RELEASE_CHANNEL, self_upgrade.channel, default stable; latest normalizes to alpha; 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; offeredVersion never offers a downgrade except to move off a known_bad version. src/core/stable-channel.ts reads and strictly parses the evidence record (stable.json on stable-record; requiredEvidenceKeys: soak_run, plus matrix_run from MATRIX_REQUIRED_FROM), maps failures to stable_missing / stable_invalid / stable_unreadable with sanitized causes, and resolveStableRelease checks the stable and v<version> tags against the record commit. src/commands/upgrade-channel.ts plans an upgrade's target (channelTarget, runUpgradeDryRun for gbrain upgrade --dry-run --json) and refuses with the typed code. src/commands/check-update.ts refreshUpdateCache never reads a bare VERSION for stable and never falls back to alpha. src/core/release-channel-notice.ts prints the one-time [gbrain notice release_channel] line on stderr (marker file under notices/; not under --json, serve or mcp; only when no channel is set). src/core/install-ref.ts is the one ref every install surface names, linted by scripts/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>/environ GBRAIN_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 while ps still shows the same server and start time), restartRefusal (ask_user + --stop-mcp when only MCP servers block, else the first manual step for the user), preflightHostRestart (pre-swap, every process stale) and runHostRestart (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 probe probeCliSocket). #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.json survives autopilot relaunches), skips a serve service whose wrapper belongs to another brain (serveServiceRunsWrapper), runs the restart without blocking the daemon (hostExecutor spawns asynchronously, 120 s cap), only in auto mode, in quiet hours and when the brain is idle (computeAutopilotIdle), and audits as restart_serve. #8776: autopilotLauncher (this brain's gbrain cron line from crontab -l, else self_upgrade.autopilot_launcher external) feeds the planner's hand-off; upgradeRestartReadiness is the preflight plan from the process table alone, which doctor's self_upgrade_health reads (local doctor only). planServeRestart reports a serve the service does not run, or one on another install, as manual and 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's package.json was 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 pid ps does not show as gbrain is dropped; gbrainEntry skips wrappers such as tini, bunx, bun x and bun run <bin>, skips interpreter flags that take a value, resolves a relative entry against the process's /proc/<pid>/cwd and accepts a src/cli.ts whose 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; supervisorRestartArgv keeps the launch options and PID file, read from --pid-file <path>, and drops a --flag=value token 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 a handoff step when ctx.autopilotLauncher is known (#8776: SIGTERM while the pid is unchanged, then the launcher must bring autopilot back), else a manual step naming gbrain autopilot --install; anything else is a ManualStep), runRestartSteps, restartProblems (old pids gone, one build, roles and the supervised worker back, warm socket accepts) and unverifiedBuilds. A stale process whose install_root is another install than the one being upgraded gets a replace_copy step first when it is a Bun global copy (bunGlobalCopyOf: probe the tag, bun remove -g then bun add -g under its BUN_INSTALL, restore on failure), else a manual step from copyFix; after the restart mismatchedBuilds names any process back on another build, and the host's mismatchFix chains that replacement with gbrain 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), calls volunteerContext per turn, streams pointers to stdout (--json for JSONL with turn attribution), logs channel: '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 the volunteer_context MCP op). Pinned by test/watch-command.test.ts.

  • src/commands/whoknows.ts — gbrain whoknows <topic> and MCP find_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() uses score = 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 by ops/insights.ts; a failed pack load supplies an empty type list. CLI supports --explain, --limit, --json and thin-client routing. Math is pinned by test/whoknows.test.ts; exact final admission, mutation races and SQL-failure behavior run on both engines in test/e2e/read-enrichment-privacy.test.ts.