Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs: gbrain sources refresh in write refusals, canonical writers, live sync, multi-source and key files
garrytane79cb322b10a
diff --git a/docs/architecture/canonical-writers.md b/docs/architecture/canonical-writers.mdindex 2a8c678d07..0565bc5bfc 100644--- a/docs/architecture/canonical-writers.md+++ b/docs/architecture/canonical-writers.md@@ -66,9 +66,19 @@ the same options resumes the remaining durable cursor.The source checkpoint commits only after the entire selected cursor is exhaustedand every admitted page has a committed receipt. It takes the source-exclusiveguard before authentication/request/page locks and checks the original anchor,-source incarnation, topology and owner epoch. Code/image importers, ignored-file-walks and Git pull/rebase remain explicitly refused in managed mode until their-own prepared publication and recovery paths exist. Remote sync retains the+source incarnation, topology and owner epoch. Code/image importers and ignored-file+walks remain explicitly refused in managed mode until their own prepared+publication and recovery paths exist. Git pull/rebase stays refused inside sync+and cycles; the one sanctioned Git writer is `gbrain sources refresh <source>`+(`src/core/persistence/worktree-refresh.ts`). It refuses new checkout writes for+every source bound to the worktree at admission (`worktree_refreshing`), waits+until queued requests and Git effects on the worktree finish, then, holding the+worktree native lock while claims stop (`fenced`), verifies HEAD and runs+`git merge --ff-only`. Pages and the source checkpoint advance only through the+ordinary managed `--no-pull` sync that follows, so every imported page is a+journaled request. A durable `persistence_worktree_refreshes` row lets a+restarted owner converge an interrupted refresh without adopting an unverified+HEAD. Remote sync retains theoriginal `submit_job` principal, admin/source/operation ceiling and normalizedpayload; runtime options cannot expand that grant and current revocation ischecked before publication.diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 068d0e046a..0242b85705 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -204,3 +204,4 @@ src/core/repair/stale-atoms.ts 2 coordinator gbrain repair stale-atoms retires asrc/commands/sources-mirror.ts 1 engine_guard `gbrain sources mirror-readonly|mirror-writable` (#5409) updates only sources.config.mirror_read_only, exactly as `sources federate` updates sources.config.federated; the sources managed_writer_guard trigger governs the row and no page, fact or file is written.src/core/sync-upstream.ts 1 engine_guard `recordUpstreamObservation` (#5255/#5176) updates only sources.upstream_checked_at, upstream_commit and upstream_behind, observations of the checkout's Git upstream outside managed_writer_guard's protected topology and checkpoint tuples; no page, fact or file is written, and a failure never fails the sync.src/core/persistence/mirror-read-only.ts 1 coordinator classifyMirrorPage stamps pages.database_only_reason=mirror_read_only only inside the coordinator publication transaction of a page write that published no file into a read-only mirror source (#5409), as classifyUnboundPage does for unbound sources.+src/core/persistence/worktree-refresh.ts 1 coordinator `gbrain sources refresh` (F0) is the one sanctioned managed Git writer: it fast-forwards the checkout only under the worktree native lock after admission refused and claims stopped every checkout write (`fenced`), then updates only sources.upstream_checked_at/upstream_commit/upstream_behind in the merged bookkeeping transaction; pages and the checkpoint advance through the ordinary managed --no-pull sync.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 52e4589adc..fcee359fba 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -35,6 +35,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/sources-set-path.ts` — `gbrain sources set-path <id> <path> [--force]`: unmanaged installations retain the legacy pointer repair and overlap check. Managed installations use the verified lifecycle rebind; force never bypasses ownership or manifest checks. Relative paths and MSYS spellings are normalized before routing. The `default_source_local_path` doctor check names this as the repair.-- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit}`. `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.+- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh}`. `refresh` dispatches to `src/commands/sources-refresh.ts` (argument parsing, stdout text or `--json` result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in `src/core/persistence/worktree-refresh.ts`). `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.- `src/commands/storage.ts` — `gbrain storage status [--repo P] [--json]`. Split into pure data (`getStorageStatus`) + JSON formatter + human formatter (ASCII-only) matching the `orphans.ts` pattern. `PageCountsByTier` and `DiskUsageByTier` are distinct nominal types so swaps fail at compile time. The repo and the counted source come from `resolveRestoreTarget` (`src/core/restore-target.ts`, the `export --restore-only` rule), and a page is listed missing exactly when that export would restore it (`isDbOnly`, then `restoreFilePath` in the page source's `scannerSlugRootMode` and `nativeFileTarget`: the recorded `source_path`, else `<slug>.md`, absent; the repo walk answers without a per-page syscall whenever it saw that exact file as a regular file under real directories, and a recorded path starting with the repo's path inside its git checkout, which export re-anchors, takes the full check), so the printed `Use: gbrain export --restore-only --source <id> --repo <path>` (the path passed through `shellQuote`, `src/core/shell-quote.ts`) writes exactly the listed files into `--dir` (default `./export`, not the repo). An unsafe recorded path or a symlinked/ambiguous file target (`OperationError` from `nativeFileTarget`) becomes one warning per reason (lowest slug plus a count of further pages) plus the refusal export would give, printed even when no file is missing; a repo whose own owner (`resolveSourceForRepoPath`: dotfile, then longest registered `local_path`) is archived is refused too (unless an active source is registered at the repo's exact path, which owns it outright), although export's exact-path rule would fall back to the only active source; a refused rule prints `Cannot suggest a restore command:` and falls back to the `--repo` / default-source path, counting the active repo owner's pages (dotfile, then longest registered `local_path`) or every source's pages when no active source owns it. `restoreSource` / `restoreRefusal` carry this in the JSON result. Pinned by `test/storage-restore-hint.test.ts`.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 06766cb360..468d1c339a 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -69,6 +69,8 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres.+- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`.+- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` bound to its revision. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex d64ef6f769..511d88e871 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Doctor's `checkSyncFreshness` also applies this predicate, including the legacy query fallback: disabled sources contribute neither warnings nor freshness counts; only boolean `false` disables, not the string `'false'`. `checkCycleFreshness` still monitors their maintenance cycles. Pinned by `test/doctor-sync-policy.test.ts` and `test/doctor-cycle-freshness.test.ts`. Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).-- `src/core/sync-upstream.ts` — upstream observation for remote-tracking sources (#5255/#5176). `observeUpstream(root, syncedCommit)` reads the checkout's `@{upstream}` commit, the newer of the `FETCH_HEAD` and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and `rev-list --count` of upstream commits the synced commit lacks; `recordUpstreamObservation` (called by `performSync` in `src/commands/sync/perform.ts` after every non-dry-run legacy or managed sync, best-effort) writes them to `sources.upstream_checked_at` / `upstream_commit` / `upstream_behind`, which `managed_writer_guard` does not protect. `upstreamFreshness` is doctor `sync_freshness`'s separate "upstream checked" verdict (a `remote_url` source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. `managedPullWarning` / `UpstreamRefresh` back the cycle sync phase (`runPhaseSync` in `src/core/cycle.ts`), which runs a managed `pull: true` as no-pull and reports `details.upstream_refresh` (`pulled|failed|skipped_managed|not_requested`) plus a `managed_pull_skipped` warning when the checkout tracks an upstream. Tests: `test/managed-cycle-pull-upstream.test.ts`, the pull row of `test/managed-phase-matrix.test.ts`.+- `src/core/sync-upstream.ts` — upstream observation for remote-tracking sources (#5255/#5176). `observeUpstream(root, syncedCommit)` reads the checkout's `@{upstream}` commit, the newer of the `FETCH_HEAD` and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and `rev-list --count` of upstream commits the synced commit lacks; `recordUpstreamObservation` (called by `performSync` in `src/commands/sync/perform.ts` after every non-dry-run legacy or managed sync, best-effort) writes them to `sources.upstream_checked_at` / `upstream_commit` / `upstream_behind`, which `managed_writer_guard` does not protect. `upstreamFreshness` is doctor `sync_freshness`'s separate "upstream checked" verdict (a `remote_url` source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. `managedPullWarning` / `UpstreamRefresh` back the cycle sync phase (`runPhaseSync` in `src/core/cycle.ts`), which runs a managed `pull: true` as no-pull and reports `details.upstream_refresh` (`pulled|failed|skipped_managed|not_requested`) plus a `managed_pull_skipped` warning when the checkout tracks an upstream. A managed brain's fix (the warning and doctor's behind/unknown verdict) is `gbrain sources refresh <source>`; an unmanaged one's is `gbrain sync --source <source>`. Tests: `test/managed-cycle-pull-upstream.test.ts`, the pull row of `test/managed-phase-matrix.test.ts`.- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.serial.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped.diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsvindex 4f58c6e258..0f5ccb9fcf 100644--- a/docs/architecture/managed-mutating-writers.tsv+++ b/docs/architecture/managed-mutating-writers.tsv@@ -72,3 +72,4 @@ cli src/core/google/loops-extract.ts coordinator Loop commitments publish througcli src/core/facts/fence-write.ts coordinator Direct fence writes publish through publishManagedEntityFacts.cli src/core/chronicle/extract-events.ts coordinator Chronicle events and their depth timeline rows publish through publishMaintenancePage.cli src/core/persistence/purge-deleted.ts coordinator Shared purge used by the cycle, the purge job, the operation and the CLI.+cli src/commands/sources-refresh.ts coordinator gbrain sources refresh drains and fences the worktree, fast-forwards it under the native lock, then imports through the managed --no-pull sync's journaled page requests.diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex 66d4a407e0..3a8bbe0c4b 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -518,8 +518,9 @@ gbrain sources writer activate --brain host --confirm-quiesced \--admin-intent writer_activate --expected-state <fresh admin_state> --json```-After activation, managed sync requires `--no-pull` (Git pull/rebase needs an-explicit drained maintenance window) and refuses `--skip-failed` and+After activation, managed sync requires `--no-pull` (new upstream commits come in+through `gbrain sources refresh <source>`, the drained worktree-wide fast-forward;+see [worktree refresh refusals](../guides/write-refusals.md#worktree-refresh-refusals)) and refuses `--skip-failed` and`--include-gitignored`; after fixing a failed item run`gbrain sync --no-pull --retry-failed` with the same source and options. Resumeautopilot with `gbrain autopilot resume` and re-enable the hooks you stopped.diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex fa452c619e..6e28a3aa60 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -235,6 +235,32 @@ vars — incident-time escape hatches, not everyday knobs.`git status` first. Gitignored files stay excluded either way (use`--include-gitignored` for those).+8. **A managed brain pulls only through `gbrain sources refresh`.** Managed+ sync refuses to pull (`gbrain sync` needs `--no-pull`) and a cycle asked to+ pull syncs the checkout as it is, because a Git merge rewrites files that+ accepted writes may be publishing into. To take new upstream commits, run+ on the owner host:++ ```bash+ gbrain sources refresh <source-id>+ ```++ It fetches, refuses new writes to every source that shares the checkout+ (`worktree_refreshing`, retryable) until queued ones finish, fast-forwards+ with `git merge --ff-only` and runs the managed `--no-pull` sync for each of+ those sources. `--dry-run` fetches and previews. Uncommitted files the+ upstream does not touch are kept and listed; dirty files it does touch, a+ diverged branch or an unfinished sync cursor refuse with the command to run+ ([refusal reference](write-refusals.md#worktree-refresh-refusals)). Bounds:+ `--wait-drain <seconds>` (default 60; `sources.refresh_drain_wait_ms`,+ `GBRAIN_REFRESH_DRAIN_WAIT_MS`) and `--fetch-timeout-ms` (default 120000;+ `sources.refresh_fetch_timeout_ms`, `GBRAIN_REFRESH_FETCH_TIMEOUT_MS`).+ A refresh interrupted by a crash is finished by the restarted owner or by+ `gbrain sources refresh <source-id> --resume`. A cron that keeps a managed+ brain current runs the refresh instead of `git pull`.++ **Say to your agent:** *"Bring my notes source up to date with its remote."*+## How to Verify1. **Edit a file and search for the change.** Edit a brain markdown file,diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex 8d03289db8..4da522221c 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -223,12 +223,13 @@ gbrain sources federate <id>gbrain sources unfederate <id>gbrain sources mirror-readonly <id>gbrain sources mirror-writable <id>+gbrain sources refresh <id> [--dry-run] [--resume|--abandon] Managed brains: fast-forward the checkout and sync.```### Read-only mirror sourcesA source whose Git remote is the source of truth (a code or docs repository-you keep current with `git pull --ff-only`) can be marked a read-only mirror:+you keep current from upstream) can be marked a read-only mirror:```bashgbrain sources mirror-readonly <id>@@ -246,14 +247,22 @@ write on, except for pages created while the source was a mirror: those haveno file in the checkout and stay database-only. Git effects of a mirror'swrites (for example a `forget`) complete as skipped. The flag is off by default.-A managed brain never pulls inside a cycle, so a mirror is advanced outside-gbrain and then synced without pulling:+A managed brain never pulls inside a cycle. Advance a managed checkout with+one command on its owner host:```bash-git -C <checkout> pull --ff-only-gbrain sync --source <id> --no-pull+gbrain sources refresh <id>```+It refuses new writes to every source that shares the checkout until queued+ones finish, fast-forwards it with `git merge --ff-only`, then syncs each of+those sources without pulling. Sources bound to one checkout (for example+`notes/` and `docs/` of the same repository) are refreshed together, because a+merge rewrites files of all of them. `--dry-run` previews the incoming commit;+refusals are listed under+[worktree refresh refusals](write-refusals.md#worktree-refresh-refusals). A+brain that is not managed keeps pulling inside `gbrain sync --source <id>`.+The autopilot cycle syncs the checkout as it is and reports`upstream_refresh: "skipped_managed"`; `gbrain doctor` (`sync_freshness`) says"upstream unknown" when the checkout was not fetched in the last 24 hours. Seediff --git a/llms-full.txt b/llms-full.txtindex ad1c469fb5..6902cd29df 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5069,6 +5069,32 @@ vars — incident-time escape hatches, not everyday knobs.`git status` first. Gitignored files stay excluded either way (use`--include-gitignored` for those).+8. **A managed brain pulls only through `gbrain sources refresh`.** Managed+ sync refuses to pull (`gbrain sync` needs `--no-pull`) and a cycle asked to+ pull syncs the checkout as it is, because a Git merge rewrites files that+ accepted writes may be publishing into. To take new upstream commits, run+ on the owner host:++ ```bash+ gbrain sources refresh <source-id>+ ```++ It fetches, refuses new writes to every source that shares the checkout+ (`worktree_refreshing`, retryable) until queued ones finish, fast-forwards+ with `git merge --ff-only` and runs the managed `--no-pull` sync for each of+ those sources. `--dry-run` fetches and previews. Uncommitted files the+ upstream does not touch are kept and listed; dirty files it does touch, a+ diverged branch or an unfinished sync cursor refuse with the command to run+ ([refusal reference](write-refusals.md#worktree-refresh-refusals)). Bounds:+ `--wait-drain <seconds>` (default 60; `sources.refresh_drain_wait_ms`,+ `GBRAIN_REFRESH_DRAIN_WAIT_MS`) and `--fetch-timeout-ms` (default 120000;+ `sources.refresh_fetch_timeout_ms`, `GBRAIN_REFRESH_FETCH_TIMEOUT_MS`).+ A refresh interrupted by a crash is finished by the restarted owner or by+ `gbrain sources refresh <source-id> --resume`. A cron that keeps a managed+ brain current runs the refresh instead of `git pull`.++ **Say to your agent:** *"Bring my notes source up to date with its remote."*+## How to Verify1. **Edit a file and search for the change.** Edit a brain markdown file,@@ -9928,7 +9954,7 @@ of making a duplicate.| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. || <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. || <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |-| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | For a source whose remote is authoritative (it never receives brain writes you need as files), make it a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) once, then advance it and sync without pulling: `gbrain sources mirror-readonly <source> && git -C <checkout> pull --ff-only && gbrain sync --source <source> --no-pull`. The printed `fix` fills in the real source and checkout. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. A coordinated in-gbrain fast-forward refresh is planned; until then this is the supported sequence. |+| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. || <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). || <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |@@ -9972,6 +9998,42 @@ when lifetime request IDs or receipt bytes reach 80% of a limit, with the`gbrain config set` value to use; outstanding-request, queued-byte andrecovery-byte limits can refuse writes without that warning.+## Worktree refresh refusals++`gbrain sources refresh <source>` is the one supported way to move a managed+checkout to new upstream commits. It runs on the source's registered owner+host, fetches, then refuses new writes to every source that shares the+checkout while queued writes finish, fast-forwards with `git merge --ff-only`+and syncs each of those sources with `--no-pull`. Each refusal below prints+`code`, a one-line `cause`, a literal `fix` with the real source filled in and+this anchor (`--json` puts them in one object on stdout); the command exits 1.++**Say to your agent:** *"Pull the latest commits into my notes source."* or+*"The refresh was refused. What do I need to do?"*++| Reason | Error code | What it means | Recovery |+| --- | --- | --- | --- |+| <a id="refresh_not_managed"></a>`refresh_not_managed` | `refresh_not_managed` | The brain is not managed, or the source has no claimed checkout. Plain sync already pulls such a source, so there is nothing to coordinate. | `gbrain sync --source <source>`. |+| <a id="refresh_not_owner"></a>`refresh_not_owner` | `refresh_not_owner` | This host is not the source's registered owner, and only the owner may move its checkout. | Run `gbrain sources refresh <source>` on the owner host; `gbrain sources writer status <source>` names it. |+| <a id="refresh_no_upstream"></a>`refresh_no_upstream` | `refresh_no_upstream` | The checkout's branch tracks no upstream (or HEAD is detached), so there is nothing to fast-forward to. | `git -C <checkout> branch --set-upstream-to <remote>/<branch>` (the fix fills in the real values), then retry. |+| <a id="fetch_failed"></a>`fetch_failed` | `fetch_failed` | `git fetch` failed or did not finish within `sources.refresh_fetch_timeout_ms` (default 120000; `GBRAIN_REFRESH_FETCH_TIMEOUT_MS`; `--fetch-timeout-ms` wins over both). Nothing changed and no refresh record was written. | Retry. For a slow remote, raise the bound with `--fetch-timeout-ms <ms>` or `gbrain config set sources.refresh_fetch_timeout_ms <ms>`. Credentials are the user's: ask them to fix authentication rather than changing the remote. |+| <a id="refresh_diverged"></a>`refresh_diverged` | `refresh_diverged` | The checkout has commits its upstream lacks, so a fast-forward is impossible. Nothing changed. | Reconcile the histories and push from a clone that is not managed, then retry. `gbrain sources reclone <source>` replaces the checkout; ask the user first, because local commits are dropped. |+| <a id="refresh_dirty"></a>`refresh_dirty` | `refresh_dirty` | Uncommitted or untracked files overlap the incoming upstream changes (the first 20 are named), or `git merge --ff-only` refused for the same reason. HEAD did not move. Uncommitted files outside the incoming changes do not refuse; they are kept and listed as `preserved_uncommitted`. | Commit or discard the named paths, then retry. Check `gbrain sources writer status <source> --json` first: a pending Git effect may be about to commit a gbrain-published file. |+| <a id="sync_in_progress"></a>`sync_in_progress` | `sync_in_progress` | A managed sync of one of the checkout's sources has an unfinished cursor. Moving the checkout now would strand it, and the refresh never waits on a sync. | Run the printed `gbrain sync --source <source> --no-pull ...` resume command (it keeps the cursor's options), then retry. |+| <a id="refresh_in_progress"></a>`refresh_in_progress` | `refresh_in_progress` | Another refresh of the same checkout is active, or a command that changes which sources share the checkout (`sources add`, `remove`, `archive`, `restore`, `reclone`) ran while one was active. | `gbrain sources refresh <source> --resume`, then retry the source command with the same request ID. |+| <a id="refresh_drain_timeout"></a>`refresh_drain_timeout` | `refresh_drain_timeout` | Queued writes or Git effects on the checkout did not finish within `--wait-drain` (default 60 s; `sources.refresh_drain_wait_ms`; `GBRAIN_REFRESH_DRAIN_WAIT_MS`). The counts are in the message. The fence was lifted and HEAD did not move. | Retry, or wait longer with `--wait-drain <seconds>`. Inspect what is queued with `gbrain sources writer status <source> --json`. |+| <a id="refresh_source_changed"></a>`refresh_source_changed` | `refresh_source_changed` | HEAD moved (an outside commit or checkout), or the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. | Retry `gbrain sources refresh <source>`. |+| <a id="refresh_recovery_required"></a>`refresh_recovery_required` | `refresh_recovery_required` | Publication or source recovery is pending on the checkout, or a refresh was interrupted and HEAD is neither the commit it started from nor the verified upstream commit. Writes to the checkout stay refused until it is resolved; gbrain never adopts a HEAD it cannot verify. | `gbrain sources writer status <source>`, then `gbrain sources refresh <source> --resume`. When HEAD is unverified the fix names both ways out: reset to the start commit and run `--abandon`, or reset to the upstream commit and run `--resume`. Resetting is destructive, so ask the user first. |+| <a id="worktree_refreshing"></a>`worktree_refreshing` | `worktree_refreshing` | A write, or a managed sync started by a cycle or another command, reached a checkout while a refresh is draining or merging it. It was not journaled. `detail` is `retry_after_ms=1000`. Writes to database-only memory are not affected. | Retry the same request ID after about a second. `gbrain sources writer status <source>` shows the refresh. A cycle's sync is retried by the next cycle. |++A refresh is recorded in `persistence_worktree_refreshes` and survives a crash.+When the owner restarts it finishes the deterministic steps on its own: an+interrupted drain or a fence with HEAD unchanged is abandoned, and a merge+that already reached the verified upstream commit moves on to syncing.+`gbrain sources refresh <source> --resume` runs the remaining syncs. Doctor+reports `worktree_refresh_stuck` for a refresh active longer than 15 minutes,+with the resume command.+## Unbound sources on PostgresA source with a checkout path (`local_path`, or `sync.repo_path` for the