Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: --retry-failed becomes a deprecated alias of plain sync; managed help sections (#6712 PR 3 L7)

garrytan7e11d1e5ee4b
diff --git a/docs/architecture/canonical-writers.md b/docs/architecture/canonical-writers.md
index b37045235b..c8401fbd84 100644
--- a/docs/architecture/canonical-writers.md
+++ b/docs/architecture/canonical-writers.md
@@ -52,8 +52,8 @@ after 25 foreground commits or one second of continuous foreground service, sync
earns a bounded batch even while new interactive requests continue arriving. Interruption or a pending owner leaves the cursor and source
checkpoint intact. A later invocation resumes the frozen target; a newer Git
HEAD is a separate subsequent sync. A revision/file conflict blocks the cursor.
-After inspecting the conflict, `--retry-failed` can start a fresh discovery once
-all earlier admitted requests are terminal. `--skip-failed` cannot advance a
+After inspecting the conflict, the next plain sync can start a fresh discovery once
+all earlier admitted requests are terminal (`--retry-failed` is a deprecated alias of it). `--skip-failed` cannot advance a
managed checkpoint past failed receipts.
When PGLite already has a resident owner, the CLI authenticates before opening
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index fe7afae631..e00d7a5d0a 100644
--- a/docs/architecture/key-files/commands-6.md
+++ b/docs/architecture/key-files/commands-6.md
@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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 `resumeFilter`s 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`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); 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); 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`, `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.
+- `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); 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`, `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.
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index b690c1d466..eb8fe8e613 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -9,14 +9,14 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
[Core Persistence](core-persistence.md) and [Managed sync and persistence stalls](persistence-stalls.md); `sync-status.ts` and
`sync-fault-class.ts` stay in [Core Services (2/3)](core-services-2.md).
-- `src/core/persistence/sync-failures.ts` — durable managed cursor/receipt diagnostics are the authority; JSONL is a compatibility mirror keyed by cursor and source/path. Failure observations deduplicate terminal receipts, retaining structured codes and attempts; success clears only its matching cursor. A failure records the cursor-selecting `syncOptions` and `processingOptions` of its run (falling back to its cursor's when read), and every local hint (the thrown failure line, the blocked report, the terminal write diagnostic and local doctor) renders the exact retry through `managedSyncRetryCommand` → `checkpointRetryCommand`; a failure recorded before options were kept says so instead of guessing. `sync --retry-failed` counts only failures of the cursor key its own options select (`managedSyncCursorKey`) and lists the others with the action that settles each (`managed-retry-actions.ts`). Local CLI shows request/run/pinned target details, while remote doctor returns source-scoped aggregates without paths, raw messages or receipt IDs. Missing durable state warns rather than certifying health. Failed receipts cannot be acknowledged, auto-skipped or rewritten; explicit idle ordinary-source retry creates fresh admission, while approved company manifests remain pinned. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/e2e/managed-sync-failures.test.ts`. #6402: an observation moves `updated_at`; a new target commit restarts `first_seen`/`attempts`; an `invalid_params` resume refusal is not recorded. #6288: after a managed sync succeeds, `clearSettledManagedSyncFailures` removes the source's rows under other cursor keys (a `--full` run's) whose cursor is done or gone and whose file the imported commit settles; `gbrain sync --source ID --acknowledge-managed REQUEST_ID_OR_PATH` (host CLI) removes only such rows, refusing others `managed_failure_unsettled` (`sync-managed-stale-failures.test.ts`). Wave 16 (#6513 comments): a failure recorded from a receipt carries `write_error_detail`, the receipt's `publicFailureDetail` projection (origin, sqlstate, raiser, table, the closed `reason`; never message text), `readManagedSyncFailures` re-reads it from the pending receipt's `error_detail`, and `formatManagedSyncFailure` appends ` raiser= table= reason=` (`publicationDetailText`, identifiers only), so the ledger mirror, doctor and the blocked report name the refusing trigger; `sync status --json` surfaces it as `last_error.write_error_detail` with `last_error.detail` = the reason (`sync-status.ts`).
+- `src/core/persistence/sync-failures.ts` — durable managed cursor/receipt diagnostics are the authority; JSONL is a compatibility mirror keyed by cursor and source/path. Failure observations deduplicate terminal receipts, retaining structured codes and attempts; success clears only its matching cursor. A failure records the cursor-selecting `syncOptions` and `processingOptions` of its run (falling back to its cursor's when read), and every local hint (the thrown failure line, the blocked report, the terminal write diagnostic and local doctor) renders the exact retry through `managedSyncRetryCommand` → `checkpointRetryCommand`; a failure recorded before options were kept says so instead of guessing. `sync --retry-failed` counts only failures of the cursor key its own options select (`managedSyncCursorKey`) and lists the others with the action that settles each (`managed-retry-actions.ts`). #6712 PR 3 (L7): `--retry-failed` is a deprecated alias of the plain sync, which retries a recorded failure by itself; a failure records the `gbrain_version` that recorded it, so an unchanged content refusal the same version recorded replays without a new request until the file or the version changes. Local CLI shows request/run/pinned target details, while remote doctor returns source-scoped aggregates without paths, raw messages or receipt IDs. Missing durable state warns rather than certifying health. Failed receipts cannot be acknowledged, auto-skipped or rewritten; explicit idle ordinary-source retry creates fresh admission, while approved company manifests remain pinned. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/e2e/managed-sync-failures.test.ts`. #6402: an observation moves `updated_at`; a new target commit restarts `first_seen`/`attempts`; an `invalid_params` resume refusal is not recorded. #6288: after a managed sync succeeds, `clearSettledManagedSyncFailures` removes the source's rows under other cursor keys (a `--full` run's) whose cursor is done or gone and whose file the imported commit settles; `gbrain sync --source ID --acknowledge-managed REQUEST_ID_OR_PATH` (host CLI) removes only such rows, refusing others `managed_failure_unsettled` (`sync-managed-stale-failures.test.ts`). Wave 16 (#6513 comments): a failure recorded from a receipt carries `write_error_detail`, the receipt's `publicFailureDetail` projection (origin, sqlstate, raiser, table, the closed `reason`; never message text), `readManagedSyncFailures` re-reads it from the pending receipt's `error_detail`, and `formatManagedSyncFailure` appends ` raiser= table= reason=` (`publicationDetailText`, identifiers only), so the ledger mirror, doctor and the blocked report name the refusing trigger; `sync status --json` surfaces it as `last_error.write_error_detail` with `last_error.detail` = the reason (`sync-status.ts`).
-- `src/core/persistence/managed-sync-orphans.ts` + `src/core/repair/managed-sync-orphans.ts` — `gbrain repair managed-sync-orphans --source <id>` (#5459), explicit-only and preview-bound (approved set, `preview_changed` on drift). `classifyManagedSyncOrphans` (read-only; doctor `sync_failures` names the repair when it finds any) takes the source's managed-sync bookkeeping and classes each row `no_cursor` (a failure row with no cursor to resume), `principal_unadoptable` (an unfinished cursor recorded by a principal that is no longer an active local writer, by join on the recorded principal), `superseded` (a pre-options cursor a later run replaced), `incarnation_retired` (#6518: an unfinished cursor or a failure row recorded under a source incarnation the source no longer has, joined on the source id alone, archived sources excluded, a live pending request still retaining it) or `mirror_only` (#6518: a local ledger row with a `managed_cursor_key` and no durable failure row under that key; `mirrorOnlyManagedFailures`, which throws on a failed durable read rather than naming every mirror), and keeps `pending_request_live` and `resumable` rows untouched. `retireManagedSyncOrphan` retires one row atomically: an `incarnation_retired` cursor needs the source still active under another incarnation at apply time and skips the live-writer veto (no retired key is resumable); a `mirror_row` deletes nothing durable and prunes the ledger row only when the durable read, repeated at apply, still finds none. `pruneMirrorOnlyManagedFailures` is the successful-sync path (`clearSettledManagedSyncFailures`). Doctor `sync_failures` classifies whenever the brain is reachable, so the diagnostic is reachable with no current-incarnation failure visible, and reports a failed classification as unknown. `sources set-strategy` points at it when an unfinished run blocks a strategy change. Pinned by `test/repair-managed-sync-orphans.test.ts` and `test/managed-sync-orphans-incarnation-6518.test.ts` (both engines); `test/repair-explicit-only.test.ts` pins its place last in `REPAIR_KINDS`.
+- `src/core/persistence/managed-sync-orphans.ts` + `src/core/repair/managed-sync-orphans.ts` — `gbrain repair managed-sync-orphans --source <id>` (#5459), explicit-only and preview-bound (approved set, `preview_changed` on drift). `classifyManagedSyncOrphans` (read-only; doctor `sync_failures` names the repair when it finds any) takes the source's managed-sync bookkeeping and classes each row `no_cursor` (a failure row with no cursor to resume), `principal_unadoptable` (an unfinished cursor recorded by a principal that is no longer an active local writer, by join on the recorded principal), `superseded` (a pre-options cursor a later run replaced), `incarnation_retired` (#6518: an unfinished cursor or a failure row recorded under a source incarnation the source no longer has, joined on the source id alone, archived sources excluded, a live pending request still retaining it) or `mirror_only` (#6518: a local ledger row with a `managed_cursor_key` and no durable failure row under that key; `mirrorOnlyManagedFailures`, which throws on a failed durable read rather than naming every mirror), and keeps `pending_request_live` and `resumable` rows untouched. `retireManagedSyncOrphan` retires one row atomically: an `incarnation_retired` cursor needs the source still active under another incarnation at apply time and skips the live-writer veto (no retired key is resumable); a `mirror_row` deletes nothing durable and prunes the ledger row only when the durable read, repeated at apply, still finds none. `pruneMirrorOnlyManagedFailures` is the successful-sync path (`clearSettledManagedSyncFailures`). Doctor `sync_failures` classifies whenever the brain is reachable, so the diagnostic is reachable with no current-incarnation failure visible, and reports a failed classification as unknown. `sources set-strategy` points at it when an unfinished run blocks a strategy change. Pinned by `test/repair-managed-sync-orphans.test.ts` and `test/managed-sync-orphans-incarnation-6518.test.ts` (both engines); `test/repair-explicit-only.test.ts` pins its place last in `REPAIR_KINDS`. #6712 PR 3 (L7): `slug_mode_refused` is an unfinished cursor whose every page committed and whose checkpoint was refused `slug_root_mode_mismatch` while the source still pins the other mode (`slugModeRefusedSql`, bound to the run and request at apply); no sync rediscovers it, so retiring it is how a person keeps the pin, and its slice record is cleared like `checkpoint_moved`'s.
- `src/core/persistence/sync-cursor-key.ts` — #6712 PR 1: one managed cursor per source. `managedCursorKey` is a digest of the source incarnation and, for a company approval only, the company; writer principal, authority and options no longer select a cursor. `legacyManagedCursorKey` reproduces the pre-0.60.255.0 key (read-only). `resolveManagedCursor` is the one boundary that picks a run's key and folds older keys in crash-safely under the drain lease: the canonical unfinished cursor wins, else the newest older-key unfinished cursor is adopted and finished in place under its own key; every other older cursor has its queued requests cancelled and is retired through `retireManagedSyncOrphan` (reason `superseded_by_adoption`, fenced by `assertDrainLease`). A cursor with a running, recovering or publishing request or a recovery row is retained and the pass waits for that request (`writer_pending`) before it drains anything. A company brain's finished old-key cursors are kept. Pinned by `test/persistence-sync-cursor-adoption.test.ts` and `test/persistence-sync-cursor-strategy-6696.test.ts`.
- `src/core/persistence/sync-lease.ts` — #6712 PR 1: the drain lease, one managed drainer per source. `withDrainLease` takes the source's sync lock (`syncLockId`) with a 2-minute TTL renewed every 20 s, so a dead holder's lease lapses inside one cron tick; it is reentrant for the holder (nested passes and the in-process lanes reuse it). The holder record (`managed-sync-lease` checkpoint: kind, id, version, start) plus the lock row give `readDrainHolder` (host, pid, heartbeat, `progress`: commits, last commit, last cursor save). A non-job holder also writes a beacon row in the `gbrain-drain-lease` minion queue (application authority, `max_stalled` 0, renewed with the lease, deleted on release) so an older binary's `liveSyncJob` backs off; downgrades are quiescent (stop serve and crons first). `assertDrainLease` is the fence inside every transaction that admits work, settles or holds an entry, folds a cursor in or swaps the cursor. Following callers (the CLI, a CLI run delegated to a serve) wait for a live holder within their budget (`followStopAt`) and take over when it releases; out of budget, or after losing the lease, they return `leaseHeldResult` (`resumable`, `sync_drain_lease_held`, `next.retry_after_ms` 60 s, `safe_to_loop`); a holder with no progress for `HOLDER_STALL_MS` (5 min) returns `leaseStalledResult` (`blocked`, `drain_stalled`, cause `no_progress`, `stall.lease_holder`). Jobs and the cycle get `SyncLockBusyError` and skip. Pinned by `test/persistence-sync-lease.test.ts`.
- `src/core/wire-skew.ts` — #6712 PR 1: the one record of wire-skew windows, each a version floor plus a calendar date (`WIRE_SKEW_WINDOWS.explicitProcessing`: floor 0.60.255.0, accepted and ignored until 2026-11-14). The delegation and admin wires read the field name from here, so removing the window is one edit. #6712 PR 2: each window names the hand-offs that accept it (`wires`) and its shape (`accepts`); `retiredWireFields` / `retiredWireNotice` serve both validators. `CONFIG_ROLLBACK_WINDOWS` records the rollback config keys' windows (honored until a date, from a version floor, with the notice that named them).
-- `src/core/sync-flags.ts` — #6712 PR 2: `SYNC_FLAGS`, every `gbrain sync` flag once, with its route (`forward` / `client` / `refuse`) on the serve and PGLite owner hand-offs; `syncFlagsRouted` and `syncWireFields` derive the ladder's, the IPC validator's and the owner lane's allowlists. A flag the argv parsers read must be listed (`test/sync-flag-table-6712.test.ts`).
+- `src/core/sync-flags.ts` — #6712 PR 2: `SYNC_FLAGS`, every `gbrain sync` flag once, with its route (`forward` / `client` / `refuse`) on the serve and PGLite owner hand-offs; `syncFlagsRouted` and `syncWireFields` derive the ladder's, the IPC validator's and the owner lane's allowlists. A flag the argv parsers read must be listed (`test/sync-flag-table-6712.test.ts`). #6712 PR 3 (L7): `managed: true` marks the ten flags `gbrain sync --help` lists under "Managed brains" (`MANAGED_HELP_FLAGS`, table order; `test/sync-managed-help-l7-6712.test.ts` pins the section and runs doctor's cron recipe through the managed flag validator).
- `src/core/sync-config-keys.ts` + `src/commands/doctor/checks/sync-config-keys.ts` — #6712 PR 2: the `sync.*` keys in three kinds: `SYNC_TUNABLE_KEYS`, the rollback keys (windows in `wire-skew.ts`) and `RETIRED_SYNC_KEYS` with their `GBRAIN_SYNC_*` replacements (`retiredSyncSetting` reads one). `effectiveSyncKey` is `config get`'s value-in-effect and origin for a retired or rollback key (its resolvers mirror the readers: `resolveBulkSettings`, `waiverBatchEnabled`, `isFederatedV2Enabled`, the write switches, `planJobDrain`); `syncKeySetNotice` is `config set`'s warning (a retired key writes nothing). Doctor `sync_config_keys` reports a stored retired key as unapplied. Pinned by `test/sync-config-keys-6712.test.ts` and `test/error-registry-retired.test.ts`.
- `src/core/persistence/managed-sync-flags.ts` — `managedForbiddenFlag` / `managedSyncFlagRefusal`: the `managed_sync_flag_refused` refusal for `--skip-failed` / `--include-gitignored` on a managed source (#6696), raised at `gbrain sync` parse, in `maybeDelegateManagedSyncToServe` before the socket, and by `resolveManagedSyncContext`.
@@ -30,7 +30,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/sync-slug-mode.ts` — #6694: the checkpoint's slug-root mode against the source's pinned `slug_root_mode`. `emptySyncScope` (source root is the repository root, both realpathed) lets `sync-prepare.ts`'s checkpoint `UPDATE` accept either pin and keep the pinned one; at a subdirectory a differing pin is diagnosed by `pinnedSlugModeMismatch` after the guarded `UPDATE` matched nothing and refused `slug_root_mode_mismatch` (cause and the person's two choices from `slugModeMismatchCause`); anything else stays `revision_conflict` (`CHECKPOINT_MOVED_MESSAGE`). `slugModeCheckpointRevivable` is the second revival predicate of `sync-run.ts` `reviveCheckpoint`: a checkpoint refused `slug_root_mode_mismatch`, or an older release's moved-checkpoint `revision_conflict`, is revived when `last_commit` still equals the run's `from` and the pin is unset, equal to the run's mode or the scope is empty; `retryFailedStart` does not consult it, so `--retry-failed` keeps its rediscovery. Test: `test/sync-slug-root-mode-6694.test.ts` (both engines).
- `src/core/persistence/sync-cursor-moves.ts` — #6712 (L2, one page, one fate): the managed-sync cursor's pure transitions, peeled out of `sync-run.ts`; each returns the next cursor and writes nothing (sync-run.ts saves it with one compare-and-swap). `advanceHeld`/`settledPast` pass an entry without a commit (held, waived via `waivedCursor`, an idempotent deletion via `deletionSettled`) and add its index to the settled ranges the checkpoint skips; a deferred entry (`Cursor.deferred`, a `source_changed` file retried after the manifest end) leaves the deferred list instead of moving the index. `promoteWindow` makes the window's first group the cursor's group once the cursor reaches it, so requests admitted after a failed or held entry are read by their own receipts, never frozen again; `committedPast` does the same after a commit. `withHeldKeys` records a held entry's page keys (`dependencyKeys`) so a later entry of the run that shares one is held behind it (`blocked_on`).
-- `src/core/persistence/sync-stop-class.ts` — #6712 (L2; #6565): how the settle path in `sync-run.ts` classifies a page request that ended without committing. `receiptClass` reads the terminal classifier: `transport` (a dropped connection or a retryable refusal, re-frozen in place), `page` (held, deferred or blocked under the hold policy) or `systemic` (the run stops with the classifier's action). `resumableStop` is a systemic stop the fault table retries (an unrecognised P0001 or a 55000 surfacing as `storage_error`); `stopRecorded` says an earlier invocation already stopped this run (its failure ledger row carries the run id), so the next plain sync re-freezes every page that refusal failed, bounded by `STOPS_PER_ENTRY`.
+- `src/core/persistence/sync-stop-class.ts` — #6712 (L2; #6565): how the settle path in `sync-run.ts` classifies a page request that ended without committing. `receiptClass` reads the terminal classifier: `transport` (a dropped connection or a retryable refusal, re-frozen in place), `page` (held, deferred or blocked under the hold policy) or `systemic` (the run stops with the classifier's action). `resumableStop` is a systemic stop the fault table retries (an unrecognised P0001 or a 55000 surfacing as `storage_error`); `stopRecorded` says an earlier invocation already stopped this run (its failure ledger row carries the run id), so the next plain sync re-freezes every page that refusal failed, bounded by `STOPS_PER_ENTRY`. #6712 PR 3 (L7): `recordedStop` also returns the row's `gbrain_version`. `retryRecordedFailure` in `sync-run.ts` (what `--retry-failed`, now its deprecated alias, did on request) retries every recorded failure on the next plain sync, except a refusal nothing changed since the same version recorded it (`replaysUnchangedRefusal`: a content refusal while the file has its frozen bytes; a `source_changed` pinned import while HEAD is the run's target and the file was not written since), a slug-mode refusal and a checkpoint whose source's `last_commit` moved (#6834), which wait for a changed file or `gbrain repair managed-sync-orphans`.
- `src/core/persistence/sync-knock-on.ts` — #6643, shrunk by #6712 (one page, one fate): no producer is left. It keeps the legacy predicate over receipts older builds wrote (`error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }`, or the pre-#6643 producers' exact messages, never an operator cancel): `isSyncKnockOn`/`syncKnockOnSql` (one predicate, never NULL) feed the terminal classifier, which renders such a receipt superseded, and `sync-run.ts` `refreezeInPlace`, which re-freezes the entry when a resumed cursor meets one (bounded by `STOPS_PER_ENTRY`, no config key). `cursorFenceCause` reads the two live causes of "cursor changed" (`run_replaced`, `outside_fence`; an older `window_dropped` still parses). `checkpoint-validation.ts` clause 3 skips converted receipts and the cursor's settled index ranges only; #6712 removed the knock-on exemption. `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`, each with `knock_on`).
- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.
- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index bd8c1f037b..0fea678eab 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -592,7 +592,7 @@ through `gbrain sources refresh <source>`, the drained worktree-wide fast-forwar
which runs inside a resident PGLite owner such as `gbrain serve` when one holds the brain;
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. Resume
+the plain `gbrain sync --no-pull` with the same source and options (`--retry-failed` is a deprecated alias of it on a managed brain). Resume
autopilot with `gbrain autopilot resume` and re-enable the hooks you stopped.
When activation refuses with `writer_not_quiesced` because of queued work, the
@@ -638,7 +638,7 @@ runbook above.
3. Dry run: `gbrain sources writer deactivate --dry-run`. It lists each blocker
with its exit and what would change, and changes nothing. Blocker exits:
`gbrain cancel-write-request <request_id>` for a queued write,
- `gbrain sync --source <id> --no-pull --retry-failed` for one that needs
+ `gbrain sync --source <id> --no-pull` for one that needs
recovery, `gbrain repair embedding-effects --source <id>` for a stuck
embedding effect, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`
for a failed Git or withdrawal effect, and `gbrain sources writer unlock` for
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 9b0345cef4..faeeb47e8e 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -531,11 +531,11 @@ If its recorded file bytes no longer match, preserve the file and receipt and
resolve the conflict on the owner; do not delete recovery records.
If a sync cursor was already invalidated, keep its failure visible until the
-owner has checked the canonical content. Then explicitly re-enumerate with the
-same source and processing options:
+owner has checked the canonical content. Then rerun the plain sync with the
+same source and processing options; it retries what the previous run recorded:
```bash
-gbrain sync --source example-source --no-pull --no-embed --no-extract --retry-failed
+gbrain sync --source example-source --no-pull --no-embed --no-extract
```
Use `--no-embed` and `--no-extract` here only if they were the original sync
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 1e54d4b2d6..9959017654 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2060,7 +2060,7 @@ More: [docs/guides/write-refusals.md#managed_pull_skipped](../../docs/guides/wri
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A managed source refuses --skip-failed and --include-gitignored: managed sync keeps every failed-receipt and ignored-file guard, so the run was refused before anything ran. | --skip-failed would acknowledge a failed receipt instead of retrying it, and --include-gitignored would import files Git ignores; neither has a managed meaning. `detail` names the flag. | Rerun the same gbrain sync command without the named flag; fix a failed file and retry it with --retry-failed, or commit an ignored file to sync it. Run: gbrain sources status --json | agent | `gbrain sources status --json` | 1 | no |
+| A managed source refuses --skip-failed and --include-gitignored: managed sync keeps every failed-receipt and ignored-file guard, so the run was refused before anything ran. | --skip-failed would acknowledge a failed receipt instead of retrying it, and --include-gitignored would import files Git ignores; neither has a managed meaning. `detail` names the flag. | Rerun the same gbrain sync command without the named flag; fix a failed file and the plain sync retries it, or commit an ignored file to sync it. Run: gbrain sources status --json | agent | `gbrain sources status --json` | 1 | no |
More: [docs/guides/write-refusals.md#managed_sync_flag_refused](../../docs/guides/write-refusals.md#managed_sync_flag_refused)
@@ -2378,7 +2378,7 @@ More: [docs/guides/windowed-reads.md#page_too_large_for_inline](../../docs/guide
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A file whose exact bytes imported before is now refused by gbrain's frontmatter reader. | The same bytes imported under an earlier gbrain version, so only gbrain changed; with `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs, such a file is held and the rest of the sync continues. | Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again with --retry-failed. | host_admin | `gbrain doctor --json` | 1 | no |
+| A file whose exact bytes imported before is now refused by gbrain's frontmatter reader. | The same bytes imported under an earlier gbrain version, so only gbrain changed; with `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs, such a file is held and the rest of the sync continues. | Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again. | host_admin | `gbrain doctor --json` | 1 | no |
### pasted_wrong_url
@@ -3228,7 +3228,7 @@ More: [docs/guides/write-refusals.md#slug_page_mismatch](../../docs/guides/write
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A managed sync of a subdirectory source ran under one slug-root mode while the source pins the other (sources.config.slug_root_mode), so its checkpoint did not advance. | At a subdirectory the two modes give different slugs (git-root keeps the subdirectory prefix, source-root does not), and the pin exists so a later sync never re-namespaces the source; the pages this run wrote already carry its mode. The pin changed after the run was discovered. A source rooted at its repository root never gets this code: both modes give it identical slugs, and its checkpoint keeps the pin it has. Older releases reported this refusal as revision_conflict. | Ask the user which mode the source keeps. To keep the mode the run used, set sources.config.slug_root_mode back to it and run gbrain sync --no-pull --source <id>; the refused checkpoint is retried by itself. To keep the new pin, run gbrain sync --no-pull --source <id> --retry-failed, which discovers the source again under it; the pages the refused run wrote keep their old slugs beside the new ones. Run: gbrain sync status --source '{source_id}' --json | user | `repeat the read that failed` | 1 | no |
+| A managed sync of a subdirectory source ran under one slug-root mode while the source pins the other (sources.config.slug_root_mode), so its checkpoint did not advance. | At a subdirectory the two modes give different slugs (git-root keeps the subdirectory prefix, source-root does not), and the pin exists so a later sync never re-namespaces the source; the pages this run wrote already carry its mode. The pin changed after the run was discovered. A source rooted at its repository root never gets this code: both modes give it identical slugs, and its checkpoint keeps the pin it has. Older releases reported this refusal as revision_conflict. | Ask the user which mode the source keeps. To keep the mode the run used, set sources.config.slug_root_mode back to it and run gbrain sync --no-pull --source <id>; the refused checkpoint is retried by itself. To keep the new pin, preview gbrain repair managed-sync-orphans --source <id> (it lists the refused cursor as slug_mode_refused), apply it with the hash it prints, and run gbrain sync --no-pull --source <id>, which discovers the source again under the pin; the pages the refused run wrote keep their old slugs beside the new ones. Run: gbrain sync status --source '{source_id}' --json | user | `repeat the read that failed` | 1 | no |
### source_binding_required
@@ -3352,7 +3352,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish. | The replacing run (a --retry-failed rediscovery or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict. | Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source. | agent | `repeat the read that failed` | 1 | no |
+| Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish. | The replacing run (a rediscovery that retried a recorded failure, or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict. | Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source. | agent | `repeat the read that failed` | 1 | no |
### sync_drain_lease_held
@@ -3414,7 +3414,7 @@ Reasons: `content_directory`.
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug. | The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed. | host_admin | `gbrain doctor --json` | 1 | no |
+| Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug. | The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull. | host_admin | `gbrain doctor --json` | 1 | no |
### tail_exposure_approval
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 2a161191e7..059ff9fae7 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -451,14 +451,17 @@ vars — incident-time escape hatches, not everyday knobs.
sync only, `gbrain sync --skip-failed` acknowledges a known-bad set.
**Managed sync never acknowledges or auto-skips failed cursors.** Its
durable failed receipt remains immutable on ordinary replay. Correct the
- cause, inspect local `gbrain doctor`, then explicitly retry an idle
- ordinary-source cursor with the same full/working-tree/filter options:
+ cause, inspect local `gbrain doctor`, then rerun the plain
+ sync for that source with the same full/working-tree/filter options; it
+ retries what the previous invocation recorded:
```bash
- gbrain sync --source <source-id> --no-pull --retry-failed
+ gbrain sync --source <source-id> --no-pull
```
- This retries with fresh admission; do not add `--skip-failed`. A successful
+ This retries with fresh admission; do not add `--skip-failed`
+ (`--retry-failed` is a deprecated alias of the plain sync on a managed
+ brain). A successful
full run does not clear a separate failed incremental cursor. Doctor reports
the remaining run; CLI blocked results exit nonzero and local diagnostics
include source/path/code/request/run/target. Counts are cumulative for the
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index fcc564d771..f7595c6f22 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -390,7 +390,7 @@ rewrites it on the next import. No command is needed.
files, for example `~/vault/notes/people/alice-example.md` and
`~/vault/notes/notes/people/alice-example.md`, sync refuses instead of
guessing. Rename or move one of the two files, commit, then run
-`gbrain sync --source vault-notes --no-pull --retry-failed`. The other
+`gbrain sync --source vault-notes --no-pull`. The other
refusal reasons are listed in [write refusal reasons](write-refusals.md).
## Citation format for agents
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 31004ce4d8..a06b8f8e73 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -230,7 +230,7 @@ and is not retried ahead of other writes.
valid, a warning with progress while one is still building (leave it
running), and a warning naming `gbrain repair request-indexes --apply` when one
is missing or INVALID. After the rebuild, run the retry the refusal printed
-(`gbrain sync --source <source> --no-pull --retry-failed` plus the saved
+(`gbrain sync --source <source> --no-pull` plus the saved
processing flags).
<a id="request-growth"></a>
@@ -478,7 +478,7 @@ request uses it.
<a id="managed-sync-orphans"></a>
**Say to your agent:** *"doctor has reported the same two sync failures for a
-week, every sync ends up to date, and `--retry-failed` changes nothing."*
+week, every sync ends up to date, and rerunning the sync changes nothing."*
A managed sync run keeps its cursor under a key derived from the source
incarnation, the writer principal and the sync options. A cursor written under
@@ -487,7 +487,7 @@ principal before the local-CLI cutover, a revoked local writer), can never be
resumed: the live writer reads only its own key. Doctor still reads every
unfinished cursor, so `sync_failures` reports `sync_incomplete` forever, and a
`managed-sync-failure` row whose key has no cursor at all is only cleared by a
-success under that same key, which never comes. `--retry-failed` follows the
+success under that same key, which never comes. A plain sync follows the
live cursor; `--skip-failed` is refused on a managed source. Nothing an
operator can run clears either.
@@ -508,14 +508,15 @@ Classes in the preview:
| `no_cursor` | a `managed-sync-failure` row with no `managed-sync` cursor under its key | cleared only by a success under the same key |
| `principal_unadoptable` | an unfinished cursor recorded by a principal that is not an active local writer | the live writer never reads that key, and the pending request is invisible to it |
| `superseded` | an unfinished cursor from before sync options were recorded, with a later completed run for the same source and incarnation | its exact options are unknown, so no command resumes it |
-| `incarnation_retired` | an unfinished cursor, or a failure row, recorded under a source incarnation the source no longer has (it was re-pointed at a new checkout, or removed and added again) | the cursor key digests the incarnation, so no current sync selects it, and every incarnation-joined reader (doctor's durable read, `--retry-failed`, `--acknowledge-managed`) drops it; only the local ledger mirror still shows it. `gbrain sync status` reports it as `cursor: null` with `last_error.code: cursor_incarnation_retired` |
-| `checkpoint_moved` | an unfinished cursor whose pages all committed and whose checkpoint was refused `revision_conflict` "The source checkpoint changed during this sync." because `sources.last_commit` moved to a commit that is neither the run's start nor its target (another run, or an older gbrain sharing the database, checkpointed the source elsewhere) | the checkpoint's compare-and-swap can never succeed, so every plain sync resumes the cursor into the same refusal; its slug `__managed_sync_checkpoint__` is bookkeeping, not a page, so there is nothing to read. After the apply the next sync discovers from the commit the source records. A cursor whose source already stands at its target is not listed: the next plain sync finishes it. The apply keeps the cursor when the rule no longer holds |
+| `incarnation_retired` | an unfinished cursor, or a failure row, recorded under a source incarnation the source no longer has (it was re-pointed at a new checkout, or removed and added again) | the cursor key digests the incarnation, so no current sync selects it, and every incarnation-joined reader (doctor's durable read, the sync retry, `--acknowledge-managed`) drops it; only the local ledger mirror still shows it. `gbrain sync status` reports it as `cursor: null` with `last_error.code: cursor_incarnation_retired` |
+| `checkpoint_moved` | an unfinished cursor whose pages all committed and whose checkpoint was refused `revision_conflict` "The source checkpoint changed during this sync." because `sources.last_commit` moved to a commit that is neither the run's start nor its target (another run, or an older gbrain sharing the database, checkpointed the source elsewhere) | the checkpoint's compare-and-swap can never succeed, so every plain sync resumes the cursor into the same refusal; its slug `__managed_sync_checkpoint__` is bookkeeping, not a page, so there is nothing to read. After the apply the next sync discovers from the commit the source records. No sync retries it, because rediscovering a path-sliced run would move `last_commit` backward; the orphan repair is the only exit. A cursor whose source already stands at its target is not listed: the next plain sync finishes it. The apply keeps the cursor when the rule no longer holds |
+| `slug_mode_refused` | an unfinished cursor whose checkpoint was refused `slug_root_mode_mismatch` (a source in a subdirectory of its repository pins one `slug_root_mode`, the run used the other) while the source keeps the other pin | the two modes give different slugs, so the checkpoint can never publish under the kept pin. Preview, then `--apply --expect <hash>`: the apply retires the cursor and the next sync discovers the source again under the kept pin. Setting the pin back to the run's mode instead lets the next plain sync retry the checkpoint by itself. No sync retries this one without a person's choice |
| `mirror_only` | a row of the local ledger (`~/.gbrain/sync-failures.jsonl`) carrying a `managed_cursor_key` with no durable failure row under that key in any incarnation | the mirror is pruned only after a durable delete, so one whose durable row is already gone keeps `gbrain doctor --fast` warning. The apply removes the ledger row after reading the durable rows again; a successful sync of the source prunes its own mirror-only rows too |
Kept and counted, never retired: a cursor whose pending request is still
queued, running or recovering (`pending_request_live`), and a cursor the live
writer can still resume with its recorded options (`resumable`; doctor prints
-the exact `gbrain sync ... --retry-failed` command). An `incarnation_retired`
+the exact `gbrain sync ...` command). An `incarnation_retired`
cursor is retired even when its recording principal is the live local writer
with recorded options: that veto is for a cursor the writer could still
resume, which no retired key can be. Rows on an archived source are never
@@ -1104,7 +1105,7 @@ candidate one class:
| `superseded` | A later write or delete of the page committed or is pending; for `put_page`, also a later failed `put_page` (newer content) or a page changed since the caller read it. | Kept; re-issue by hand if still wanted. |
| `unpinned_target` | A `remember` saved unattributed; replaying would infer its subject again and could pick another page. | Kept. Re-issue it with an explicit `entity` if it is still wanted. |
| `file_database_drift` | Its last replay hit `source_changed` and the file still differs from the database. | Kept until the file matches again (a reconcile that writes only the file counts) or the page changes; reconcile it first. |
-| `producer_owned` | gbrain produced it (sync or file import, reconcile, relink, maintenance page, job). | Kept. The preview prints the command that produces it again from current content (sync: `gbrain sync --source <id> --no-pull --retry-failed`). |
+| `producer_owned` | gbrain produced it (sync or file import, reconcile, relink, maintenance page, job). | Kept. The preview prints the command that produces it again from current content (sync: `gbrain sync --source <id> --no-pull`). |
The apply replays exactly the previewed set. Each write is classified again
and its original caller's authority is checked again first: a write that
@@ -2082,8 +2083,8 @@ walk me through it before changing anything."*
| Symptom or error text | Preview | Apply | Verify | Who acts | Consent |
| --- | --- | --- | --- | --- | --- |
| Sync `BLOCKED` on one file (`Invalid YAML frontmatter`, a frontmatter slug conflict, `Content too large`); after upgrading, sync prints `Held <path>: …`; doctor `git_held_files` or `frontmatter_repairable` warns; the upgrade banner prints `frontmatter_holds:` | `gbrain sources status <source>`, then `gbrain repair frontmatter --source <source>` (add `--include-ambiguous` for interpretations) | nothing to unblock: the next sync converts the blocked request in place (`gbrain sync --source <source> --no-pull` does it now); for the backlog, the printed `gbrain repair frontmatter … --apply --expect <hash> --yes` ([held files](#held-files)) | `gbrain doctor --only git_held_files,frontmatter_repairable --json` (both ok) | brain host; the repair apply after the user agrees | `destructive` (repair apply rewrites the previewed lines) |
-| Tag, timeline or take writes fail with `writer_coordinator_required` or `storage_error: Publication failed (P0001)` on a managed brain; sync ends `PARTIAL` at a tagged page | `gbrain doctor --json` (`schema_version` is 197 or later) | the original `gbrain sync --source <source> … --no-pull --retry-failed --json`, then `gbrain extract --stale --source-id <source>` and `gbrain extract timeline --source db --source-id <source>`, then `gbrain facts relink --source <source> --dry-run` (paid tier only after the user agrees), then `gbrain repair failed-writes --source <source>` and, after the user agrees, its printed `--apply --expect <hash>` | `gbrain sources status` shows the new `last_commit`; a second `gbrain extract timeline --source db` run adds no rows; a second `gbrain repair failed-writes` preview lists nothing to replay | brain host; the replay apply after the user agrees | paid (relink tier), destructive (replay apply) |
-| Sync `BLOCKED` with `checkpoint_validation_timeout` | `gbrain doctor` (`persistence_request_indexes`) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <source> --no-pull --retry-failed …` | `gbrain doctor --only persistence_request_indexes --json` reports `ok`; `gbrain sources status` shows the new `last_commit` | brain host | none |
+| Tag, timeline or take writes fail with `writer_coordinator_required` or `storage_error: Publication failed (P0001)` on a managed brain; sync ends `PARTIAL` at a tagged page | `gbrain doctor --json` (`schema_version` is 197 or later) | the original `gbrain sync --source <source> … --no-pull --json`, then `gbrain extract --stale --source-id <source>` and `gbrain extract timeline --source db --source-id <source>`, then `gbrain facts relink --source <source> --dry-run` (paid tier only after the user agrees), then `gbrain repair failed-writes --source <source>` and, after the user agrees, its printed `--apply --expect <hash>` | `gbrain sources status` shows the new `last_commit`; a second `gbrain extract timeline --source db` run adds no rows; a second `gbrain repair failed-writes` preview lists nothing to replay | brain host; the replay apply after the user agrees | paid (relink tier), destructive (replay apply) |
+| Sync `BLOCKED` with `checkpoint_validation_timeout` | `gbrain doctor` (`persistence_request_indexes`) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <source> --no-pull …` | `gbrain doctor --only persistence_request_indexes --json` reports `ok`; `gbrain sources status` shows the new `last_commit` | brain host | none |
| Doctor `persistence_request_indexes` warns | `gbrain repair request-indexes` | `gbrain repair request-indexes --apply` | `gbrain doctor --only persistence_request_indexes --json` | brain host | none |
| Doctor `persistence_request_growth` warns | `gbrain doctor --json` | the printed `gbrain config set persistence.limits.<limit> <value>` | `gbrain doctor --only persistence_request_growth --json` | brain host | none |
| Working-tree sync prints `legacy file(s) skipped … no contextual retrieval mode` | `gbrain repair contextual-mode` | `gbrain repair contextual-mode --apply` | the next `gbrain sync --working-tree` no longer prints the line | brain host, after the user agrees | none |
@@ -2211,7 +2212,7 @@ Then recover what doctor names, in this order (skip a step whose check is ok):
`orphan-bindings` and `embedding-effects` also run under `gbrain repair --all`
and `gbrain doctor --remediate --include-repairs`; `embedding-effects` is paid
work when it queues a retry. Retry commands: `gbrain sources writer retry-effects <source> --request-id <id>`
-(one failed or parked effect), `gbrain sync --source <id> --no-pull --retry-failed`
+(one failed or parked effect), `gbrain sync --source <id> --no-pull`
(a failed sync write) and `gbrain repair embedding-effects --source <id> --apply`
(stuck embedding effects, including a used-up retry allowance).
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 8d3d51185d..0e00229d6f 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -54,7 +54,7 @@ moving again; ask me only about the ones gbrain will not decide by itself."*
refuses every repair-class hold instead, as releases before #6377 did.
3. Run that sync. It re-screens the scheduled files, imports each one that now
passes and holds again what still fails; the rest of the source is never
- blocked. With `--retry-failed` a cursor an older release left blocked on a
+ blocked. A cursor an older release left blocked on a
page fault converts in place (same run, no rediscovery).
4. If `needs_human` is true, stop looping and page a person with the slug and
`human_reason` from `status` (`next.user_message` is written for relay).
@@ -174,7 +174,8 @@ earlier one is held. A file that changed after its request was admitted
(`source_changed`) is retried after the manifest's last entry, at most three
times, then held `worktree_dirty`. A transport fault re-freezes the entry in
place; a systemic stop is re-frozen in place by the next plain sync, at most
-three times in a row before the failure stays recorded for `--retry-failed`.
+three times in a row, and once that bound is spent the next plain sync
+resets it and tries again.
A `knock_on` or `knock_on_exhausted` error was written by an older gbrain
(a page cancelled only because another page of its sync did not commit, or
@@ -187,7 +188,7 @@ the extra drain and reports it); an older build's `window_dropped` reads as
a knock-on. A checkpoint refused by a receipt at an index the cursor passed
without a commit is re-assessed on every resume and commits without
rediscovering the manifest; one a receipt still blocks is rediscovered by
-`--retry-failed`.
+the next plain sync.
An unknown code is systemic and human: `gbrain errors <code>` explains it
offline, `gbrain doctor --json` says what the brain thinks.
@@ -223,7 +224,7 @@ it and kept going; the receipt lists the hold (`held`, `held_count`) and
run ([held files](write-refusals.md#held-files-and-content-refusals)).
- `revision_conflict`, `page_identity_changed`, `pinned_git_worktree_conflict`
as a `last_error` come from a run on an older release; this release holds
- them. Rerun with `--retry-failed`: the stopped entry converts in place, the
+ them. Rerun the plain sync: the stopped entry converts in place, the
manifest is not re-frozen. A `revision_conflict` or `cancelled` error with
`detail: knock_on` needs no flag: the next plain sync re-freezes the entry
(act on `root_cause` instead).
@@ -250,8 +251,11 @@ repair: a source in a subdirectory of its repository pins one
Ask the user which mode the source keeps. Restoring the pin to the run's mode
lets the next plain `gbrain sync --no-pull --source <id>` finish (the refused
checkpoint is retried by itself); keeping the new pin takes
-`gbrain sync --no-pull --source <id> --retry-failed`, and the pages the refused
-run wrote keep their old slugs beside the new ones. A source rooted at its
+`gbrain repair managed-sync-orphans --source <id>` (it lists the cursor as
+`slug_mode_refused`; preview, then `--apply --expect <hash>`), after which the
+next sync discovers the source again under the kept pin. No sync retries that
+checkpoint by itself. The pages the refused run wrote keep their old slugs
+beside the new ones. A source rooted at its
repository root never gets this code: both modes give it the same slugs, and
a checkpoint an older release refused there as `revision_conflict` finishes on
the next plain sync.
@@ -260,10 +264,10 @@ the next plain sync.
The frozen manifest always lived in the cursor (`op_checkpoints`, op
`managed-sync`). What threw it away was the failure ledger: every run death
-wrote a row, and `--retry-failed` read the row and rediscovered from index 0
+wrote a row, and the retry read the row and rediscovered from index 0
(eight to twelve minutes of silence on a 14k-entry source). Page faults are
-now holds and connection faults are not recorded, so a relaunch, with or
-without `--retry-failed`, finds the cursor and resumes it. Only a systemic
+now holds and connection faults are not recorded, so a relaunch finds
+the cursor and resumes it. Only a systemic
failure still writes a ledger row.
When HEAD moved past the pinned target while the run drained, the drain takes
@@ -291,7 +295,7 @@ how often a person or an agent had to step in, per UTC day for the last seven
days, so a soak can show that sync keeps moving on its own.
- `interventions`: `sync_non_plain` (a `gbrain sync` with a recovery flag such
- as `--retry-failed`, `--full`, `--break-lock` or `--skip-failed`; the plain
+ as the deprecated `--retry-failed`, `--full`, `--break-lock` or `--skip-failed`; the plain
scheduler flags `--all`, `--no-pull`, `--hard-deadline`, `--no-embed`,
`--no-lanes`, `--no-bulk` and `--json` do not count), `repair_apply` (a
`gbrain repair … --apply` of any kind but file-drift), `unblock_apply`,
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index e52dec1db3..f0a28c200c 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -54,9 +54,9 @@
| `gbrain waiting` lists bank, payment or shipping alerts as people waiting on you | upgrade (#5012: mail with `Precedence: bulk/list/junk`, a `List-Id` or a no-reply `Reply-To` opens no reply-owed loop); for loops opened before the upgrade, `gbrain waiting` prints `gbrain loops drop sender <email> --source <id> --dry-run` per sender; preview, then run it without `--dry-run` (cannot be undone), or `gbrain loops mute sender <email>` for a reversible stop ([open loops](open-loops.md#the-surfaces)) | agent, after the user agrees | none to preview | `gbrain waiting --json` no longer lists the sender |
| [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` |
| [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |
-| [`gbrain sync` refused `managed_sync_flag_refused`](write-refusals.md#managed_sync_flag_refused) | rerun the same command without the flag `detail` names (`--skip-failed` or `--include-gitignored`); fix a failed file and use `--retry-failed`, or commit an ignored file | agent | none | `gbrain sources status --json` |
-| [`--retry-failed` says failures "belong to a run with different sync options"](#retry-other-options) | run the command printed on each line: `resumable (replay …)` or `resumable (fresh discovery …)` reruns under the failed run's options, `safely orphaned` previews `gbrain repair managed-sync-orphans --source <id>` (apply with its hash), `unresolved` names what has to finish first | agent; the repair apply after the user agrees | the repair retires bookkeeping rows only | `gbrain sync status --source <id> --json` |
-| [Managed sync blocked with `checkpoint_validation_timeout`](#checkpoint-validation-timeout) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` |
+| [`gbrain sync` refused `managed_sync_flag_refused`](write-refusals.md#managed_sync_flag_refused) | rerun the same command without the flag `detail` names (`--skip-failed` or `--include-gitignored`); fix a failed file and rerun the plain sync (`--retry-failed` is a deprecated alias), or commit an ignored file | agent | none | `gbrain sources status --json` |
+| [Sync with the deprecated `--retry-failed` alias says failures "belong to a run with different sync options"](#retry-other-options) | run the command printed on each line: `resumable (replay …)` or `resumable (fresh discovery …)` reruns under the failed run's options, `safely orphaned` previews `gbrain repair managed-sync-orphans --source <id>` (apply with its hash), `unresolved` names what has to finish first | agent; the repair apply after the user agrees | the repair retires bookkeeping rows only | `gbrain sync status --source <id> --json` |
+| [Managed sync blocked with `checkpoint_validation_timeout`](#checkpoint-validation-timeout) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` |
| [Doctor warns `persistence_session_timeouts` (`session_timeouts_not_applied`)](#session-timeouts-not-applied) | `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` on the database, or accept it: preparation reads carry their own bound | brain host | none (a role default; `destructive` only in that it changes a server setting) | `gbrain doctor --only persistence_session_timeouts --json` |
| `gbrain init` or `gbrain upgrade` stops with `schema_lock_blocked` naming a pid (or, before #5227, sat in `wait_event_type=Lock` with no output) | let the named session finish, or with the user's agreement end it on the database host: `SELECT pg_terminate_backend(<pid>)`; then rerun the same command ([ENGINES.md](../ENGINES.md#schema-lock-blocked)) | brain host, after the user agrees | `destructive` when it ends another session | the rerun completes; `gbrain doctor --json` shows the schema at head |
| [`queue_capacity`, `persistence_capacity` or `persistence_request_growth`](#write-capacity) | run the printed `gbrain config set persistence.limits.<limit> <value>` | brain host | none | `gbrain doctor --only persistence_capacity,persistence_request_growth --json` |
@@ -104,9 +104,9 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).
-<a id="retry-other-options"></a>**`--retry-failed` lists failures that "belong to a run with different sync options"?** A managed retry resumes only the cursor its own options select; each other failure gets one line with its class and the command that settles it. `resumable (replay …)`: an unfinished run holds it, and the command resumes that run under its recorded options. `resumable (fresh discovery, not a replay …)`: no run holds it any more; the command starts a new run from HEAD under the failed run's options, which clears the failure when it completes. For a failure recorded before runs kept their options, the options are recovered only when an option set reproduces its cursor key exactly. `safely orphaned`: nothing current can resume it; preview `gbrain repair managed-sync-orphans --source <id>` and apply with the hash it prints. `unresolved`: its options were never recorded and nothing selects it; the line says what has to finish first (a request still in flight, or a current run whose completion lets the orphan repair retire it).
+<a id="retry-other-options"></a>**A sync (or the deprecated `--retry-failed` alias) lists failures that "belong to a run with different sync options"?** A managed retry resumes only the cursor its own options select; each other failure gets one line with its class and the command that settles it. `resumable (replay …)`: an unfinished run holds it, and the command resumes that run under its recorded options. `resumable (fresh discovery, not a replay …)`: no run holds it any more; the command starts a new run from HEAD under the failed run's options, which clears the failure when it completes. For a failure recorded before runs kept their options, the options are recovered only when an option set reproduces its cursor key exactly. `safely orphaned`: nothing current can resume it; preview `gbrain repair managed-sync-orphans --source <id>` and apply with the hash it prints. `unresolved`: its options were never recorded and nothing selects it; the line says what has to finish first (a request still in flight, or a current run whose completion lets the orphan repair retire it).
-<a id="checkpoint-validation-timeout"></a>**A managed sync is blocked with `checkpoint_validation_timeout`?** Run the printed commands on the brain host: `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …`. Doctor's `persistence_request_growth` warns before lifetime request IDs run out.
+<a id="checkpoint-validation-timeout"></a>**A managed sync is blocked with `checkpoint_validation_timeout`?** Run the printed commands on the brain host: `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull …`. Doctor's `persistence_request_growth` warns before lifetime request IDs run out.
<a id="pglite-aborted"></a>**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](../ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](../INSTALL.md#pglite-crashes-at-startup-runtimeerror-aborted).
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index a2b75a3522..5e6352d1b0 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -58,7 +58,7 @@ of making a duplicate.
| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: run `gbrain sync --source <source> --no-pull` on the brain host (the refusal's fix), read the page again and resubmit with a new request ID. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. |
| <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. A purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then import its current content into the surviving page with `gbrain repair file-drift --source <id> --slug <surviving-slug> --prefer file` (preview, then the apply command it prints) and `gbrain sync --source <id> --no-pull`. Sync does not overwrite a surviving page that differs from the file: it holds it [`file_drift`](#file_drift), whose fix leads with the same command. For a purge, soft-delete instead. After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. |
| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. |
-| `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull --retry-failed`. |
+| `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull`. |
| `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. |
| `physical_root_directory_changed` | `recovery_required` | The directory at the checkout's recorded path is not the one the owner stamped: its inode changed, or its birth time differs from the stamp by more than 1 µs, while the owner token, brain, worktree, root and device all still match. A checkout deleted and recreated at the same path (restore from backup, rebuilt container, Migration Assistant copy) looks like this. A birth time within 1 µs of the stamp is accepted (#6501: APFS reports a new directory's birth time tens of nanoseconds apart across processes); a stamp of `0` against a filesystem that now reports a birth time, or a damaged stamp, still refuses. | If the checkout was recreated at its recorded path, do a deliberate relocated-root self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. `writer status --json` prints the commands filled in. Retry the original write with the **same** request ID. Never delete ownership marker files. |
| <a id="recreated-root"></a>recreated or moved canonical root | `recovery_required` | The checkout at the recorded path is a different directory (new inode and birth time after a restore, a rebuilt container or a Migration Assistant copy) or the recorded path now resolves through a symlink; without this release every verb, self-transfer included, refused with no exit (#5914). | Same path, directory recreated: the self-transfer above with `--confirm-relocated-root` on **both** phases; it waives only the directory identity comparison and needs the reservation beside the root (`.gbrain-owner-<hash>.json`) and the stamp to agree on token, brain, worktree, root and coordination path. Recorded path now a symlink to the moved checkout: `gbrain sources set-path <source> <path>` on the owner host keeps the worktree and moves its records. `gbrain sources writer deactivate --dry-run` lists `physical_root` when its real run would refuse. Runbook: [recreated root](../architecture/topologies.md#recreated-root). Never delete ownership marker files. |
@@ -68,7 +68,7 @@ of making a duplicate.
| `take_row_collision` | `take_row_collision` | A save adds a takes-table row whose row number already belongs to a different take that exists only in the database. The save stops instead of overwriting that take. | Renumber the new takes row, or add the existing take to the page's takes table, then save with the current `expected_revision` and a **new** request ID (the content changed). |
| `invalid_source_uri` | `invalid_source_uri` | The brain has shared skillpacks, and the page's stored `source_uri` is a `file:` URI that cannot be turned into a local path, so gbrain cannot prove the write stays outside a skillpack. Shared-skill protection stays on. | The source owner inspects the page's stored `source_uri` on the brain host and replaces it with an absolute file URI or clears it; there is no dedicated command yet. Retry with a **new** request ID. |
| `queue_capacity` | `queue_capacity` | Admission would exceed a write-journal limit. Existing requests keep their place; nothing is evicted. For the cumulative limits (lifetime request IDs and receipt bytes), `detail` names the limit, for example `principal_lifetime_ids`; for the outstanding-request caps, `detail` carries the counts (`outstanding=<used> limit=<limit>`), and a managed `gbrain sync` drain waits them out ([`write_capacity`](#drain-write-capacity)). | For a cumulative limit, run the printed `gbrain config set persistence.limits.<limit> <value>` (sized for about one more year at the current rate), then retry with the **same** request ID. For outstanding-request, queued-byte or recovery-byte limits, let outstanding requests finish and check `gbrain sources writer status`. See [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention). |
-| <a id="checkpoint-validation-timeout"></a>`index_building`, `index_missing` or `indexes_valid` | `checkpoint_validation_timeout` | A managed sync's checkpoint validation (the check that every page receipt of the run committed) hit the coordinator's 5-second statement timeout on a large `persistence_requests` table. The checkpoint request failed terminally instead of being retried ahead of every other write to the source, so other writes proceed; `last_commit` is unchanged and every page the run already committed stays committed. `detail` says which of three states the request indexes were in when the hint was built. | `index_building`: migration 179 is still building the indexes; wait (doctor `persistence_request_indexes` shows progress), then run the printed retry. `index_missing`: run `gbrain repair request-indexes --apply` (it drops an INVALID index and rebuilds it concurrently on Postgres), then the printed retry. `indexes_valid`: run the printed retry once; if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. The retry is `gbrain sync --source <source> --no-pull --retry-failed` plus the run's `--repo` base and cursor options (`--full`, `--working-tree`, `--src-subpath`, `--exclude`, `--include-hidden`, `--strategy`) and saved processing flags, so it resumes the same cursor. Do not cancel the request: a cancelled checkpoint still blocks the next one. |
+| <a id="checkpoint-validation-timeout"></a>`index_building`, `index_missing` or `indexes_valid` | `checkpoint_validation_timeout` | A managed sync's checkpoint validation (the check that every page receipt of the run committed) hit the coordinator's 5-second statement timeout on a large `persistence_requests` table. The checkpoint request failed terminally instead of being retried ahead of every other write to the source, so other writes proceed; `last_commit` is unchanged and every page the run already committed stays committed. `detail` says which of three states the request indexes were in when the hint was built. | `index_building`: migration 179 is still building the indexes; wait (doctor `persistence_request_indexes` shows progress), then run the printed retry. `index_missing`: run `gbrain repair request-indexes --apply` (it drops an INVALID index and rebuilds it concurrently on Postgres), then the printed retry. `indexes_valid`: run the printed retry once; if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. The retry is `gbrain sync --source <source> --no-pull` plus the run's `--repo` base and cursor options (`--full`, `--working-tree`, `--src-subpath`, `--exclude`, `--include-hidden`, `--strategy`) and saved processing flags, so it resumes the same cursor. Do not cancel the request: a cancelled checkpoint still blocks the next one. |
| <a id="connector-account-changed"></a>`account_changed`, `account_unresolved` | `connector_account_changed` | A managed Google or GitHub connector's credential resolves to a different account than the one pinned for the source (Google email, GitHub App installation or login), or to no account at all. Google checks every enabled service before any service runs. Nothing was imported. No reset flag authorizes an account change. | The suggestion gives two branches with real values. (A) Restore the credential for the pinned account (the configured `g_token_env`, `g_token_command`, vault credential, `gh_token_env` or GitHub App key), then `gbrain sync --source <source>`. (B) For a deliberate change, add a new source for the new account (`gbrain google setup --account <email>`, or `gbrain sources add <new-id> --kind github … --app-install <id>`), then `gbrain sources archive <source>`; existing pages stay under the old source. The refused run is recorded, and autopilot then skips the source (an `unavailable-path` skip in the fan-out, `freshness_source_path_skipped` with `code: connector_account_changed` in the freshness loop) instead of retrying it every interval; doctor `connector_account_mismatch` lists such sources. A `gbrain sync --source <source>` that passes the account check clears the skip, and so does a change to the source's connector config (one more automatic try). |
| <a id="connector-intent-outdated"></a>`pre_upgrade` | `connector_intent_outdated` | A connector write was admitted in the intent format retired in v0.60.11.0. With detail `pre_upgrade` it was admitted before this brain's upgrade; otherwise a connector host older than v0.60.11.0 admitted it. The consumer recovers any file publication in progress first, then fails the request. | `pre_upgrade`: nothing to do; the item is fetched again on the next `gbrain sync --source <source>` under a new request ID. Otherwise: `gbrain upgrade` on the host that runs connector jobs, then `gbrain sync --source <source>`. |
| <a id="invalid-connector-text"></a>`invalid_connector_text` | `invalid_connector_text` | A Google or GitHub item's identity field (a path, item id or account) contains a NUL or an unpaired UTF-16 surrogate, which cannot be stored. Prose (bodies, subjects, titles) is cleaned at render time and never refused. The item is counted toward a hold; the rest of the sync continues. | Nothing to run for one refusal. Once the item is held, `gbrain sources status <source>` names it; after the provider data is fixed, `gbrain sources retry-held <source>`, then `gbrain sync --source <source>`. |
@@ -83,13 +83,13 @@ of making a duplicate.
| <a id="activation_source_path_missing"></a>`source_path_missing` | `source_changed` | `gbrain sources writer activate` (with or without `--dry-run`) found a source whose recorded `local_path` no longer exists on this host, for example a checkout that lived in a temporary directory. Activation cannot verify that source's canonical directory, so nothing changed. The message names the source and the missing path. Claiming the source at another directory does not help while the stale path stays recorded. | Run the command the suggestion prints: `gbrain sources set-path <source> <directory>` to point the source at its checkout (the suggestion fills in the claimed directory when the source is claimed), or `gbrain sources remove <source> --confirm-destructive` when the source is no longer needed (`gbrain sources archive <source>` keeps a 72-hour grace period). Then `gbrain sources writer activate --confirm-quiesced --dry-run` and activate. |
| <a id="source_checkout_missing"></a>canonical checkout missing | `recovery_required` | A managed source lifecycle command (`gbrain sources archive`, `remove`, `purge`, `restore`, `rebind`) found that the source's canonical checkout directory was deleted out of band. A source with **no pages** that is the **only** source on that checkout is retired anyway: archive, remove and purge succeed and the receipt records `retired_without_checkout` with the missing path. Otherwise nothing changed; the message names the path, the page count and how many other sources share the checkout. Recreating an empty directory at the same path does not help (its physical identity differs). | Restore the checkout (for example from a backup) and retry. If it is gone for good, switch the brain to classic mode with `gbrain sources writer deactivate --dry-run`, then the printed `apply_command` (see the [deactivate runbook](../architecture/topologies.md#deactivate-runbook)), and retire the source there with `gbrain sources archive <source>`. |
| <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. |
-| <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull --retry-failed`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). |
+| <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). |
| <a id="extract-timeline-refused"></a>timeline extract refused | the printed code, usually `writer_coordinator_required` | `gbrain extract timeline --source db` (or a timeline-only `gbrain extract timeline` on a managed brain) could not write a page's timeline rows. It prints `refused: <code>; nothing written; existing timeline rows are untouched` per page, a summary of written versus refused, and exits 1. The rows import already stored for each page stay as they were. | `gbrain extract --stale` (add `--source-id <id>` when you scoped the run) publishes links and missing timeline rows on the managed path. If it refuses too, follow the row for the printed code. |
| 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, preview with `gbrain doctor --remediation-plan --json` and, after the user agrees, run `gbrain doctor --remediate --yes --include-repairs --expect <plan_hash> --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 not affected. | 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. | `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="managed_sync_flag_refused"></a>`managed_sync_flag_refused` (`detail` = the flag) | `managed_sync_flag_refused` | A managed source keeps every failed-receipt and ignored-file guard, so `gbrain sync --skip-failed` and `gbrain sync --include-gitignored` have no managed meaning. The refusal names the flag and comes before anything runs: at parse in `gbrain sync` (before a legacy ledger row is acknowledged or the cost gate runs, `--all` included), before the serve-delegation ladder looks for the serve's socket, and in the managed-sync guard that sync jobs, MCP `sync_brain` and the cycle reach. Nothing is admitted and no cursor is written. | Rerun the printed `fix` (the same command without the flag). A failed file is fixed and then retried with `gbrain sync --source <source> --no-pull --retry-failed`; an ignored file syncs once it is committed and not ignored. `gbrain sync status --source <source> --json` shows the source's failures and holds. |
+| <a id="managed_sync_flag_refused"></a>`managed_sync_flag_refused` (`detail` = the flag) | `managed_sync_flag_refused` | A managed source keeps every failed-receipt and ignored-file guard, so `gbrain sync --skip-failed` and `gbrain sync --include-gitignored` have no managed meaning. The refusal names the flag and comes before anything runs: at parse in `gbrain sync` (before a legacy ledger row is acknowledged or the cost gate runs, `--all` included), before the serve-delegation ladder looks for the serve's socket, and in the managed-sync guard that sync jobs, MCP `sync_brain` and the cycle reach. Nothing is admitted and no cursor is written. | Rerun the printed `fix` (the same command without the flag). A failed file is fixed and then retried by the plain `gbrain sync --source <source> --no-pull`; an ignored file syncs once it is committed and not ignored. `gbrain sync status --source <source> --json` shows the source's failures and holds. |
| <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). |
| <a id="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. |
@@ -116,7 +116,7 @@ a receipt can report has a row here.
| `writer_pool_capacity` | `writer_pool_capacity` | The canonical owner has no free publication slot right now; the write stays queued. | Wait and poll the receipt (`gbrain write-request <id>`). If it persists, check `gbrain sources writer status <source>`. |
| `revision_required` | `revision_required` | The operation must be bound to a revision you reviewed (for example `--if-version` or `expected_revision`), and none was given: a `put_page` of a page that already exists without `expected_revision` reports this since #5385 (earlier releases said `revision_conflict`). | Preview first, then repeat with the revision the preview printed. |
| `revision_conflict` | `revision_conflict` | The page changed after the revision this write was bound to. Nothing was overwritten. | Re-read the page, merge your change, and save with the new revision. |
-| `sync_cursor_replaced` | `sync_cursor_replaced` | A managed sync checkpoint found that another sync run of the same source (a `--retry-failed` rediscovery, a newer sync) replaced the cursor it belongs to, so it had nothing left to publish. The receipt is a conflict; no managed-sync failure is recorded for it, and the run that awaited it goes on with the cursor that now covers the source. | Nothing: let the current sync finish. `gbrain sync status --source <id> --json` shows that cursor. A same-run index lag keeps reporting `revision_conflict`. |
+| `sync_cursor_replaced` | `sync_cursor_replaced` | A managed sync checkpoint found that another sync run of the same source (a rediscovery, a newer sync) replaced the cursor it belongs to, so it had nothing left to publish. The receipt is a conflict; no managed-sync failure is recorded for it, and the run that awaited it goes on with the cursor that now covers the source. | Nothing: let the current sync finish. `gbrain sync status --source <id> --json` shows that cursor. A same-run index lag keeps reporting `revision_conflict`. |
| <a id="revision-backfill"></a>`revision_backfill_pending` | `revision_backfill_pending` | The page was written before page revisions existed (an upgrade from below schema v150) and the resumable revision backfill has not reached it, so it has no revision to bind to. Its revision reads as `backfill_pending`, never a UUID. Nothing was written. `gbrain doctor` reports the backfill as `revision_backfill` with the pending count and any failed rows by page. | Resume the backfill on the brain host with `gbrain apply-migrations --force-schema` (it prints its progress; `--yes` alone does not resume it once the schema is current). Rows that used all three attempts are no longer retried: run `gbrain repair orphan-children` to preview orphaned child rows and torn page bodies ([orphan children](repair.md#orphan-children)). |
| `idempotency_conflict` | `idempotency_conflict` | The `request_id` was already used for a different target, content or protocol. | Use a new `request_id` for a different write; reuse an ID only to replay the same write. |
| <a id="write_pending"></a>`write_pending` | `write_pending` (CLI exit 10) | The write was accepted but has not committed yet. It keeps its request ID and may still commit. The CLI exits 10, not 1; a lost acknowledgment with no receipt is `submission_status: "unknown"` and exits 1. See [CLI exit status for writes](../protocol/MEMORY_VERBS_v1.md#cli-exit-status-for-writes). | Poll `gbrain call get_write_request '{"request_id":"<id>"}'`, or repeat the same command with the same `--request-id` and a longer `--wait <seconds>`. Scripts that only need the write admitted pass `--accept-pending` (or `GBRAIN_ACCEPT_PENDING=1`) to exit 0. |
@@ -135,7 +135,7 @@ a receipt can report has a row here.
| `writer_registration_required` | `writer_registration_required` | The source needs an active canonical owner before this operation, for example activation. | Claim the source on its owner host (`gbrain sources writer status <source>` names the next step). |
| `writer_identity_invalid` | `writer_identity_invalid` | This host's local writer identity file is unreadable or has an unknown format. | Run `gbrain doctor` on the host; it names the identity file to repair. |
| `writer_not_initialized` | `writer_not_initialized` | The brain has no persistence identity yet, usually because migrations have not run. | Run `gbrain apply-migrations --yes` on the brain host. |
-| <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | On a managed brain whose `tags`, `timeline_entries` or `takes` table has a `source_id` column gbrain does not create, the managed writer guard of a gbrain older than v0.60.38.0 refuses every insert and update of those rows, including coordinated ones. gbrain v0.60.38.0 and later take those rows' source from their page and ignore the column; an uncoordinated delete of such a row on a live page is refused, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md#060380---2026-10-03) (or [repair](repair.md#recover-after-an-upgrade)): `gbrain sync … --no-pull --retry-failed`, `gbrain extract --stale`, `gbrain extract timeline --source db`, a previewed `gbrain facts relink`, then `gbrain repair failed-writes` (preview, then `--apply --expect <hash>`) for the refused `put_page`, `add_timeline_entry` and `remember` calls; see [failed writes](repair.md#failed-writes). |
+| <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | On a managed brain whose `tags`, `timeline_entries` or `takes` table has a `source_id` column gbrain does not create, the managed writer guard of a gbrain older than v0.60.38.0 refuses every insert and update of those rows, including coordinated ones. gbrain v0.60.38.0 and later take those rows' source from their page and ignore the column; an uncoordinated delete of such a row on a live page is refused, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md#060380---2026-10-03) (or [repair](repair.md#recover-after-an-upgrade)): `gbrain sync … --no-pull`, `gbrain extract --stale`, `gbrain extract timeline --source db`, a previewed `gbrain facts relink`, then `gbrain repair failed-writes` (preview, then `--apply --expect <hash>`) for the refused `put_page`, `add_timeline_entry` and `remember` calls; see [failed writes](repair.md#failed-writes). |
| `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. A file write refused because the path sits in a managed canonical worktree names that worktree in the message, and its `detail` reads `root=<directory> source=<id or unknown> evidence=<marker file, managed-root registry or source binding>`. | Run the operation through the command the message names, on a managed brain. When the brain is not managed and the evidence is an ownership file (`.gbrain-owner.json`, `.gbrain-owner-<hash>.json`, `.gbrain-managed`), check it with `gbrain sources writer status` before removing anything: a half-finished claim is finished or rolled back through writer administration. |
| `fact_already_expired` | `fact_already_expired` | The fact the write targets is already expired or withdrawn. | Nothing to do; list active facts to find the current one. |
| `source_writeback_required` | `source_writeback_required` | The write needs a correction to the source's repository files, and this caller or profile never writes them. | Make the correction in the source repository, then sync. |
@@ -205,7 +205,7 @@ with each file and fix the ones that need no guessing."*
| <a id="parser_regression"></a>`parser_regression` | With `GBRAIN_SYNC_PARSER_REGRESSION=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. |
| <a id="preparation_stalled-hold"></a>`preparation_stalled` | The write for this file could not finish *preparing* within its attempt limit, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`preparation_stalled`](#preparation_stalled). | `gbrain sources writer status --source <source> --json` (read-only), fix what it names, then `gbrain sources retry-held <source>` and the same sync with its options. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
| <a id="worktree_dirty"></a>`worktree_dirty` | The working tree holds uncommitted bytes for this file that match neither the pinned commit nor the current page (an agent mid-edit on a live checkout), and importing the pinned version would discard them (#6340). Before this release the refusal (`source_changed` / `pinned_git_worktree_conflict`) stopped the whole run; now the file is held, the local edit is untouched and the rest of the source syncs. The hold keeps the pinned blob (`meta.blob_oid`) and a hash of the working bytes, counts `meta.attempts` each time the same file is held again, and a page held three times is reported `needs_human` by `gbrain sync status`. Bytes that are **committed at HEAD** past the pinned target are not a conflict at all: sync imports them as HEAD has them and the later pin..HEAD diff re-imports the same bytes as a no-op. Since 0.60.179.0 (#6513) the same hold covers a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: that refusal used to block the cursor with no exit, because `--retry-failed` replays the same pin against the same bytes, `sources refresh` refuses `sync_in_progress` on the unfinished cursor and `--acknowledge-managed` refuses `cursor_unfinished`. Working-tree bytes that already *are* the correction (gbrain's own writeback, published before the request that carried it settled) are not a conflict either: the page imports and the file is left as it is. | Commit the edit (or restore the file), then `gbrain sync unblock --source <source> --apply` re-screens every held file that is now committed and prints the sync to run (`gbrain sources retry-held <source>` does the same for all holds). A later commit that changes the file re-screens it on its own. Never discard or normalize the local bytes. Runbook: [sync unblock](sync-unblock-runbook.md). |
-| <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `GBRAIN_SYNC_PARSER_REGRESSION=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull --retry-failed`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |
+| <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `GBRAIN_SYNC_PARSER_REGRESSION=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |
| <a id="takes_holder_invalid"></a>takes holder (`invalid_params`) | `takes_add`, or `takes_supersede` with an explicit `holder`, was given a holder the takes fence cannot carry: empty, whitespace, or not `world`, `brain`, `people/<slug>` or `companies/<slug>` (a legacy bare slug is accepted). The value is trimmed first, so `" world "` is stored as `world`. Nothing was written: before this release such a holder was published into the fence and every later takes write on that page was refused `target_fence_malformed`. A supersede without an override keeps the row's stored holder. A page whose stored holder is already malformed still refuses every takes write (`invalid_fence`); `gbrain repair fences` is the way out. | Resend with a holder in that grammar (`holder: me` on the brain host resolves the owner's holder). For a page already carrying a malformed holder, preview `gbrain repair fences --slug <slug>` and apply it, or edit the `who` cell by hand. Format: [holders](fence-format.md#holders). |
| <a id="changed_since_preview"></a>`changed_since_preview` | A hash-bound repair apply (`gbrain repair frontmatter --apply --expect <hash>`, `gbrain repair fences --apply --expect <hash>`, `gbrain repair content --apply --expect <h1>[,<h2>]`) found a file, its proposed change or its page different from what the preview showed, so that item was not written; the rest of the approved set still applied. | Preview again with the same selection and apply the new hash (for the content lane, one hash per kind in lane order). For frontmatter, show the user the new diff first; a fence repair needs no extra consent ([fence reason](#fence-changed_since_preview)). |
@@ -510,11 +510,11 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run
| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_progress` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like (older builds named this cause `no_admission`; it is retired, and a receipt carrying it means the same). The pass returns when the run's final checkpoint commits: the tail after it (planner statistics, link extraction for the imported pages) runs after the drain lease is released, outside this governor, bounded at 5 minutes; the checkpoint's own transaction records it as owed, so a process that dies before it leaves it for the next sync of the source, and a failed or cut-short tail keeps the run `synced` with a `[gbrain notice sync_tail_degraded]` whose fix is `gbrain extract --stale --source-id <id>`. The owner process bounds its own publish the same way: past the ceiling the claim reads `waiting_on: publication_deadline`, a Postgres publish transaction idle past it is ended by the server (nothing commits), 30 s later a Postgres publish still running is cancelled (its connection is discarded, nothing commits, and the write is queued again), and a publish that still has not settled 35 s after the ceiling makes the owner report `restart_required` (its heartbeat row carries `restart_required`, which the drain reads as `owner_wedged_here`; the consumer status lists it under `stuck_publications`); restart that process. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. |
| <a id="drain-database-contention"></a>`database_contention` | `database_contention` | `blocked` (or an error) | Three consecutive passes hit database contention, a statement timeout or a dropped connection, or reading the awaited write's state failed (an authentication or permission failure stops at once). The drain retries transient failures with backoff before giving up. Accepted writes keep their request IDs. | Fix database access (`gbrain engine status --probe`), then rerun `next.command`. |
| <a id="drain-writer-blocked"></a>`recovery_required`, `owner_unavailable`, `unexpected_file_bytes`, `unexpected_staging_bytes` | `recovery_required` | `blocked` | The checkout's writer needs intervention before more pages can publish: interrupted publication recovery, no live owner, or unexpected bytes in the file or staging area. | `gbrain sources writer status <source>` and the fix it prints. Unexpected bytes are the user's edits; ask before discarding them. Then rerun `next.command`. |
-| <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (it adds `--retry-failed`). Ask the user before skipping content. |
+| <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (the plain sync with the same options). Ask the user before skipping content. |
| <a id="drain-preparation-abandoned"></a>`preparation_abandoned` | `preparation_abandoned` | `resumable` | A write this process's own writer holds was still preparing past its allowance (its budget plus 30 s, never more than the ceiling `persistence.preparation_ceiling_ms` plus 30 s) and the process cannot cancel it, so the sync exited to end it. The cursor and accepted writes are intact; `drain.stall` names the step (`stall.step`, `stall.waiting_on`). Exit 0. | Rerun `next.command` (`safe_to_loop` is true). The next pass holds the entry as `preparation_stalled` if it stalls again; `gbrain sources writer status --source <source> --json` shows what it was stuck on. |
| <a id="preparation_systemic"></a><a id="drain-preparation-systemic"></a>`preparation_systemic` | `preparation_systemic` | `blocked` | The run's breaker tripped: more `preparation_stalled` receipts than a source should hold (the `GBRAIN_SYNC_HOLD_ESCALATE_COUNT` / `GBRAIN_SYNC_HOLD_ESCALATE_PCT` rule over this run's screened imports) or five stalled entries in a row with no page committed between them. The run stopped with one diagnostic instead of holding every file: the write owner, not the files, is the likely cause. `breaker` carries the rule, the counts, the last step and the fix; exit 1. | `gbrain sources writer status --source <source> --json`, fix what it names or upgrade gbrain, then rerun the same sync: it re-freezes the stopped entry under a fresh request and schedules the files this run held for a re-screen. |
| <a id="drain-write-capacity"></a>`write_capacity` | `queue_capacity` | `blocked` | The sync could not admit its next write for the whole no-progress window (30 s) because other writers' requests held the outstanding-request cap of its write principal (`persistence.limits.principal_outstanding`, default 100; the brain cap `persistence.limits.brain_outstanding`, 1000, works the same way): on one host the CLI sync and a maintenance run (fact-fence adoption, `dream`) share the `local_cli` principal, so a long adoption queue leaves no room for a sync write. Nothing failed and the cursor is intact: the drain retried the admission with backoff while they settled, printing `waiting for write capacity (N outstanding of M)`, and stopped only when the window passed. `drain.capacity` carries the counts and the wait; exit 1. A cumulative cap (permanent request IDs, receipt bytes) is a different refusal: it names its config key and stops at once. | `gbrain sources writer status --source <source> --json` lists the outstanding requests (read-only). Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync; it resumes where it stopped. |
-| <a id="drain-connection-lost"></a>`connection_lost` | `connection_lost` | `blocked` | The database connection dropped three times in a row (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`: a pooler closing the socket mid-statement) with no page committed between the drops (#6340). Each drop was reconnected and retried after 5, 15 and 45 s; a drop that then moves data is not reported at all. Nothing is recorded against the source: the cursor and its frozen manifest stand, and `drain.connection` carries the count and the last error text (never a URL). Exit 1. | Check the database and pooler (`gbrain doctor --json`), then rerun `next.command` (`safe_to_loop` is true, `retry_after_ms` 60 s): it resumes at the stored cursor without re-freezing the manifest, with or without `--retry-failed`. Runbook: [sync unblock](sync-unblock-runbook.md#connection). |
+| <a id="drain-connection-lost"></a>`connection_lost` | `connection_lost` | `blocked` | The database connection dropped three times in a row (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`: a pooler closing the socket mid-statement) with no page committed between the drops (#6340). Each drop was reconnected and retried after 5, 15 and 45 s; a drop that then moves data is not reported at all. Nothing is recorded against the source: the cursor and its frozen manifest stand, and `drain.connection` carries the count and the last error text (never a URL). Exit 1. | Check the database and pooler (`gbrain doctor --json`), then rerun `next.command` (`safe_to_loop` is true, `retry_after_ms` 60 s): it resumes at the stored cursor without re-freezing the manifest. Runbook: [sync unblock](sync-unblock-runbook.md#connection). |
| <a id="drain-capacity-paused"></a>`capacity_paused` | `capacity_paused` | `resumable` | The run passed its capacity preflight, then a cumulative write cap refused its next admission (`write_quota_exhausted`) or, for a background sync, the pause line did (`write_capacity_backpressure`): another writer used the room the preflight counted on. Nothing failed; the cursor and every accepted write stand, and `drain.capacity_pause` names the refusal and its config raise. | Run the `gbrain config set` the report names on the brain host (request ids never free; receipt bytes also free as receipts compact), then rerun the same `gbrain sync`. Verify with `gbrain doctor --only persistence_capacity --json`. |
| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock) or `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`). The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, `effect_recovery`, `request_recovery`, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. |
| <a id="sync_drain_lease_held"></a>`drain_lease_held` | `sync_drain_lease_held` | `resumable` | Another process holds the source's drain lease (#6712): one managed drainer per source, and that holder (a serve, a `sync` job, the dream cycle, another terminal) is still committing pages. `gbrain sync` follows it within its own `--timeout` and run deadline, printing the holder (kind, pid, host, gbrain version) and the pages it commits (every 10 s on a terminal, 60 s otherwise), and takes the lease when the holder releases it. This code means the budget ended first, or the lease moved to another process mid-pass (`lost`); nothing this run admitted is lost and the cursor is intact. `--no-delegate` never skips the lease. `drain.lease_held.holder` reuses the drain's owner fields: `kind`, `id`, `host`, `pid`, `started_at`, `last_heartbeat_at`, `version` and `progress` (`committed`, `last_committed_at`, `last_progress_at`); `next.retry_after_ms` is 60 s and `next.safe_to_loop` is true. Exit 0. A cron that runs `gbrain sync` every few minutes beside a serve exits 0 here on each tick while the serve works. | Rerun `next.command` after `next.retry_after_ms`, or let the holder finish. Ctrl-C while following stops only this run; the holder keeps going. A holder that commits nothing for 5 minutes is not reported here: the run stops [`drain_stalled`](#drain-lease-stalled) instead. |
diff --git a/llms-full.txt b/llms-full.txt
index 94b039eb17..6d2cf33490 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7055,14 +7055,17 @@ vars — incident-time escape hatches, not everyday knobs.
sync only, `gbrain sync --skip-failed` acknowledges a known-bad set.
**Managed sync never acknowledges or auto-skips failed cursors.** Its
durable failed receipt remains immutable on ordinary replay. Correct the
- cause, inspect local `gbrain doctor`, then explicitly retry an idle
- ordinary-source cursor with the same full/working-tree/filter options:
+ cause, inspect local `gbrain doctor`, then rerun the plain
+ sync for that source with the same full/working-tree/filter options; it
+ retries what the previous invocation recorded:
```bash
- gbrain sync --source <source-id> --no-pull --retry-failed
+ gbrain sync --source <source-id> --no-pull
```
- This retries with fresh admission; do not add `--skip-failed`. A successful
+ This retries with fresh admission; do not add `--skip-failed`
+ (`--retry-failed` is a deprecated alias of the plain sync on a managed
+ brain). A successful
full run does not clear a separate failed incremental cursor. Doctor reports
the remaining run; CLI blocked results exit nonzero and local diagnostics
include source/path/code/request/run/target. Counts are cumulative for the
@@ -7296,7 +7299,7 @@ moving again; ask me only about the ones gbrain will not decide by itself."*
refuses every repair-class hold instead, as releases before #6377 did.
3. Run that sync. It re-screens the scheduled files, imports each one that now
passes and holds again what still fails; the rest of the source is never
- blocked. With `--retry-failed` a cursor an older release left blocked on a
+ blocked. A cursor an older release left blocked on a
page fault converts in place (same run, no rediscovery).
4. If `needs_human` is true, stop looping and page a person with the slug and
`human_reason` from `status` (`next.user_message` is written for relay).
@@ -7416,7 +7419,8 @@ earlier one is held. A file that changed after its request was admitted
(`source_changed`) is retried after the manifest's last entry, at most three
times, then held `worktree_dirty`. A transport fault re-freezes the entry in
place; a systemic stop is re-frozen in place by the next plain sync, at most
-three times in a row before the failure stays recorded for `--retry-failed`.
+three times in a row, and once that bound is spent the next plain sync
+resets it and tries again.
A `knock_on` or `knock_on_exhausted` error was written by an older gbrain
(a page cancelled only because another page of its sync did not commit, or
@@ -7429,7 +7433,7 @@ the extra drain and reports it); an older build's `window_dropped` reads as
a knock-on. A checkpoint refused by a receipt at an index the cursor passed
without a commit is re-assessed on every resume and commits without
rediscovering the manifest; one a receipt still blocks is rediscovered by
-`--retry-failed`.
+the next plain sync.
An unknown code is systemic and human: `gbrain errors <code>` explains it
offline, `gbrain doctor --json` says what the brain thinks.
@@ -7465,7 +7469,7 @@ it and kept going; the receipt lists the hold (`held`, `held_count`) and
run ([held files](write-refusals.md#held-files-and-content-refusals)).
- `revision_conflict`, `page_identity_changed`, `pinned_git_worktree_conflict`
as a `last_error` come from a run on an older release; this release holds
- them. Rerun with `--retry-failed`: the stopped entry converts in place, the
+ them. Rerun the plain sync: the stopped entry converts in place, the
manifest is not re-frozen. A `revision_conflict` or `cancelled` error with
`detail: knock_on` needs no flag: the next plain sync re-freezes the entry
(act on `root_cause` instead).
@@ -7492,8 +7496,11 @@ repair: a source in a subdirectory of its repository pins one
Ask the user which mode the source keeps. Restoring the pin to the run's mode
lets the next plain `gbrain sync --no-pull --source <id>` finish (the refused
checkpoint is retried by itself); keeping the new pin takes
-`gbrain sync --no-pull --source <id> --retry-failed`, and the pages the refused
-run wrote keep their old slugs beside the new ones. A source rooted at its
+`gbrain repair managed-sync-orphans --source <id>` (it lists the cursor as
+`slug_mode_refused`; preview, then `--apply --expect <hash>`), after which the
+next sync discovers the source again under the kept pin. No sync retries that
+checkpoint by itself. The pages the refused run wrote keep their old slugs
+beside the new ones. A source rooted at its
repository root never gets this code: both modes give it the same slugs, and
a checkpoint an older release refused there as `revision_conflict` finishes on
the next plain sync.
@@ -7502,10 +7509,10 @@ the next plain sync.
The frozen manifest always lived in the cursor (`op_checkpoints`, op
`managed-sync`). What threw it away was the failure ledger: every run death
-wrote a row, and `--retry-failed` read the row and rediscovered from index 0
+wrote a row, and the retry read the row and rediscovered from index 0
(eight to twelve minutes of silence on a 14k-entry source). Page faults are
-now holds and connection faults are not recorded, so a relaunch, with or
-without `--retry-failed`, finds the cursor and resumes it. Only a systemic
+now holds and connection faults are not recorded, so a relaunch finds
+the cursor and resumes it. Only a systemic
failure still writes a ledger row.
When HEAD moved past the pinned target while the run drained, the drain takes
@@ -7533,7 +7540,7 @@ how often a person or an agent had to step in, per UTC day for the last seven
days, so a soak can show that sync keeps moving on its own.
- `interventions`: `sync_non_plain` (a `gbrain sync` with a recovery flag such
- as `--retry-failed`, `--full`, `--break-lock` or `--skip-failed`; the plain
+ as the deprecated `--retry-failed`, `--full`, `--break-lock` or `--skip-failed`; the plain
scheduler flags `--all`, `--no-pull`, `--hard-deadline`, `--no-embed`,
`--no-lanes`, `--no-bulk` and `--json` do not count), `repair_apply` (a
`gbrain repair … --apply` of any kind but file-drift), `unblock_apply`,
@@ -10595,9 +10602,9 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| `gbrain waiting` lists bank, payment or shipping alerts as people waiting on you | upgrade (#5012: mail with `Precedence: bulk/list/junk`, a `List-Id` or a no-reply `Reply-To` opens no reply-owed loop); for loops opened before the upgrade, `gbrain waiting` prints `gbrain loops drop sender <email> --source <id> --dry-run` per sender; preview, then run it without `--dry-run` (cannot be undone), or `gbrain loops mute sender <email>` for a reversible stop ([open loops](open-loops.md#the-surfaces)) | agent, after the user agrees | none to preview | `gbrain waiting --json` no longer lists the sender |
| [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` |
| [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |
-| [`gbrain sync` refused `managed_sync_flag_refused`](write-refusals.md#managed_sync_flag_refused) | rerun the same command without the flag `detail` names (`--skip-failed` or `--include-gitignored`); fix a failed file and use `--retry-failed`, or commit an ignored file | agent | none | `gbrain sources status --json` |
-| [`--retry-failed` says failures "belong to a run with different sync options"](#retry-other-options) | run the command printed on each line: `resumable (replay …)` or `resumable (fresh discovery …)` reruns under the failed run's options, `safely orphaned` previews `gbrain repair managed-sync-orphans --source <id>` (apply with its hash), `unresolved` names what has to finish first | agent; the repair apply after the user agrees | the repair retires bookkeeping rows only | `gbrain sync status --source <id> --json` |
-| [Managed sync blocked with `checkpoint_validation_timeout`](#checkpoint-validation-timeout) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` |
+| [`gbrain sync` refused `managed_sync_flag_refused`](write-refusals.md#managed_sync_flag_refused) | rerun the same command without the flag `detail` names (`--skip-failed` or `--include-gitignored`); fix a failed file and rerun the plain sync (`--retry-failed` is a deprecated alias), or commit an ignored file | agent | none | `gbrain sources status --json` |
+| [Sync with the deprecated `--retry-failed` alias says failures "belong to a run with different sync options"](#retry-other-options) | run the command printed on each line: `resumable (replay …)` or `resumable (fresh discovery …)` reruns under the failed run's options, `safely orphaned` previews `gbrain repair managed-sync-orphans --source <id>` (apply with its hash), `unresolved` names what has to finish first | agent; the repair apply after the user agrees | the repair retires bookkeeping rows only | `gbrain sync status --source <id> --json` |
+| [Managed sync blocked with `checkpoint_validation_timeout`](#checkpoint-validation-timeout) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` |
| [Doctor warns `persistence_session_timeouts` (`session_timeouts_not_applied`)](#session-timeouts-not-applied) | `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` on the database, or accept it: preparation reads carry their own bound | brain host | none (a role default; `destructive` only in that it changes a server setting) | `gbrain doctor --only persistence_session_timeouts --json` |
| `gbrain init` or `gbrain upgrade` stops with `schema_lock_blocked` naming a pid (or, before #5227, sat in `wait_event_type=Lock` with no output) | let the named session finish, or with the user's agreement end it on the database host: `SELECT pg_terminate_backend(<pid>)`; then rerun the same command ([ENGINES.md](../ENGINES.md#schema-lock-blocked)) | brain host, after the user agrees | `destructive` when it ends another session | the rerun completes; `gbrain doctor --json` shows the schema at head |
| [`queue_capacity`, `persistence_capacity` or `persistence_request_growth`](#write-capacity) | run the printed `gbrain config set persistence.limits.<limit> <value>` | brain host | none | `gbrain doctor --only persistence_capacity,persistence_request_growth --json` |
@@ -10645,9 +10652,9 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).
-<a id="retry-other-options"></a>**`--retry-failed` lists failures that "belong to a run with different sync options"?** A managed retry resumes only the cursor its own options select; each other failure gets one line with its class and the command that settles it. `resumable (replay …)`: an unfinished run holds it, and the command resumes that run under its recorded options. `resumable (fresh discovery, not a replay …)`: no run holds it any more; the command starts a new run from HEAD under the failed run's options, which clears the failure when it completes. For a failure recorded before runs kept their options, the options are recovered only when an option set reproduces its cursor key exactly. `safely orphaned`: nothing current can resume it; preview `gbrain repair managed-sync-orphans --source <id>` and apply with the hash it prints. `unresolved`: its options were never recorded and nothing selects it; the line says what has to finish first (a request still in flight, or a current run whose completion lets the orphan repair retire it).
+<a id="retry-other-options"></a>**A sync (or the deprecated `--retry-failed` alias) lists failures that "belong to a run with different sync options"?** A managed retry resumes only the cursor its own options select; each other failure gets one line with its class and the command that settles it. `resumable (replay …)`: an unfinished run holds it, and the command resumes that run under its recorded options. `resumable (fresh discovery, not a replay …)`: no run holds it any more; the command starts a new run from HEAD under the failed run's options, which clears the failure when it completes. For a failure recorded before runs kept their options, the options are recovered only when an option set reproduces its cursor key exactly. `safely orphaned`: nothing current can resume it; preview `gbrain repair managed-sync-orphans --source <id>` and apply with the hash it prints. `unresolved`: its options were never recorded and nothing selects it; the line says what has to finish first (a request still in flight, or a current run whose completion lets the orphan repair retire it).
-<a id="checkpoint-validation-timeout"></a>**A managed sync is blocked with `checkpoint_validation_timeout`?** Run the printed commands on the brain host: `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …`. Doctor's `persistence_request_growth` warns before lifetime request IDs run out.
+<a id="checkpoint-validation-timeout"></a>**A managed sync is blocked with `checkpoint_validation_timeout`?** Run the printed commands on the brain host: `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull …`. Doctor's `persistence_request_growth` warns before lifetime request IDs run out.
<a id="pglite-aborted"></a>**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](../ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](../INSTALL.md#pglite-crashes-at-startup-runtimeerror-aborted).
diff --git a/plugin/skills/cron-scheduler/SKILL.md b/plugin/skills/cron-scheduler/SKILL.md
index 8bff955aad..6411917432 100644
--- a/plugin/skills/cron-scheduler/SKILL.md
+++ b/plugin/skills/cron-scheduler/SKILL.md
@@ -110,9 +110,11 @@ sources:
sync line. Any other detail means another host owns the source: install a
per-source line on that host (`gbrain sync --source <id> --no-pull
--hard-deadline 13m`, plus its refresh) instead of claiming it here.
-- Failed files: run the `--retry-failed` command the failure prints
- (`gbrain sync --source <id> --no-pull --retry-failed …`) after fixing the
- files; never add `--skip-failed`.
+- Failed files: after fixing the files and committing them, rerun the plain
+ `gbrain sync --source <id> --no-pull …` with the failed run's options; the
+ next sync retries what the last one recorded. Never add `--skip-failed`
+ (`--retry-failed` is a deprecated alias of the plain sync on a managed
+ brain).
`gbrain doctor` prints this managed line in `sync_consolidation` on a managed
brain with 2+ active sources.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 7ba1d75461..5727f80464 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli/main.ts 3010 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts
+src/cli/main.ts 3011 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated)
src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)
src/commands/doctor.ts 686 ratchet +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
src/core/config.ts 1985 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys)
-src/core/persistence/sync-run.ts 1745 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts)
+src/core/persistence/sync-run.ts 1756 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions
src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 707 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707
diff --git a/skills/cron-scheduler/SKILL.md b/skills/cron-scheduler/SKILL.md
index 025d92bc91..36a50c3a54 100644
--- a/skills/cron-scheduler/SKILL.md
+++ b/skills/cron-scheduler/SKILL.md
@@ -109,9 +109,11 @@ sources:
sync line. Any other detail means another host owns the source: install a
per-source line on that host (`gbrain sync --source <id> --no-pull
--hard-deadline 13m`, plus its refresh) instead of claiming it here.
-- Failed files: run the `--retry-failed` command the failure prints
- (`gbrain sync --source <id> --no-pull --retry-failed …`) after fixing the
- files; never add `--skip-failed`.
+- Failed files: after fixing the files and committing them, rerun the plain
+ `gbrain sync --source <id> --no-pull …` with the failed run's options; the
+ next sync retries what the last one recorded. Never add `--skip-failed`
+ (`--retry-failed` is a deprecated alias of the plain sync on a managed
+ brain).
`gbrain doctor` prints this managed line in `sync_consolidation` on a managed
brain with 2+ active sources.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 9462b04f67..78de0b6899 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -66,7 +66,7 @@
"conversation-archive/routing-eval.jsonl": "ae087a84b1fd5b108b7cdab8d035a09b3ccecd8aad53ba5f71e463059108cfca",
"correction-pipeline/SKILL.md": "c19869aa60ac00e15fc97ca016dd84dd63338fdf3d7b39990b33900eb7dcc703",
"correction-pipeline/routing-eval.jsonl": "7f8d96606a8d7bed3d79fdcee6904764c8abb9fa0b506adb414b5c4805b69d0b",
- "cron-scheduler/SKILL.md": "2d22d71ae746c2d7bbd76ff0a26c093f40d380823fc6ff6d5c763d258ff91a70",
+ "cron-scheduler/SKILL.md": "a89bfeb058034d5033c42d56b35297e5f33e28a6dac01860d5e033a10262b3a5",
"cross-modal-review/SKILL.md": "fc00a04e2ff9f498bee9b0b636bceba9dcfdc869c35d9a983109f408170f0807",
"daily-task-manager/SKILL.md": "e93264a83b5fd0a19b2f06a322b3a4ad92d418f6a968c1cd51f4bea79cbca4d9",
"daily-task-manager/routing-eval.jsonl": "e98b2592e65c26952242436a960d8b2061e375b269004a18c230cbcf1d692ff9",
diff --git a/src/cli/main.ts b/src/cli/main.ts
index ca0958f278..7356427f75 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -2438,6 +2438,7 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis
// #6340: `sync status` / `sync unblock` read and schedule on the brain's own engine: no watchdog, no serve delegation (a delegate would refuse the subcommand).
const syncOperator = command === 'sync' && (args[0] === 'status' || args[0] === 'unblock');
if (command === 'sync' && !syncOperator) {
+ (await import('../commands/sync/args.ts')).noteRetryFailedDeprecated(args);
try {
const { resolveSyncHardDeadline } = await import('../commands/sync.ts');
const res = resolveSyncHardDeadline(args, {
diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.ts
index 3e0245169c..d209324371 100644
--- a/src/commands/doctor/checks/sync-failures.ts
+++ b/src/commands/doctor/checks/sync-failures.ts
@@ -76,7 +76,7 @@ export async function checkSyncFailures(engine: BrainEngine | null, opts: { sour
const resumable = managed.filter(row => !orphanKeys.has(row.cursor_key));
const retries = [...new Set(resumable.map(row => managedSyncRetryCommand(row)))];
const recovery = requiresManagedRetry
- ? `${resumable.length || !orphans.length ? `Fix the cause, then run ${retries.length ? retries.join(' ; ') : 'gbrain sync --no-pull --retry-failed with the same source and options'}. Completed full runs do not resolve a different unfinished cursor.` : ''}${orphanNote}${unreadNote}`.trim()
+ ? `${resumable.length || !orphans.length ? `Fix the cause, then run ${retries.length ? retries.join(' ; ') : 'gbrain sync --no-pull with the same source and options (it retries the recorded failure)'}. Completed full runs do not resolve a different unfinished cursor.` : ''}${orphanNote}${unreadNote}`.trim()
: `Fix the file(s) and re-run 'gbrain sync', or use 'gbrain sync --skip-failed' to acknowledge legacy file failures.${orphanNote}${unreadNote}`;
const legacyNote = managedBrain ? legacyLedgerNote(unresolvedLegacy) : '';
// #6712 PR 2 (L5): each managed failure with the classifier's category and the public category beside it.
diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.ts
index 359455cd77..175f229cba 100644
--- a/src/commands/persistence-admin.ts
+++ b/src/commands/persistence-admin.ts
@@ -67,8 +67,8 @@ deactivate converts the whole brain back to classic mode (it takes no <source>):
--dry-run prints every blocker with its exit and what would change, and changes
nothing. It refuses while the writer admin lock is set or any request, effect,
recovery or connector/maintenance lease is pending, naming each blocker's exit
-(gbrain cancel-write-request <request_id>, gbrain sync --source <id> --no-pull
---retry-failed, gbrain repair embedding-effects --source <id>, gbrain sources
+(gbrain cancel-write-request <request_id>, gbrain sync --source <id> --no-pull,
+gbrain repair embedding-effects --source <id>, gbrain sources
writer retry-effects <source> --request-id <id> --dry-run, gbrain sources writer
unlock). It retires every worktree, removes source and host bindings, and keeps
canonical files and database pages. Its output and status report the database
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 83b61bd3c3..797e08ef14 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -19,7 +19,7 @@ export interface SyncResult {
failures?: ManagedSyncFailure[];
runId?: string;
managedWrite?: import('../core/persistence/sync-run.ts').ManagedSyncWriteDiagnostic;
- /** #6643: the request a `--retry-failed` rediscovery waits for (its producer and slug), instead of a silent no-op. */
+ /** #6643: the request a rediscovery that retries a recorded failure waits for (its producer and slug), instead of a silent no-op. */
retryWait?: import('../core/persistence/sync-run.ts').RetryWait;
/** #6712 PR 1: another drainer holds (or took) the source's drain lease; `resumable`, nothing admitted by this run. */
leaseHeld?: import('../core/persistence/sync-lease.ts').DrainLeaseHeld;
@@ -180,7 +180,7 @@ export interface SyncOpts {
logNoop?: boolean;
/** Bug 9 — acknowledge + skip past current failure set (CLI --skip-failed). */
skipFailed?: boolean;
- /** Bug 9 — re-attempt unacknowledged failures explicitly (CLI --retry-failed). */
+ /** CLI --retry-failed: a deprecated alias (#6712 PR 3); a plain sync retries a recorded failure. Connector syncs still read it. */
retryFailed?: boolean;
/** Managed connector sources: discard the connector checkpoint and re-walk the window once (CLI --reset-checkpoint). */
resetCheckpoint?: boolean;
diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.ts
index d05022b78a..c296013dc7 100644
--- a/src/commands/sync/args.ts
+++ b/src/commands/sync/args.ts
@@ -37,7 +37,66 @@ names, then 'gbrain sources retry-held <id>' and the same sync. Many such
stalls in one run stop it with outcome blocked / preparation_systemic.
'gbrain config set sync.holds fail' restores fail-closed blocking.
-Options:
+Managed brains (the flags an operator or cron needs; listed first):
+ --source <id> Scope sync to a single source. Defaults to the
+ brain's default source.
+ --all Sync every registered source instead of just the
+ default (multi-source brains).
+ --no-pull Skip 'git pull' before the sync. Implied on managed
+ brains, which never pull during sync: 'gbrain sources
+ refresh <id>' moves the checkout, and sync catches the
+ index up to it.
+ --timeout <dur> Stop the sync after <dur> (per source with --all).
+ A managed sync drains its whole backlog in one run
+ until it is done, blocked, or this budget ends;
+ progress never extends it. A stopped managed drain
+ is 'resumable' (exit 0): rerun the same command.
+ When another process is draining the source (a
+ serve, a sync job, another terminal), the run follows
+ it within this budget and its own deadline, printing
+ the holder and the pages it commits; it takes over
+ when the holder finishes. Out of budget it is
+ 'resumable' with code sync_drain_lease_held; a holder
+ that commits nothing for 5 minutes stops it blocked
+ (drain_stalled). Ctrl-C stops following and leaves
+ the holder alone.
+ See docs/guides/live-sync.md (catching up a large
+ backlog on managed Postgres).
+ --hard-deadline <dur>
+ Stop the whole process after <dur> (for example 13m),
+ even when a step hangs. Doctor's managed cron line is
+ 'gbrain sync --all --no-pull --hard-deadline 13m'
+ every 15 minutes. A non-TTY run gets a default
+ deadline that extends while pages keep committing;
+ --no-hard-deadline waives it.
+ --json Emit a structured JSON envelope on stdout
+ ({schema_version: 1, sources, parallel,
+ ok_count, error_count, skipped_count}). Sources
+ skipped by --missing-path skip appear with
+ status 'skipped_missing_path' and their
+ local_path. All human output routes to stderr
+ (single-source runs too) so '--json | jq'
+ parses cleanly.
+ Exit codes: 0 = all sources ok or skipped,
+ 1 = any error, 2 = cost-prompt-not-confirmed.
+ Managed syncs add outcome (synced | resumable |
+ blocked), drain and next {command, safe_to_loop,
+ eta_seconds, why}.
+ --dry-run Show what would be synced without writing; lists
+ every file the content screen would hold (would_hold)
+ and screen errors separately (screen_skipped).
+ --no-bulk Managed Postgres sync: publish one page per transaction
+ instead of bulk groups (each page keeps its own write
+ request either way). GBRAIN_SYNC_BULK=0 does the
+ same for every run of a process; tune the group size
+ with 'gbrain config set sync.bulk_size N'.
+ --no-lanes Same as --lanes 1: one bulk group at a time.
+ --break-lock Release the source's sync lock (the managed drain
+ lease) left by a holder that is gone: a dead pid on
+ this host, or a heartbeat past its TTL. A live holder
+ is never broken; --max-age <s> narrows it.
+
+Classic brains / advanced (classic sync, processing opt-outs, one-off repair):
--no-embed Skip the embed step. Use this when the embed
provider is misconfigured or you want to defer
embedding (run 'gbrain embed --stale' later).
@@ -47,8 +106,6 @@ Options:
--workers N Run the import phase with N parallel workers
(alias: --concurrency). Default: 4 when the
diff is >100 files, else serial.
- --source <id> Scope sync to a single source. Defaults to the
- brain's default source.
--repo <path> Path to the brain repo. Defaults to the path
saved by 'gbrain init'.
--full Force a full re-sync (rare; usually incremental).
@@ -81,44 +138,32 @@ Options:
Caution: imports untracked files as-is — unignored
scratch files and secrets included; review 'git status'
before enabling, especially as persisted config.
- --dry-run Show what would be synced without writing; lists
- every file the content screen would hold (would_hold)
- and screen errors separately (screen_skipped).
- --skip-failed Legacy sync only: acknowledge previously-recorded
+ --skip-failed Classic sync only: acknowledge previously-recorded
sync failures so the bookmark can advance. Held files
never need it; a managed source refuses it
(managed_sync_flag_refused), as it does
- --include-gitignored.
+ --include-gitignored: fix the file, then run the
+ plain sync again.
--acknowledge-managed <request_id|path>
Managed sync, owner host only: remove a recorded
failure (for example a --full run's) that the imported
commit already settles; refuses anything still unsynced.
- --retry-failed Re-attempt previously-failed files; clear on success.
- Not needed for held files, which re-screen on the next
- sync when they change (or with 'gbrain sources
- retry-held <id>'). On a managed source, failures held
- under another run's options are listed with the action
- that settles each: a replay or fresh discovery under
- their options, the orphan repair, or what is unresolved.
+ --retry-failed Deprecated: accepted for two releases and prints a
+ coaching notice. A plain sync now retries a failure
+ the previous run recorded by itself, so drop the
+ flag. Held files re-screen on the next sync when they
+ change (or with 'gbrain sources retry-held <id>'). On
+ a google or github connector source it still
+ re-approves the failed item receipts it meets.
--reset-checkpoint Connector source only: re-walk its window once from an empty
checkpoint; unchanged pages are not admitted again.
--watch Re-sync continuously on an interval.
--interval N Watch-mode interval in seconds (default 60).
- --no-pull Skip 'git pull' before the sync. Implied on managed
- brains, which never pull during sync: 'gbrain sources
- refresh <id>' moves the checkout, and sync catches the
- index up to it.
- --no-bulk Managed Postgres sync: publish one page per transaction
- instead of bulk groups (each page keeps its own write
- request either way). GBRAIN_SYNC_BULK=0 does the
- same for every run of a process; tune the group size
- with 'gbrain config set sync.bulk_size N'.
--lanes N Managed Postgres sync: publish at most N bulk groups at
once (1-16, default 16, capped by the connection pool:
GBRAIN_POOL_SIZE minus 4). Pages still commit in file
order. Persist with 'gbrain config set sync.lanes N' or
GBRAIN_SYNC_LANES; the drain reports what limited it.
- --no-lanes Same as --lanes 1: one bulk group at a time.
--no-delegate Keep this process's own write consumer even when a
live 'gbrain serve' could run the sync. Normally sync
hands the run to that serve over its IPC socket and
@@ -129,18 +174,12 @@ Options:
sync runs here beside the serve; on PGLite it fails
fast if a live serve holds the brain. It never skips
the drain lease: one drainer per managed source.
- --break-lock Release the source's sync lock (the managed drain
- lease) left by a holder that is gone: a dead pid on
- this host, or a heartbeat past its TTL. A live holder
- is never broken; --max-age <s> narrows it.
--force-break-lock Release it without the liveness check (destructive:
only when you have stopped the holder yourself).
--no-schema-pack Skip loading the active schema pack (no per-file pack
regex runs; pages use legacy prefix typing). Escape
hatch if a suspect pack regex is wedging sync.
GBRAIN_SYNC_TRACE=1 names the file being imported (hang triage).
- --all Sync every registered source instead of just the
- default (multi-source brains).
--parallel N (with --all) Run up to N sources concurrently.
Default: min(sourceCount, --workers, 4). Each
source takes its own per-source DB lock
@@ -156,35 +195,6 @@ Options:
from error_count and the rc=1 gate). Use skip on
brains whose sources were registered from more
than one machine.
- --json Emit a structured JSON envelope on stdout
- ({schema_version: 1, sources, parallel,
- ok_count, error_count, skipped_count}). Sources
- skipped by --missing-path skip appear with
- status 'skipped_missing_path' and their
- local_path. All human output routes to stderr
- (single-source runs too) so '--json | jq'
- parses cleanly.
- Exit codes: 0 = all sources ok or skipped,
- 1 = any error, 2 = cost-prompt-not-confirmed.
- Managed syncs add outcome (synced | resumable |
- blocked), drain and next {command, safe_to_loop,
- eta_seconds, why}.
- --timeout <dur> Stop the sync after <dur> (per source with --all).
- A managed sync drains its whole backlog in one run
- until it is done, blocked, or this budget ends;
- progress never extends it. A stopped managed drain
- is 'resumable' (exit 0): rerun the same command.
- When another process is draining the source (a
- serve, a sync job, another terminal), the run follows
- it within this budget and its own deadline, printing
- the holder and the pages it commits; it takes over
- when the holder finishes. Out of budget it is
- 'resumable' with code sync_drain_lease_held; a holder
- that commits nothing for 5 minutes stops it blocked
- (drain_stalled). Ctrl-C stops following and leaves
- the holder alone.
- See docs/guides/live-sync.md (catching up a large
- backlog on managed Postgres).
--yes Accept any interactive prompts (CI / non-TTY).
Subcommands:
@@ -215,6 +225,18 @@ See also:
`);
}
+/** #6712 PR 3 (L7): the coaching notice `--retry-failed` prints while it stays accepted (two releases). */
+export const RETRY_FAILED_DEPRECATED = '--retry-failed is deprecated: a plain gbrain sync now retries a failure the previous run recorded by itself, '
+ + 'so drop the flag (it stays accepted for two releases and changes nothing on a Git source). On a google or github connector source it still '
+ + 're-approves the failed item receipts it meets.';
+let retryFailedNoted = false;
+/** Prints the `--retry-failed` coaching notice on stderr, once per process (the CLI pipeline and the sync command both call it). */
+export function noteRetryFailedDeprecated(args: string[]): void {
+ if (retryFailedNoted || !args.includes('--retry-failed')) return;
+ retryFailedNoted = true;
+ process.stderr.write(`[gbrain notice sync_retry_failed_deprecated] ${RETRY_FAILED_DEPRECATED}\n`);
+}
+
/** Flags read before the `--break-lock` branch. */
/** setTimeout treats delays above 2^31-1 ms as ~1 ms; --interval stays within that bound. */
const MAX_WATCH_INTERVAL_SECONDS = Math.floor(2_147_483_647 / 1000);
diff --git a/src/commands/sync/report.ts b/src/commands/sync/report.ts
index e635a82b23..1ad9cdf271 100644
--- a/src/commands/sync/report.ts
+++ b/src/commands/sync/report.ts
@@ -129,7 +129,7 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = p
const retries = [...new Set((result.failures ?? []).map(failure => managedSyncRetryCommand(failure)))];
write(retries.length
? ` Fix the cause, then run: ${retries.join(' ; ')} (this admits a fresh run after active work drains).`
- : ' Fix the cause, then run gbrain sync --no-pull --retry-failed with the same source and options; this admits a fresh run after active work drains.');
+ : ' Fix the cause, then run gbrain sync --no-pull with the same source and options; it retries the recorded failure and admits a fresh run after active work drains.');
break;
}
write(`Sync BLOCKED at ${result.toCommit.slice(0, 8)}: ${result.failedFiles ?? 0} file(s) failed.`);
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index 7e2f857a6d..1643d9e8b7 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -22,7 +22,7 @@ import { automaticSyncSkip, isSyncDisabledConfig } from '../../core/sync-policy.
import { composeAbortSignals } from '../../core/sync-reconcile.ts';
import { acknowledgeFailures, unacknowledgedSyncFailures } from '../../core/sync.ts';
import type { SyncResult, SyncOpts } from '../sync.ts';
-import { printSyncHelp, parseSyncFlags, parseSyncFanoutFlags } from './args.ts';
+import { printSyncHelp, parseSyncFlags, parseSyncFanoutFlags, noteRetryFailedDeprecated } from './args.ts';
import { implyManagedNoPull, refuseManagedForbiddenFlags } from './managed-no-pull.ts';
import { legacyLedgerRows } from '../../core/persistence/legacy-sync-failures.ts';
import type { SyncFlags, SyncFanoutFlags } from './args.ts';
@@ -108,6 +108,7 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {
if (args.includes('--acknowledge-managed')) return runAcknowledgeManaged(engine, args);
const flags = parseSyncFlags(args);
+ noteRetryFailedDeprecated(args);
const { repoPath, dryRun, skipFailed, syncAll, jsonOut, breakLock, forceBreakLock, maxAgeSeconds } = flags;
let { noEmbed } = flags;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 83ffa4ae98..c5e65f63de 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -18,7 +18,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--prefer-postgres', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--url', '--yes'],
- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 0aaffc06f6..bcc321d79a 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -357,7 +357,7 @@ export const CODES = {
managed_sync_flag_refused: { class: 'caller', summary: "A managed source refuses --skip-failed and --include-gitignored: managed sync keeps every failed-receipt and ignored-file guard, so the run was refused before anything ran.",
why: "--skip-failed would acknowledge a failed receipt instead of retrying it, and --include-gitignored would import files Git ignores; neither has a managed meaning. `detail` names the flag.",
docs: 'docs/guides/write-refusals.md#managed_sync_flag_refused',
- suggestion: 'Rerun the same gbrain sync command without the named flag; fix a failed file and retry it with --retry-failed, or commit an ignored file to sync it.',
+ suggestion: 'Rerun the same gbrain sync command without the named flag; fix a failed file and the plain sync retries it, or commit an ignored file to sync it.',
fix: { argv: ['gbrain', 'sources', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists each source with its recorded failures and held files, the work the refused flag would have skipped.',
verify: { argv: ['gbrain', 'sources', 'status', '--json'] } } },
managed_pull_skipped: { class: 'retryable', summary: "The managed pull was skipped." },
@@ -404,7 +404,7 @@ export const CODES = {
page_shrink_refused: { class: 'caller', summary: "put_page refused to replace a large page with content much smaller than the stored body; nothing was written.", why: "Above the inline read size (mcp.inline_body_bytes, 256 KB) a get_page read returns a window, not the body, so a replacement far smaller than the page is most often a window sent back as the whole page, which would delete the unread rest.", docs: 'docs/guides/windowed-reads.md#page_shrink_refused', suggestion: "Change part of the page with edit_page (revision from get_page body: 'none'). Pass allow_shrink: true only when the smaller content is the intended complete page.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body; edit_page with that revision changes only the text it names.", requires_exclusive: false } },
page_too_large_for_inline: { class: 'caller', summary: "The whole page does not fit one result on this connection, so get_page did not return its body.", why: "A result is measured as the complete encoded frame; a body over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be cut or rejected by the client. Nothing was truncated: windowed reads cover the whole page in pieces.", docs: 'docs/guides/windowed-reads.md#page_too_large_for_inline', legacy_error: 'invalid_params', suggestion: "Read the outline (body: 'outline'), then windows (body: 'window' with lines, bytes, around_chunk_id or the returned next_cursor). To replace the page, edit it with edit_page and the revision from body: 'none'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.", requires_exclusive: false, verify: { mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } } } } },
parse_error: { class: 'caller', summary: "The request body is not valid JSON." },
- parser_regression: { class: 'server', summary: "A file whose exact bytes imported before is now refused by gbrain's frontmatter reader.", why: "The same bytes imported under an earlier gbrain version, so only gbrain changed; with `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs, such a file is held and the rest of the sync continues.", suggestion: 'Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again with --retry-failed.' },
+ parser_regression: { class: 'server', summary: "A file whose exact bytes imported before is now refused by gbrain's frontmatter reader.", why: "The same bytes imported under an earlier gbrain version, so only gbrain changed; with `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs, such a file is held and the rest of the sync continues.", suggestion: 'Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again.' },
pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },
payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },
pattern_claims_pending: { class: 'retryable', summary: "An existing pattern page is waiting on the rewrite that de-duplicates its claim sources, so no patterns child was submitted this run.", why: "The patterns child reads existing pattern pages; until their claim records reference one shared reflection list, the pages can overflow the model's window and the run pays for nothing.", fix: { argv: ['gbrain', 'write-requests', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Lists the write receipts of the source, newest first, so the held rewrites show, read-only.', requires_exclusive: false } },
@@ -529,7 +529,7 @@ export const CODES = {
slug_root_mode_mismatch: { class: 'caller', actor: 'user',
summary: "A managed sync of a subdirectory source ran under one slug-root mode while the source pins the other (sources.config.slug_root_mode), so its checkpoint did not advance.",
why: "At a subdirectory the two modes give different slugs (git-root keeps the subdirectory prefix, source-root does not), and the pin exists so a later sync never re-namespaces the source; the pages this run wrote already carry its mode. The pin changed after the run was discovered. A source rooted at its repository root never gets this code: both modes give it identical slugs, and its checkpoint keeps the pin it has. Older releases reported this refusal as revision_conflict.",
- suggestion: 'Ask the user which mode the source keeps. To keep the mode the run used, set sources.config.slug_root_mode back to it and run gbrain sync --no-pull --source <id>; the refused checkpoint is retried by itself. To keep the new pin, run gbrain sync --no-pull --source <id> --retry-failed, which discovers the source again under it; the pages the refused run wrote keep their old slugs beside the new ones.',
+ suggestion: 'Ask the user which mode the source keeps. To keep the mode the run used, set sources.config.slug_root_mode back to it and run gbrain sync --no-pull --source <id>; the refused checkpoint is retried by itself. To keep the new pin, preview gbrain repair managed-sync-orphans --source <id> (it lists the refused cursor as slug_mode_refused), apply it with the hash it prints, and run gbrain sync --no-pull --source <id>, which discovers the source again under the pin; the pages the refused run wrote keep their old slugs beside the new ones.',
fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'user', requires_exclusive: false,
why: 'Read-only: last_error names the pinned mode and the mode the run used; the choice between them is the user\'s.' } },
source_binding_required: { class: 'caller', summary: "A write needs an explicit source binding on this MCP server (--source-guard)." },
@@ -569,9 +569,9 @@ export const CODES = {
suggestion: 'Follow the check fix: it waits, inspects holds (gbrain sync status --source <id> --json) or retries (gbrain sync --source <id>) depending on the state.' },
// wave 16 (GBRA-79) #6513: a managed-sync checkpoint whose cursor another run of the source replaced.
sync_cursor_replaced: { class: 'caller', summary: "Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish.",
- why: "The replacing run (a --retry-failed rediscovery or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict.",
+ why: "The replacing run (a rediscovery that retried a recorded failure, or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict.",
suggestion: 'Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source.' },
- sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed.' },
+ sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull.' },
tail_exposure_approval: { class: 'caller', summary: "A fence on a world-visible page has no end marker and prose follows its table; closing it after the last row is safe for the table but makes those lines visible to remote readers, so the content-repair lane previews the close and waits for a hash-bound approval instead of applying it unattended.", why: "Everything after an unpaired begin marker is hidden by the privacy boundary. The repair model read the tail as prose (not rows), so the only judgment left is whether those exact lines may become visible, and that is the user's: the preview prints them and the hash binds them. On a private page nothing new is disclosed and the lane closes the fence by itself.", actor: 'user', docs: 'docs/guides/write-refusals.md#tail_exposure_approval', suggestion: 'Show the user the preview\'s exposed lines (gbrain repair content --source <id> --only <path>, read-only), then run the printed gbrain repair content --source <id> --only <path> --apply --expect <hash> only after they agree; a changed tail invalidates the hash. By hand: add the end marker directly after the last table row and move the trailing text where it belongs, commit, then gbrain sync --source <id> --no-pull.' },
take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },
target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },
@@ -672,6 +672,7 @@ export const NOTICE_CODES = {
first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run decisions (search mode, writeback, harness wiring, skills) carry defaults the user may change. The one muteable ask.' },
first_run_decisions_muted: { kind: 'info', summary: 'First-run decisions are still open, but the user muted them; the fix shows them again (`gbrain notices unmute first_run_decisions`).' },
migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },
+ sync_retry_failed_deprecated: { kind: 'coaching', summary: '`gbrain sync --retry-failed` is a deprecated alias for a plain sync, accepted for two releases: a plain sync retries a failure the previous run recorded by itself. Drop the flag.' },
sync_tail_degraded: { kind: 'degraded', summary: 'A managed sync ended synced, but its post-checkpoint tail (planner statistics, link extraction for the imported pages) failed, was cut off at its budget or did not start before the run\'s deadline; the step stays scheduled for the next sync, and the fix runs it now (`gbrain extract --stale --source-id <id>`, or doctor for the statistics).' },
no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
diff --git a/src/core/minions/handlers/sync-retry-failed.ts b/src/core/minions/handlers/sync-retry-failed.ts
index a1afcdbb37..87fd438a25 100644
--- a/src/core/minions/handlers/sync-retry-failed.ts
+++ b/src/core/minions/handlers/sync-retry-failed.ts
@@ -7,7 +7,8 @@ import type { MinionHandler } from '../types.ts';
export function makeSyncRetryFailedHandler(engine: BrainEngine): MinionHandler {
return async () => {
const { runSync } = await import('../../../commands/sync.ts');
- await runSync(engine, ['--retry-failed']);
+ // #6712 PR 3 (L7): a plain sync retries recorded failures; the job name stays for queued jobs and doctor's remediation.
+ await runSync(engine, []);
return { ok: true };
};
}
diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.ts
index 4ec0835e47..5f5faf1a5f 100644
--- a/src/core/persistence/checkpoint-validation.ts
+++ b/src/core/persistence/checkpoint-validation.ts
@@ -128,9 +128,12 @@ export async function readRequestIndexStates(engine: Pick<BrainEngine, 'executeR
const shellWord = (value: string) => /^[\w./@:=+-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
-/** The exact retry for the failed checkpoint: same source and cursor-selecting options, plus the recorded processing flags. */
+/**
+ * The exact retry for the failed run: the same source and discovery options, plus the recorded processing flags. #6712
+ * PR 3 (L7): a plain sync retries a recorded failure by itself, so the command carries no retry flag.
+ */
export function checkpointRetryCommand(input: { sourceId: string; processingOptions?: Partial<SyncProcessingOptions> | null; syncOptions?: SyncCursorOptions | null; repoPath?: string | null }): string {
- const base = `gbrain sync --source ${shellWord(input.sourceId)} --no-pull --retry-failed`;
+ const base = `gbrain sync --source ${shellWord(input.sourceId)} --no-pull`;
// A compacted receipt (intent cleared) or a checkpoint admitted before the options were recorded
// cannot name its cursor; never print assumed defaults for it.
if (!input.syncOptions) return `${base} with the same options as the failed run (this receipt no longer records them)`;
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index 10b4c7c4f7..9622d2710b 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -98,7 +98,7 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
blockers.push({ kind: 'request', id: r.request_id, source_id: r.source_id, detail: `${r.operation} ${r.state}${r.recovering ? ', recovering' : ''} (${r.source_id}:${r.slug})`,
exit: r.state === 'queued' && !r.recovering ? `gbrain cancel-write-request ${r.request_id} (MCP: cancel_write_request), or wait for the owner to publish it`
: r.state === 'running' && !r.recovering ? 'wait for the owner to finish publishing it, then rerun deactivate'
- : `gbrain sync --source ${r.source_id} --no-pull --retry-failed` });
+ : `gbrain sync --source ${r.source_id} --no-pull` });
}
const topology = await engine.executeRaw<{ id: string; operation: string; source_id: string }>(
"SELECT id::text AS id, operation, source_id FROM persistence_topology_changes WHERE state='recovering' OR recovery IS NOT NULL ORDER BY created_at LIMIT 20");
diff --git a/src/core/persistence/graduation-drain.ts b/src/core/persistence/graduation-drain.ts
index 90a4d25bc4..143edf32ac 100644
--- a/src/core/persistence/graduation-drain.ts
+++ b/src/core/persistence/graduation-drain.ts
@@ -43,7 +43,7 @@ export async function graduationBlockers(source: BrainEngine, hostId: string): P
blockers.push({ kind: 'foreign_host_binding', id: r.request_id, detail: `${detail} is bound to a worktree owned by host ${r.owner_host_id}`,
argv: ['gbrain', 'sources', 'writer', 'transfer', 'prepare', r.source_id], needsUser: true });
} else if (r.recovering || r.state === 'recovering') {
- blockers.push({ kind: 'request', id: r.request_id, detail, argv: ['gbrain', 'sync', '--source', r.source_id, '--no-pull', '--retry-failed'], needsUser: false });
+ blockers.push({ kind: 'request', id: r.request_id, detail, argv: ['gbrain', 'sync', '--source', r.source_id, '--no-pull'], needsUser: false });
} else {
blockers.push({ kind: 'request', id: r.request_id, detail, needsUser: false });
}
diff --git a/src/core/persistence/managed-sync-flags.ts b/src/core/persistence/managed-sync-flags.ts
index 180654e773..8dca7778b3 100644
--- a/src/core/persistence/managed-sync-flags.ts
+++ b/src/core/persistence/managed-sync-flags.ts
@@ -13,7 +13,7 @@ import { shellQuote } from '../agent-output.ts';
export type ManagedForbiddenFlag = '--skip-failed' | '--include-gitignored';
const WHY: Record<ManagedForbiddenFlag, string> = {
- '--skip-failed': 'A managed sync never acknowledges a failed receipt to move past it: fix the file, then retry it with --retry-failed.',
+ '--skip-failed': 'A managed sync never acknowledges a failed receipt to move past it: fix the file, and the plain sync retries it.',
'--include-gitignored': 'A managed sync imports only files Git tracks and does not ignore: commit the file, or change .gitignore, to sync it.',
};
diff --git a/src/core/persistence/managed-sync-orphans.ts b/src/core/persistence/managed-sync-orphans.ts
index 810759e4e1..6a02fdf4d4 100644
--- a/src/core/persistence/managed-sync-orphans.ts
+++ b/src/core/persistence/managed-sync-orphans.ts
@@ -26,6 +26,10 @@
* or an older binary, checkpointed the source elsewhere). The checkpoint can never publish and no resume clears it;
* retiring the cursor lets the next sync discover from the commit the source now records. A cursor whose source
* already stands at its target is not one: the next sync finishes it (sync-slug-mode.ts `checkpointMovedToTarget`).
+ * - `slug_mode_refused` (#6712 PR 3): an unfinished cursor whose every page committed and whose checkpoint was refused
+ * `slug_root_mode_mismatch` while the source still pins the other mode. Which mode the source keeps is a person's
+ * decision, so no sync rediscovers it by itself; retiring the cursor is how they keep the pin: the next sync discovers
+ * the source again under it. Setting the pin back instead lets the next sync retry the checkpoint by itself.
* - `mirror_only` (#6518): a row of the local compatibility ledger
* (`~/.gbrain/sync-failures.jsonl`) carrying a `managed_cursor_key` with no
* durable `managed-sync-failure` row under that key in any incarnation. The
@@ -47,7 +51,7 @@ import { clearSyncSlice } from './sync-slices.ts';
import type { SyncCursorOptions } from './sync-prepare.ts';
/** `superseded_by_adoption` (#6712 PR 1): an unfinished cursor of the incarnation that the drain's fan-in did not adopt (sync-cursor-key.ts). */
-export type ManagedSyncOrphanReason = 'no_cursor' | 'principal_unadoptable' | 'superseded' | 'incarnation_retired' | 'mirror_only' | 'superseded_by_adoption' | 'checkpoint_moved';
+export type ManagedSyncOrphanReason = 'no_cursor' | 'principal_unadoptable' | 'superseded' | 'incarnation_retired' | 'mirror_only' | 'superseded_by_adoption' | 'checkpoint_moved' | 'slug_mode_refused';
export type ManagedSyncOrphanRetained = 'pending_request_live' | 'resumable';
export interface ManagedSyncOrphan {
@@ -77,7 +81,7 @@ interface CursorRow {
cursor_key: string; source_id: string; source_incarnation: string; run_id: string | null;
principal_kind: string | null; principal_id: string | null; has_sync_options: boolean;
pending_request_id: string | null; pending_state: string | null;
- principal_live: boolean; superseded: boolean; checkpoint_moved: boolean; updated_at: string;
+ principal_live: boolean; superseded: boolean; checkpoint_moved: boolean; slug_mode_refused: boolean; updated_at: string;
}
/**
@@ -96,6 +100,18 @@ const checkpointMovedSql = (msg: string) => `(c.completed_keys->0->'pending'->'i
AND NOT EXISTS(SELECT 1 FROM persistence_requests o WHERE o.source_id=s.id AND o.intent->>'cursorKey'=c.fingerprint
AND (o.state IN ('queued','running','recovering') OR o.recovery IS NOT NULL)))`;
+/**
+ * #6712 PR 3: the cursor `c` (of source `s`) stands at its checkpoint, refused `slug_root_mode_mismatch`, and the source
+ * still pins a mode other than the run's. Shared by the classification and the retirement's re-check.
+ */
+const slugModeRefusedSql = `(c.completed_keys->0->'pending'->'intent'->>'kind'='managed_sync_checkpoint' AND c.completed_keys->0->>'companyReceiptId' IS NULL
+ AND (c.completed_keys->0->>'index')::int>=(c.completed_keys->0->>'total')::int
+ AND s.config->>'slug_root_mode' IS NOT NULL AND s.config->>'slug_root_mode' IS DISTINCT FROM c.completed_keys->0->>'slugMode'
+ AND EXISTS(SELECT 1 FROM persistence_requests m WHERE m.source_id=s.id AND m.request_id=(c.completed_keys->0->'pending'->>'requestId')::uuid
+ AND m.state IN ('failed','conflict') AND m.recovery IS NULL AND m.error_code='slug_root_mode_mismatch')
+ AND NOT EXISTS(SELECT 1 FROM persistence_requests o WHERE o.source_id=s.id AND o.intent->>'cursorKey'=c.fingerprint
+ AND (o.state IN ('queued','running','recovering') OR o.recovery IS NOT NULL)))`;
+
/** Read-only. `sourceIds` narrows to those sources; null reads every active source. */
export async function classifyManagedSyncOrphans(engine: SqlEngine, sourceIds: string[] | null = null): Promise<ManagedSyncOrphanClassification> {
const cursors = await engine.executeRaw<CursorRow>(`
@@ -111,6 +127,7 @@ export async function classifyManagedSyncOrphans(engine: SqlEngine, sourceIds: s
AND n.completed_keys->0->>'sourceId'=s.id AND n.completed_keys->0->>'incarnation'=s.incarnation::text
AND COALESCE(n.completed_keys->0->>'done','false')='true' AND n.updated_at>c.updated_at) AS superseded,
${checkpointMovedSql('$2')} AS checkpoint_moved,
+ ${slugModeRefusedSql} AS slug_mode_refused,
to_char(c.updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS updated_at
FROM op_checkpoints c
JOIN sources s ON s.id=c.completed_keys->0->>'sourceId' AND s.incarnation::text=c.completed_keys->0->>'incarnation' AND NOT COALESCE(s.archived,false)
@@ -127,7 +144,7 @@ export async function classifyManagedSyncOrphans(engine: SqlEngine, sourceIds: s
const principal = row.principal_kind && row.principal_id ? { kind: row.principal_kind, id: row.principal_id } : null;
if (row.pending_request_id && row.pending_state && !TERMINAL.includes(row.pending_state)) { retained.push({ cursor_key: row.cursor_key, source_id: row.source_id, why: 'pending_request_live' }); continue; }
const reason: ManagedSyncOrphanReason | null = !row.principal_live ? 'principal_unadoptable' : !row.has_sync_options && row.superseded ? 'superseded'
- : row.checkpoint_moved ? 'checkpoint_moved' : null;
+ : row.checkpoint_moved ? 'checkpoint_moved' : row.slug_mode_refused ? 'slug_mode_refused' : null;
if (!reason) { retained.push({ cursor_key: row.cursor_key, source_id: row.source_id, why: 'resumable' }); continue; }
orphans.push({ kind: 'unfinished_cursor', cursor_key: row.cursor_key, source_id: row.source_id, source_incarnation: row.source_incarnation, run_id: row.run_id,
principal, pending_request_id: row.pending_request_id, pending_state: row.pending_state, reason, updated_at: row.updated_at });
@@ -237,12 +254,14 @@ export async function pruneMirrorOnlyManagedFailures(engine: SqlEngine, sourceId
* its checkpoint is still the refused one, the source still records a commit other than its start and target, and no
* request under its key is open or carries recovery. It is bound to the previewed run and checkpoint request, so a run
* that replaced the cursor under the same key since the preview is kept, and a path slice's record is cleared with it.
+ * A `slug_mode_refused` cursor (#6712 PR 3) is retired under the same binding while `slugModeRefusedSql` still holds.
*/
export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<ManagedSyncOrphan, 'kind' | 'cursor_key' | 'run_id' | 'source_id' | 'source_incarnation' | 'reason'>
& { pending_request_id?: string | null },
inTx?: (tx: BrainEngine) => Promise<void>): Promise<{ cursor: boolean; failure: boolean; manifest: boolean; mirror: boolean }> {
const retired = orphan.reason === 'incarnation_retired';
- const mode = retired ? 'retired' : orphan.reason === 'superseded_by_adoption' ? 'adoption' : orphan.reason === 'checkpoint_moved' ? 'checkpoint_moved' : 'orphan';
+ const mode = retired ? 'retired' : orphan.reason === 'superseded_by_adoption' ? 'adoption' : orphan.reason === 'checkpoint_moved' ? 'checkpoint_moved'
+ : orphan.reason === 'slug_mode_refused' ? 'slug_mode_refused' : 'orphan';
if (orphan.kind === 'mirror_row') {
const durable = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1", [orphan.cursor_key]);
if (durable.length) return { cursor: false, failure: false, manifest: false, mirror: false };
@@ -265,6 +284,9 @@ export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<
OR $4::text='checkpoint_moved' AND c.completed_keys->0->>'runId' IS NOT DISTINCT FROM $6::text
AND c.completed_keys->0->'pending'->>'requestId' IS NOT DISTINCT FROM $7::text
AND EXISTS(SELECT 1 FROM sources s WHERE s.id=$2 AND s.incarnation::text=$3 AND NOT COALESCE(s.archived,false) AND ${checkpointMovedSql('$5')})
+ OR $4::text='slug_mode_refused' AND c.completed_keys->0->>'runId' IS NOT DISTINCT FROM $6::text
+ AND c.completed_keys->0->'pending'->>'requestId' IS NOT DISTINCT FROM $7::text
+ AND EXISTS(SELECT 1 FROM sources s WHERE s.id=$2 AND s.incarnation::text=$3 AND NOT COALESCE(s.archived,false) AND ${slugModeRefusedSql})
OR $4::text='orphan' AND NOT EXISTS(SELECT 1 FROM persistence_local_writers w WHERE w.revoked_at IS NULL
AND w.id::text=c.completed_keys->0->'authority'->'writer'->'principal'->>'id'
AND c.completed_keys->0->'authority'->'writer'->'principal'->>'kind' IN ('local_cli','local_stdio')
@@ -275,7 +297,7 @@ export async function retireManagedSyncOrphan(engine: BrainEngine, orphan: Pick<
if (!cursor) return { cursor: false, failure: false, manifest: false, mirror: false };
// #6834: a retired path slice's record goes with it, so the next discovery starts from the recorded commit instead of resuming that slice.
const intent = (rows[0] as { intent?: { slice?: { target?: string }; syncOptions?: SyncCursorOptions } | null }).intent;
- if (mode === 'checkpoint_moved' && intent?.slice?.target && intent.syncOptions) await clearSyncSlice(tx, orphan.source_id, orphan.source_incarnation!, intent.syncOptions, intent.slice.target);
+ if ((mode === 'checkpoint_moved' || mode === 'slug_mode_refused') && intent?.slice?.target && intent.syncOptions) await clearSyncSlice(tx, orphan.source_id, orphan.source_incarnation!, intent.syncOptions, intent.slice.target);
}
const failure = (await tx.executeRaw(`DELETE FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=$1
AND NOT EXISTS(SELECT 1 FROM op_checkpoints c WHERE c.op='managed-sync' AND c.fingerprint=$1
diff --git a/src/core/persistence/sync-checkpoint-replaced.ts b/src/core/persistence/sync-checkpoint-replaced.ts
index 56730d26c7..9f370eddda 100644
--- a/src/core/persistence/sync-checkpoint-replaced.ts
+++ b/src/core/persistence/sync-checkpoint-replaced.ts
@@ -1,7 +1,7 @@
/**
* #6513 (wave 16 G3.4): a managed-sync checkpoint whose cursor another run of the same source replaced.
*
- * The replacing run (`--retry-failed` rediscovery, a newer sync of the source) re-covers the source from its own
+ * The replacing run (a rediscovery that retries a recorded failure, a newer sync of the source) re-covers the source from its own
* discovery, so the superseded checkpoint has nothing left to publish: its refusal is `sync_cursor_replaced` (receipt
* state `conflict`), it records no managed-sync failure, and the run that awaited it goes on with the winning cursor.
* A same-run index lag keeps `revision_conflict`, a missing manifest keeps `storage_error`, and a page request whose
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 637b0e20ff..bd239e4310 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -487,7 +487,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const unownedDeletion = foreignOrigin && entry.action === 'delete' && !origin && !company;
if (foreignOrigin && !unownedDeletion) {
const error = new OperationError('page_identity_changed', 'A different origin occupies the imported slug.',
- `Page ${slug} in source ${sourceId} records the origin '${page.source_path}', but sync found it at '${entry.sourcePath}'. On the brain host, rename or move one of the two files so each page has one origin, commit, then run gbrain sync --source ${sourceId} --no-pull --retry-failed.`);
+ `Page ${slug} in source ${sourceId} records the origin '${page.source_path}', but sync found it at '${entry.sourcePath}'. On the brain host, rename or move one of the two files so each page has one origin, commit, then run gbrain sync --source ${sourceId} --no-pull.`);
error.detail = 'sync_origin_mismatch';
throw error;
}
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 35a5f5ee35..60f05fc253 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -1028,9 +1028,8 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: s
: `The source's writer needs intervention (${d!.stop_reason}) before more pages can publish. Inspect it, fix what it names, then rerun: ${resumeCommand}`,
...(d!.stop_reason === 'drain_stalled' ? { code: 'drain_stalled', cause: d!.stall?.cause } : {}), ...(docs ? { docs } : {}) };
}
- const retry = resumeCommand.includes(' --retry-failed') ? resumeCommand : `${resumeCommand} --retry-failed`;
- return { command: retry, safe_to_loop: false, retry_after_ms: 0, ...estimate,
- why: 'A page failed to publish. Fix the cause named in managed_write / failures first; rerunning without a fix returns the same failure. Ask the user before skipping content.',
+ return { command: resumeCommand.replace(' --retry-failed', ''), safe_to_loop: false, retry_after_ms: 0, ...estimate,
+ why: 'A page failed to publish. Fix the cause named in managed_write / failures first; the same sync then retries it, and rerunning without a fix returns the same failure. Ask the user before skipping content.',
...(docs ? { docs } : {}) };
}
diff --git a/src/core/persistence/sync-failures.ts b/src/core/persistence/sync-failures.ts
index 5d8a3153d6..af80956399 100644
--- a/src/core/persistence/sync-failures.ts
+++ b/src/core/persistence/sync-failures.ts
@@ -8,6 +8,7 @@ import { resolveManagedSyncContext, syncGit, syncGitPath } from './sync-discover
import { readGitHold } from './sync-holds.ts';
import { pruneMirrorOnlyManagedFailures } from './managed-sync-orphans.ts';
import { publicFailureDetail } from './publication-failure.ts';
+import { VERSION } from '../../version.ts';
export interface ManagedSyncFailure {
source_id: string;
@@ -35,13 +36,15 @@ export interface ManagedSyncFailure {
* (a receipt from before #6643); the victim is then the only request named.
*/
root_cause?: ManagedSyncRootCause;
+ /** #6712 PR 3 (L7): the gbrain version that recorded the failure; absent on failures recorded before it was kept. */
+ gbrain_version?: string;
}
export interface ManagedSyncRootCause { request_id: string | null; slug: string | null; state: string | null; code: string | null; message: string | null;
/** The cursor fence cause when the root is a cursor refusal (`outside_fence`, `run_replaced`, `window_dropped`). */
cause?: string; unknown?: true }
export async function recordManagedSyncFailure(engine: BrainEngine, value: Omit<ManagedSyncFailure, 'first_seen' | 'attempts'> & { first_seen?: string }): Promise<{ failure: ManagedSyncFailure; ledgerRecorded: boolean }> {
- const failure = { ...value, first_seen: value.first_seen ?? new Date().toISOString(), attempts: 1 };
+ const failure = { ...value, gbrain_version: VERSION, first_seen: value.first_seen ?? new Date().toISOString(), attempts: 1 };
const recorded = await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
const [row] = await tx.executeRaw<{ completed_keys: [ManagedSyncFailure] }>(`
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 167b5ea7ac..29ca83befe 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -127,7 +127,7 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
{ code: 'plan_stale', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The approved company-brain manifest changed; inspect and approve the repository again.' },
// #6694: the source's pinned slug-root mode changed under a run of a subdirectory source; the checkpoint waits for the choice.
{ code: 'slug_root_mode_mismatch', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: the two modes give different slugs',
- human_reason: 'The source pins one slug-root mode and the sync ran under the other. A person chooses: set sources.config.slug_root_mode back to the mode the run used and rerun gbrain sync --no-pull --source <source> (the checkpoint is retried by itself), or keep the pin and run gbrain sync --no-pull --source <source> --retry-failed (the pages the refused run wrote keep their old slugs beside the new ones).' },
+ human_reason: 'The source pins one slug-root mode and the sync ran under the other. A person chooses: set sources.config.slug_root_mode back to the mode the run used and rerun gbrain sync --no-pull --source <source> (the checkpoint is retried by itself), or keep the pin, retire the refused cursor with gbrain repair managed-sync-orphans --source <source> (preview, then apply with its hash) and rerun the sync (the pages the refused run wrote keep their old slugs beside the new ones).' },
{ code: 'invalid_params', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The resume options conflict with the stored cursor; use the resume command the error prints.' },
// #6518: bookkeeping of an incarnation the source no longer has; a retry selects a different key, so only the repair clears it.
{ code: 'cursor_incarnation_retired', class: 'systemic', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview lists nothing to retire, or the same code returns after the apply' },
diff --git a/src/core/persistence/sync-origin.ts b/src/core/persistence/sync-origin.ts
index a98216759b..e17181f6dc 100644
--- a/src/core/persistence/sync-origin.ts
+++ b/src/core/persistence/sync-origin.ts
@@ -36,7 +36,7 @@ export function sameSyncOrigin(stored: string, origin: string, context?: SyncOri
if (nested && existsSync(join(context.root, stripped))) {
const error = new OperationError('page_identity_changed', 'A recorded page origin could name two files in this source.',
`Source '${context.sourceId}' records '${recorded}', which can mean the file '${stripped}' or the file '${recorded}' under the source directory. `
- + `On the source host, rename or move one of those two files, commit, then run gbrain sync --source ${context.sourceId} --no-pull --retry-failed.`);
+ + `On the source host, rename or move one of those two files, commit, then run gbrain sync --source ${context.sourceId} --no-pull.`);
error.detail = 'ambiguous_source_path';
throw error;
}
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 5d44020e93..7b0b66cc0c 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -169,7 +169,7 @@ function syncPublicationRefusal(code: RegistryCode, message: string, row: WriteR
/**
* #6643: the refusal of a request whose run another run replaced: not a failure of its page. Its next step is the
- * status read, never a `--retry-failed` rerun: the replacing run covers the page.
+ * status read, never a retry: the replacing run covers the page.
*/
function supersededRefusal(message: string, row: WriteRequest, cause: string): OperationError {
const status = ['gbrain', 'sync', 'status', '--source', row.source_id, '--json'];
@@ -525,7 +525,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
if (p.kind !== 'managed_sync_delete' && (!p.processingOptions ||
['noEmbed', 'noExtract', 'noSchemaPack'].some(key => typeof p.processingOptions?.[key as keyof SyncProcessingOptions] !== 'boolean'))) {
throw new OperationError('invalid_params', 'The legacy sync request has no durable processing options.',
- 'Inspect this unchanged request, then use --retry-failed with explicit sync options to rediscover. Unknown embedding and schema consent cannot be inferred from a retry.');
+ 'Inspect this unchanged request, then rerun the sync with explicit sync options: it retries the recorded failure by rediscovering. Unknown embedding and schema consent cannot be inferred from a retry.');
}
enterClaimStep(clock, 'authority', undefined, 'db');
await validateSyncAuthority(engine, p.syncAuthority, row.slug);
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 680c7b2dad..8aa3893e4c 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -15,7 +15,7 @@ import { preparationConfigView } from './config-snapshot.ts';
import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';
import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';
-import { checkpointRevival } from './sync-slug-mode.ts';
+import { CHECKPOINT_MOVED_MESSAGE, checkpointRevival } from './sync-slug-mode.ts';
import { managedCursorKey, resolveManagedCursor } from './sync-cursor-key.ts';
import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';
import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';
@@ -62,7 +62,7 @@ import { recordSyncRunTrend } from '../fence-repair/census-store.ts';
import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, releaseDiscoveredHolds, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type GitHoldCode, type SyncHoldPolicy } from './sync-holds.ts';
import { withScreeningPaths } from './screening-paths.ts';
import { withBoundedReadSession } from './bounded-reads.ts';
-import { receiptClass, resumableStop, stopRecorded } from './sync-stop-class.ts';
+import { receiptClass, recordedStop, replaysContentRefusal, replaysUnchangedRefusal, resumableStop, stopRecorded } from './sync-stop-class.ts';
import { advanceHeld, committedPast, deletionSettled, entryOf, indexOf, promoteWindow, waivedCursor, withHeldKeys, withoutPending } from './sync-cursor-moves.ts';
import { withSyncTail } from './sync-tail.ts';
import { assertDrainLease, currentDrainLease, leaseHeldResult, readDrainHolder, withDrainLease } from './sync-lease.ts';
@@ -194,7 +194,7 @@ function stampProgress(prior: CursorProgress | undefined, fromIndex: number, ind
const OP = 'managed-sync';
type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };
const header = ({ entries, companyPlan: _plan, ...value }: Cursor): CursorHeader => ({ ...value, total: entries.length });
-/** A managed sync run stopped before admitting the current entry; the recorded failure lets --retry-failed rediscover. */
+/** A managed sync run stopped before admitting the current entry; the next sync retries the recorded failure by rediscovering. */
function syncRunRefusal(code: RegistryCode, message: string, retry: Parameters<typeof checkpointRetryCommand>[0], cause: string): OperationError {
return opError(code, message, `${cause} Pages committed earlier in this run stay committed. Check the source with the command in fix, then run: ${checkpointRetryCommand(retry)}`,
{ fix: readFix(`Shows source ${retry.sourceId}'s owner and every pending, failed or recovering request, read-only.`,
@@ -763,7 +763,7 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:
const CHECKPOINT_REVIVAL_LIMIT = 3;
type SettleInput = Parameters<typeof settleFailedRequest>[1];
-/** #6712: an entry the run stopped on (a transport or systemic fault, a legacy knock-on) is re-frozen in place at most this many times in a row; then its failure stays recorded until --retry-failed. */
+/** #6712: an entry the run stopped on (a transport or systemic fault, a legacy knock-on) is re-frozen in place at most this many times in a row; then its failure is recorded and the next sync resets the bound. */
export const STOPS_PER_ENTRY = 3;
/**
@@ -771,7 +771,7 @@ export const STOPS_PER_ENTRY = 3;
* receipt, a systemic stop an earlier invocation recorded, or a legacy knock-on an older gbrain cancelled) is re-frozen in
* place under a fresh request: the cursor does not advance past it and the failed receipt is recorded as converted
* (`convertedFromFailed`), so it never blocks the checkpoint. Bounded by `STOPS_PER_ENTRY` re-freezes in a row at the
- * entry (`Pending.stops`); null past the bound, so the failure is recorded and stays until --retry-failed.
+ * entry (`Pending.stops`); null past the bound, so the failure is recorded and the next sync resets the bound (`retryRecordedFailure`).
*/
async function refreezeInPlace(engine: BrainEngine, input: SettleInput): Promise<Cursor | null> {
const { cursor, key, pending, assertActive } = input;
@@ -1328,34 +1328,49 @@ interface HoldRunState { sourceId?: string; incarnation?: string; remote?: boole
*/
/**
- * `--retry-failed` on an unfinished cursor whose pending request failed (or whose run has a ledger row). #6340: a pending
- * request that failed on a page fault (a page that moved, a dirty file) converts in place with the frozen manifest; every
- * other failure keeps the explicit rediscovery from HEAD. Null when nothing applies (an unfinished request, no failure).
+ * #6712 PR 3 (L7): a plain sync retries the failure an earlier invocation recorded for this run (`stopRecorded`), which
+ * `--retry-failed` (now its deprecated alias) used to do on request. A stop the drain re-freezes in place (a transport fault,
+ * a resumable systemic stop, a legacy knock-on) is left to the drain, with its `STOPS_PER_ENTRY` bound reset once the bound
+ * is spent; a checkpoint refused only by a receipt that no longer blocks it revives in the drain. Otherwise a pending
+ * request that failed on a page fault (#6340: a page that moved, a dirty file) converts in place with the frozen manifest,
+ * and every other recorded failure (a content refusal whose file or gbrain version changed, a stop before admission)
+ * rediscovers from HEAD. Null when nothing applies: no failure of this run is recorded, its request is still unfinished,
+ * a content refusal would refuse the same bytes again, or the failure needs a person's decision (a slug-mode refusal, a
+ * checkpoint whose source checkpoint moved: `gbrain repair managed-sync-orphans`).
*/
-async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: string, input: { opts: SyncOpts; context: ManagedSyncContext; authority: SyncAuthority;
+async function retryRecordedFailure(engine: BrainEngine, cursor: Cursor, key: string, input: { opts: SyncOpts; context: ManagedSyncContext; authority: SyncAuthority;
processingOptions: SyncProcessingOptions; syncOptions: SyncCursorOptions; startupConfig: BrainEngine; frozenRun: Parameters<typeof freezeEntry>[4]; runStartedAt: string;
discoveryRun: string; assertActive: () => void }): Promise<{ cursor: Cursor; discoveryTarget?: string } | { wait: RetryWait } | null> {
const { opts, context, authority, processingOptions, syncOptions, assertActive } = input;
+ const recorded = await recordedStop(engine, key, cursor.runId);
+ assertActive();
+ if (!recorded) return null;
const failed = cursor.pending ? await getWriteRequest(engine, admittedBy(cursor.pending, cursor), cursor.pending.requestId) : null;
assertActive();
- // #6712: --retry-failed resets the in-place re-freeze bound of an entry the run stopped on for a fault not its page's; the drain re-freezes it again.
- if (failed && cursor.pending && (cursor.pending.stops ?? 0) >= STOPS_PER_ENTRY && ['failed', 'conflict', 'cancelled'].includes(failed.state) && (isSyncKnockOn(failed) || receiptClass(failed) === 'transport' || resumableStop(failed))) {
+ const terminal = !!failed && ['failed', 'conflict', 'cancelled'].includes(failed.state);
+ if (failed && !terminal && failed.state !== 'committed') return null;
+ const fault = terminal ? receiptClass(failed!) : null;
+ if (terminal && cursor.pending && cursor.pending.intent.kind !== 'managed_sync_checkpoint'
+ && (fault === 'transport' || isSyncKnockOn(failed!) || (fault === 'systemic' && resumableStop(failed!)))) {
+ if ((cursor.pending.stops ?? 0) < STOPS_PER_ENTRY) return null;
const { stops: _stops, ...pending } = cursor.pending;
return { cursor: await saveCursor(engine, key, cursor, { ...cursor, pending }, false, assertActive) };
}
- // #6643/#6712: a legacy knock-on (re-frozen in place, `refreezeInPlace`) and a checkpoint refused only by a receipt that no
- // longer blocks it recover in the drain (settleFailedRequest); neither rediscovers the frozen manifest. A checkpoint a
- // receipt still blocks (since #6712 a legacy knock-on the cursor never settled is one) rediscovers, as --retry-failed says.
- if (failed && cursor.pending && isSyncKnockOn(failed)) return null;
- if (failed && cursor.pending?.intent.kind === 'managed_sync_checkpoint' && cursor.index === cursor.entries.length && revivableCheckpointRefusal(failed)
+ if (terminal && cursor.pending?.intent.kind === 'managed_sync_checkpoint' && cursor.index === cursor.entries.length
+ && (revivableCheckpointRefusal(failed!) || await checkpointRevival(engine, cursor, cursor.pending.intent, failed!))
&& !await findIncompleteSyncReceipt(engine, cursor.binding.worktree_id, cursor.runId, cursor.convertedFromFailed ?? [], cursor.settled ?? null)) return null;
- const recorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, cursor.runId]);
- assertActive();
- if (!((failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) || (recorded.length && (failed?.state === 'committed' || !failed)))) return null;
+ // A slug-mode refusal the pin still disagrees with is a person's choice (rediscovering would adopt the new pin), and a
+ // checkpoint the source's last_commit moved away from is never rediscovered by itself (#6834: a path-sliced run would
+ // rediscover its slice's older target and move last_commit backward). Both stay recorded with their decision;
+ // `gbrain repair managed-sync-orphans` retires the cursor (and its slice record), and the next sync discovers again.
+ if (terminal && (failed!.error_code === 'slug_root_mode_mismatch'
+ || cursor.pending?.intent.kind === 'managed_sync_checkpoint' && failed!.error_code === 'revision_conflict' && failed!.error_message === CHECKPOINT_MOVED_MESSAGE)) return null;
+ if (terminal && cursor.pending!.intent.kind !== 'managed_sync_checkpoint' && replaysUnchangedRefusal(failed!, recorded,
+ { root: cursor.root, intent: cursor.pending!.intent, target: cursor.target, head: () => syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim() })) return null;
const blocker = await oldRunBlocker(engine, cursor, key);
assertActive();
if (blocker) return { wait: blocker };
- // Only the #6340 page faults convert here (a content refusal under --retry-failed keeps its explicit rediscovery; #6513: a checkpoint is never a page fault).
+ // Only the #6340 page faults convert here (a content refusal rediscovers; #6513: a checkpoint is never a page fault).
const pageFault = !!failed && !!cursor.pending && cursor.pending.intent.kind !== 'managed_sync_checkpoint' && (pinnedWorktreeConflict(failed) || failed.error_code === 'revision_conflict');
const screen = pageFault ? await loadSyncScreenRun(input.startupConfig, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote) : null;
const converted = screen ? await convertBlockedCursor(engine, cursor, key, assertActive, { ...input.frozenRun, screen, observedAt: cursor.discoveredAt ?? input.runStartedAt }) : cursor;
@@ -1494,12 +1509,15 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
assertActive();
if (cursor && !cursor.done && !opts.dryRun) cursor = await adoptCursor(engine, key, cursor, { authority, processingOptions, syncOptions, embedDeferred: opts.embedDeferred, assertActive, state });
assertActive();
- if (company && opts.retryFailed && cursor && !cursor.done && !opts.dryRun) {
+ const companyStop = company && cursor && !cursor.done && !opts.dryRun ? await recordedStop(engine, key, cursor.runId) : null;
+ if (companyStop && cursor) {
const failed = cursor.pending ? await getWriteRequest(engine, admittedBy(cursor.pending, cursor), cursor.pending.requestId) : null;
const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [cursor.sourceId]);
assertActive();
// #6712: a legacy knock-on is re-frozen in place by the drain (refreezeInPlace), within its stop bound.
- if (!unfinished.length && (failed && ['failed', 'conflict', 'cancelled'].includes(failed.state) && !isSyncKnockOn(failed) || !cursor.pending && !cursor.processingOptions)) {
+ // The approved manifest pins the content, so a content refusal this version recorded replays until the approval changes.
+ if (!unfinished.length && (failed && ['failed', 'conflict', 'cancelled'].includes(failed.state) && !isSyncKnockOn(failed) && !replaysContentRefusal(failed, companyStop, () => true)
+ || !cursor.pending && !cursor.processingOptions)) {
if (cursor.processingOptions && digest(cursor.processingOptions) !== digest(processingOptions)) {
throw syncRunRefusal('invalid_params', 'The approved company sync must retain its original processing options.',
{ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath: frozenRun.repoPath },
@@ -1511,8 +1529,9 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
}
}
const startupConfig = await preparationConfigView(engine); // #5984 G3: one config read answers the startup's config reads
- if (cursor && opts.retryFailed && !opts.dryRun && !company && !cursor.done) {
- const retried = await retryFailedStart(engine, cursor, key, { opts, context, authority, processingOptions, syncOptions, startupConfig, frozenRun, runStartedAt, discoveryRun, assertActive });
+ let retried: Awaited<ReturnType<typeof retryRecordedFailure>> = null;
+ if (cursor && !opts.dryRun && !company && !cursor.done) {
+ retried = await retryRecordedFailure(engine, cursor, key, { opts, context, authority, processingOptions, syncOptions, startupConfig, frozenRun, runStartedAt, discoveryRun, assertActive });
if (retried && 'wait' in retried) return { ...result(cursor, 'partial', 'writer_pending'), ...(authority.writer.remote ? {} : { retryWait: retried.wait }) };
if (retried) { cursor = retried.cursor; if (retried.discoveryTarget) { phase = 'discovery'; discoveryTarget = retried.discoveryTarget; } }
}
@@ -1560,7 +1579,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
if (opts.dryRun) return dryRun(cursor);
frozenRun.screen = company ? null : await loadSyncScreenRun(startupConfig, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote);
const observedAt = frozenRun.observedAt = cursor.discoveredAt ?? runStartedAt;
- if (frozenRun.screen && !opts.retryFailed && cursor.pending && !cursor.done) {
+ if (frozenRun.screen && !retried && cursor.pending && !cursor.done) {
phase = 'freeze';
cursor = await convertBlockedCursor(engine, cursor, key, assertActive, frozenRun);
}
diff --git a/src/core/persistence/sync-slug-mode.ts b/src/core/persistence/sync-slug-mode.ts
index c85791a2c1..180f4e0b61 100644
--- a/src/core/persistence/sync-slug-mode.ts
+++ b/src/core/persistence/sync-slug-mode.ts
@@ -32,7 +32,7 @@ export async function pinnedSlugModeMismatch(engine: Pick<BrainEngine, 'executeR
export function slugModeMismatchCause(sourceId: string, pinned: string, slugMode: SlugRootMode): string {
return `Source ${sourceId} pins slug_root_mode=${pinned}, but this sync ran under ${slugMode}; at a subdirectory the two modes give different slugs, so the checkpoint did not advance. `
+ `A person decides which mode the source keeps: set sources.config.slug_root_mode back to ${slugMode} and rerun gbrain sync --no-pull --source ${sourceId}, `
- + `or keep ${pinned} and run gbrain sync --no-pull --source ${sourceId} --retry-failed, which discovers the source again under ${pinned} (pages this run wrote keep their ${slugMode} slugs beside the new ones).`;
+ + `or keep ${pinned}: preview gbrain repair managed-sync-orphans --source ${sourceId} (it lists this run's cursor as slug_mode_refused), apply it with the hash it prints, then rerun gbrain sync --no-pull --source ${sourceId}, which discovers the source again under ${pinned} (pages this run wrote keep their ${slugMode} slugs beside the new ones).`;
}
/**
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index a9b849a107..525504b809 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -281,9 +281,9 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
+ ' and names the sync to run; it refuses the rest by name and drops nothing.' }
: retired ? { ...repairPreview, verify }
: unfinished || lastError
- ? { argv: ['gbrain', 'sync', ...resume, ...(lastError ? ['--retry-failed'] : [])], consent: [], actor: 'agent', requires_exclusive: false, verify,
- why: lastError && selfHealing ? `The last run stopped on a page that only waited on another page of the same sync (${lastError.detail}); --retry-failed (or the same sync) re-freezes it under a fresh request${lastError.root_cause?.request_id ? `, and request ${lastError.root_cause.request_id} is what it waited on` : ''}.`
- : lastError ? `The last run recorded ${lastError.code} (${lastError.class}); this release holds or retries it, and --retry-failed converts the stopped entry in place without re-freezing the manifest.`
+ ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: lastError && selfHealing ? `The last run stopped on a page that only waited on another page of the same sync (${lastError.detail}); the same sync re-freezes it under a fresh request${lastError.root_cause?.request_id ? `, and request ${lastError.root_cause.request_id} is what it waited on` : ''}.`
+ : lastError ? `The last run recorded ${lastError.code} (${lastError.class}); the same sync retries it: it holds or re-freezes the stopped entry in place, or rediscovers the source from HEAD.`
: `The cursor stands at ${header!.index}/${header!.total}; the same command resumes it against the frozen manifest.` }
: null;
const [oldest, recovery] = await Promise.all([oldestBlocker(engine, sourceId), recoveryProbe(engine, sourceId)]);
diff --git a/src/core/persistence/sync-stop-class.ts b/src/core/persistence/sync-stop-class.ts
index 2f57950273..45cc675d20 100644
--- a/src/core/persistence/sync-stop-class.ts
+++ b/src/core/persistence/sync-stop-class.ts
@@ -8,6 +8,13 @@ import type { BrainEngine } from '../engine.ts';
import type { WriteRequest } from './model.ts';
import { classifyTerminal } from './terminal-classify.ts';
import { classifySyncFault } from './sync-fault-class.ts';
+import { isContentRefusal } from '../import-screen.ts';
+import { sha256 } from './digest.ts';
+import { readSyncFile } from './sync-discovery.ts';
+import { VERSION } from '../../version.ts';
+import { pinnedWorktreeConflict } from './sync-page-fault.ts';
+import { statSync } from 'node:fs';
+import { join } from 'node:path';
/**
* #6712 (#6565): how the run treats a receipt that did not commit, from the terminal classifier: `transport` (a dropped
@@ -27,7 +34,7 @@ export function receiptClass(row: WriteRequest): 'transport' | 'page' | 'systemi
/**
* #6712 (#6565): a stop the next plain sync re-freezes in place: a database refusal the fault table retries (an
* unrecognised P0001 or a 55000 raised under a page write surfaces as `storage_error`). A content, consent or option
- * refusal is never one: its receipt stays the diagnosis until --retry-failed.
+ * refusal is never one: its receipt stays the diagnosis until the next sync retries it from HEAD (`retryRecordedFailure`).
*/
export function resumableStop(row: WriteRequest): boolean {
const verdict = classifySyncFault({ code: row.error_code ?? 'storage_error', message: row.error_message ?? null });
@@ -39,5 +46,43 @@ export function resumableStop(row: WriteRequest): boolean {
* and the pages its window admitted after the stop and the same refusal failed are re-frozen like the stop itself.
*/
export async function stopRecorded(engine: BrainEngine, key: string, runId: string): Promise<boolean> {
- return (await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, runId])).length > 0;
+ return (await recordedStop(engine, key, runId)) !== null;
+}
+/** #6712 PR 3 (L7): this run's recorded stop with the gbrain version that recorded it (null on a row from before versions were kept), or null when none is. */
+export async function recordedStop(engine: BrainEngine, key: string, runId: string): Promise<RecordedStop | null> {
+ const [row] = await engine.executeRaw<RecordedStop>(
+ "SELECT completed_keys->0->>'gbrain_version' AS gbrain_version, (extract(epoch FROM updated_at)*1000)::text AS recorded_ms FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, runId]);
+ return row ?? null;
+}
+export interface RecordedStop { gbrain_version: string | null; recorded_ms: string }
+
+/**
+ * #6712 PR 3 (L7): a content refusal is a function of the file's bytes and the parser that read them, so while both are the
+ * ones that refused it (the file is unchanged and this gbrain version recorded the failure) the sync replays the recorded
+ * failure without a new request. A changed file, an upgrade, or a failure an older build recorded is retried.
+ */
+export function replaysContentRefusal(failed: WriteRequest, recorded: { gbrain_version: string | null }, unchanged: () => boolean): boolean {
+ return isContentRefusal(failed.error_code, failed.error_message) && recorded.gbrain_version === VERSION && unchanged();
+}
+
+/**
+ * #6712 PR 3 (L7): whether the next sync replays a page's recorded refusal instead of retrying it, because what decides it
+ * has not changed since this gbrain version recorded it: a content refusal while the file has its frozen bytes, and a pinned
+ * import refused for newer working-tree bytes (`source_changed`) while HEAD is still the run's target and the file was not
+ * written after the failure was recorded. Committing the file, editing it or upgrading gbrain retries it.
+ */
+export function replaysUnchangedRefusal(failed: WriteRequest, recorded: RecordedStop,
+ entry: { root: string; intent: { path?: string | null; rawHash?: string | null }; target: string; head: () => string }): boolean {
+ if (replaysContentRefusal(failed, recorded, () => fileUnchangedSinceFreeze(entry.root, entry.intent))) return true;
+ if (!pinnedWorktreeConflict(failed) || recorded.gbrain_version !== VERSION || !entry.intent.path || entry.head() !== entry.target) return false;
+ try { return statSync(join(entry.root, entry.intent.path)).mtimeMs <= Number(recorded.recorded_ms); } catch { return false; }
+}
+
+/** Whether the entry's file still has the bytes its frozen request carried (a missing file, for a deletion). */
+export function fileUnchangedSinceFreeze(root: string, intent: { path?: string | null; rawHash?: string | null }): boolean {
+ if (!intent.path) return true;
+ try {
+ const bytes = readSyncFile(root, intent.path);
+ return (bytes === null ? null : sha256(bytes)) === (intent.rawHash ?? null);
+ } catch { return false; }
}
diff --git a/src/core/persistence/sync-window.ts b/src/core/persistence/sync-window.ts
index 3111382605..500a3105f1 100644
--- a/src/core/persistence/sync-window.ts
+++ b/src/core/persistence/sync-window.ts
@@ -18,8 +18,6 @@ export const WINDOW_CANCEL_MESSAGE = 'An earlier page of the same sync did not c
/** #6402 residual (P4.3): the lane fault a group released under, kept on its rows as `blocked_reason`. */
export type LaneFault = 'lock_timeout' | 'statement_timeout';
export const laneFaultBlockedReason = (fault: LaneFault) => `lane_${fault}` as const;
-export const laneFaultOf = (blockedReason: string | null | undefined): LaneFault | null =>
- blockedReason === 'lane_lock_timeout' ? 'lock_timeout' : blockedReason === 'lane_statement_timeout' ? 'statement_timeout' : null;
/** The lane-fault cancel text older builds wrote (no producer since #6712). */
export const laneFaultCancelMessage = (fault: LaneFault) =>
`An earlier page of the same sync did not commit after ${fault} on its lane group; this page was not published and is re-frozen on the next sync pass.`;
diff --git a/src/core/persistence/sync-write-diagnostic.ts b/src/core/persistence/sync-write-diagnostic.ts
index f76b5f251d..67e24e80f5 100644
--- a/src/core/persistence/sync-write-diagnostic.ts
+++ b/src/core/persistence/sync-write-diagnostic.ts
@@ -34,10 +34,10 @@ export function managedSyncWriteDiagnostic(cursor: { sourceId: string; root: str
const diagnostic: ManagedSyncWriteDiagnostic = { source_id: cursor.sourceId, slug: pending.slug,
path: pending.intent.path, write_error: code, ...detail, ...(verdict ? { category: verdict.category, public_category: verdict.public_category } : {}),
write_request: publicWriteReceipt(receiptFor(row)) };
- // #6194: an import that lost to a database write the hold could not prove; --retry-failed re-imports the Git version over it.
+ // #6194: an import that lost to a database write the hold could not prove; the retry re-imports the Git version unless discovery's drift guard holds it.
if (terminal && code === 'revision_conflict' && pending.intent.kind === 'managed_sync_import') diagnostic.suggestion = `The page changed in the database after this import was frozen. `
+ `Before retrying, compare the file and the page with gbrain sources reconcile ${cursor.sourceId} ${pending.slug} --preview (it writes nothing): a retry re-imports the Git version over the database one. ${diagnostic.suggestion}`;
- if (terminal) diagnostic.suggestion += ` After repair, run ${checkpointRetryCommand({ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? null, repoPath: pending.intent.repoPath })} to start a new request. Without --retry-failed, the frozen terminal request returns the same outcome. Skipping failures cannot bypass a managed write.`;
+ if (terminal) diagnostic.suggestion += ` After repair, run ${checkpointRetryCommand({ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? null, repoPath: pending.intent.repoPath })} to retry it under a new request. Skipping failures cannot bypass a managed write.`;
if (diagnostic.reason === 'pinned_git_worktree_conflict' && pending.intent.path && pending.intent.content !== null) {
try {
const bytes = readSyncFile(cursor.root, pending.intent.path);
diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.ts
index a6c7d2f3e7..e0c030b413 100644
--- a/src/core/persistence/terminal-classify.ts
+++ b/src/core/persistence/terminal-classify.ts
@@ -105,7 +105,7 @@ export function terminalVerifyArgv(sourceId: string): string[] { return failures
export function terminalInspectArgv(requestId: string): string[] { return ['gbrain', 'write-request', requestId, '--json']; }
function syncRetry(sourceId: string, why: string): Action {
- return { argv: ['gbrain', 'sync', '--source', sourceId, '--no-pull', '--retry-failed', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why,
+ return { argv: ['gbrain', 'sync', '--source', sourceId, '--no-pull', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why,
verify: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] }, docs: 'docs/guides/sync-unblock-runbook.md' };
}
function inspect(sourceId: string, why: string, userMessage?: string): Action {
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
index b3d9966702..5d25eaef98 100644
--- a/src/core/persistence/worktree-refresh.ts
+++ b/src/core/persistence/worktree-refresh.ts
@@ -277,15 +277,15 @@ async function worktreeRecoveryPending(engine: BrainEngine, binding: WorktreeBin
}
/** Never wait on a sync: an unexhausted cursor names its own resume command. */
async function assertNoUnfinishedSync(engine: BrainEngine, members: string[]): Promise<void> {
- const [cursor] = await engine.executeRaw<{ source_id: string; header: Record<string, unknown>; failed: boolean }>(`SELECT c.completed_keys->0->>'sourceId' AS source_id,
- c.completed_keys->0 AS header,EXISTS (SELECT 1 FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=c.fingerprint) AS failed
+ const [cursor] = await engine.executeRaw<{ source_id: string; header: Record<string, unknown> }>(`SELECT c.completed_keys->0->>'sourceId' AS source_id,
+ c.completed_keys->0 AS header
FROM op_checkpoints c WHERE c.op='managed-sync' AND COALESCE(c.completed_keys->0->>'done','false')<>'true'
AND c.completed_keys->0->>'sourceId'=ANY($1::text[]) ORDER BY c.updated_at LIMIT 1`, [members]);
if (!cursor) return;
const header = cursor.header as { processingOptions?: Record<string, boolean>; syncOptions?: Parameters<typeof checkpointRetryCommand>[0]['syncOptions'] };
const resume = checkpointRetryCommand({ sourceId: cursor.source_id, processingOptions: header.processingOptions, syncOptions: header.syncOptions ?? null });
throw refusal('sync_in_progress', `Source ${cursor.source_id} has an unfinished managed sync cursor; moving the checkout now would strand it.`,
- `${cursor.failed ? resume : resume.replace(' --retry-failed', '')}, then retry the refresh.`);
+ `${resume}, then retry the refresh.`);
}
async function drainCounts(engine: BrainEngine, worktreeId: string): Promise<{ requests: number; effects: number; recovery: number }> {
@@ -326,15 +326,15 @@ async function syncMembers(engine: BrainEngine, git: Git, row: WorktreeRefreshRo
try { result = await performManagedSync(engine, { sourceId, noPull: true }); }
catch (error) {
const failure = error instanceof OperationError ? error : opError('storage_error', error instanceof Error ? error.message : String(error),
- `The managed sync of source ${sourceId} failed during refresh ${row.id}. Check its writer status, fix the cause, then resume with gbrain sync --source ${sourceId} --no-pull --retry-failed.`);
- blocked.push({ source_id: sourceId, code: failure.code, message: failure.message, resume: `gbrain sync --source ${sourceId} --no-pull --retry-failed` });
+ `The managed sync of source ${sourceId} failed during refresh ${row.id}. Check its writer status, fix the cause, then resume with gbrain sync --source ${sourceId} --no-pull.`);
+ blocked.push({ source_id: sourceId, code: failure.code, message: failure.message, resume: `gbrain sync --source ${sourceId} --no-pull` });
status = 'blocked';
break;
}
status = result.status;
if (result.status === 'blocked_by_failures') {
blocked.push({ source_id: sourceId, code: result.managedWrite?.write_error ?? result.failureCodes?.[0]?.code ?? 'sync_blocked',
- message: result.managedWrite?.message ?? 'The managed sync is blocked by a failed write.', resume: `gbrain sync --source ${sourceId} --no-pull --retry-failed` });
+ message: result.managedWrite?.message ?? 'The managed sync is blocked by a failed write.', resume: `gbrain sync --source ${sourceId} --no-pull` });
break;
}
if (result.status === 'partial') await new Promise(resolve => setTimeout(resolve, DRAIN_POLL_MS));
@@ -383,10 +383,10 @@ export async function refreshWorktree(engine: BrainEngine, sourceId: string, opt
try {
const result = await performManagedSync(engine, { sourceId: member, noPull: true });
if (result.status === 'blocked_by_failures') blocked.push({ source_id: member, code: result.managedWrite?.write_error ?? 'sync_blocked',
- message: result.managedWrite?.message ?? 'The managed sync is blocked by a failed write.', resume: `gbrain sync --source ${member} --no-pull --retry-failed` });
+ message: result.managedWrite?.message ?? 'The managed sync is blocked by a failed write.', resume: `gbrain sync --source ${member} --no-pull` });
synced.push({ source_id: member, status: result.status, last_commit: await lastCommit(engine, member) });
} catch (error) {
- blocked.push({ source_id: member, code: (error as OperationError).code ?? 'storage_error', message: (error as Error).message, resume: `gbrain sync --source ${member} --no-pull --retry-failed` });
+ blocked.push({ source_id: member, code: (error as OperationError).code ?? 'storage_error', message: (error as Error).message, resume: `gbrain sync --source ${member} --no-pull` });
}
}
return { ...base, status: blocked.length ? 'sync_blocked' : 'already_current', synced, ...(blocked.length ? { sync_blocked: blocked, next: blocked.map(b => b.resume).join(' ; ') } : {}) };
diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.ts
index 5e4c77c0f4..ff66887c66 100644
--- a/src/core/repair/failed-writes.ts
+++ b/src/core/repair/failed-writes.ts
@@ -86,7 +86,7 @@ function previewCommand(scope: RepairScope): string {
/** The command that produces an owner-internal write again, from current content. */
function producerCommand(producer: string, sourceId: string): string {
const parts = producer.split(':');
- if (parts.some(part => part.startsWith('managed_sync') || part === 'managed_file_import')) return `gbrain sync --source ${sourceId} --no-pull --retry-failed --json`;
+ if (parts.some(part => part.startsWith('managed_sync') || part === 'managed_file_import')) return `gbrain sync --source ${sourceId} --no-pull --json`;
if (parts.includes('canonical_reconcile')) return `gbrain sources reconcile ${sourceId} --audit`;
if (parts.includes('managed_file_repair')) return `gbrain repair frontmatter --source ${sourceId} (a frontmatter repair) or gbrain repair fences --source ${sourceId} (a fence repair)`;
if (parts.includes('relink_facts')) return `gbrain facts relink --source ${sourceId} --dry-run`;
diff --git a/src/core/repair/managed-sync-orphans.ts b/src/core/repair/managed-sync-orphans.ts
index a6b72504ba..275cc45e83 100644
--- a/src/core/repair/managed-sync-orphans.ts
+++ b/src/core/repair/managed-sync-orphans.ts
@@ -11,6 +11,9 @@
* #6834: a cursor whose checkpoint was refused because the source's
* `last_commit` moved elsewhere (`checkpoint_moved`) is retirable too; it
* never resumes, and the next sync discovers from the recorded commit.
+ * #6712 PR 3: a cursor refused for its slug-root mode while the source still
+ * pins the other one (`slug_mode_refused`) is retirable too: retiring it is how
+ * a person keeps the new pin.
* Retiring an old incarnation's bookkeeping says nothing about whether the
* current source's files were imported; `gbrain sync status` does.
*/
@@ -36,6 +39,7 @@ const describe = (orphan: ManagedSyncOrphan) => orphan.reason === 'no_cursor' ?
: orphan.reason === 'incarnation_retired' ? `${orphan.kind === 'unfinished_cursor' ? 'cursor' : 'failure row'} recorded under source incarnation ${orphan.source_incarnation?.slice(0, 8) ?? '?'}, which the source no longer has; no current sync selects it`
: orphan.reason === 'mirror_only' ? 'local ledger mirror row with no durable failure row under its key'
: orphan.reason === 'checkpoint_moved' ? `cursor whose pages all committed and whose checkpoint (request ${orphan.pending_request_id ?? '?'}) was refused because the source's last_commit moved to a commit outside this run; no resume can publish it, and the next sync discovers from the commit the source records`
+ : orphan.reason === 'slug_mode_refused' ? `cursor whose pages all committed and whose checkpoint (request ${orphan.pending_request_id ?? '?'}) was refused because the source pins the other slug_root_mode; retiring it keeps the pin, and the next sync discovers the source again under it`
: 'cursor from before recorded sync options, superseded by a completed run';
export const managedSyncOrphansRepair: RepairHandler = {
diff --git a/src/core/sync-flags.ts b/src/core/sync-flags.ts
index c74cc38bec..f0de5366cd 100644
--- a/src/core/sync-flags.ts
+++ b/src/core/sync-flags.ts
@@ -31,39 +31,42 @@ export interface SyncFlagSpec {
serve: SyncFlagRoute;
/** The PGLite persistence owner lane (`writer_sync`). */
owner: SyncFlagRoute;
+ /** #6712 PR 3 (L7): listed in the "Managed brains" section of `gbrain sync --help` (at most 10; the rest are classic or advanced). */
+ managed?: true;
}
const bool = (field: string, serve: SyncFlagRoute, owner: SyncFlagRoute): SyncFlagSpec => ({ arity: 'boolean', field, type: 'boolean', serve, owner });
const local = (arity: SyncFlagSpec['arity'], serve: SyncFlagRoute = 'refuse', owner: SyncFlagRoute = 'refuse'): SyncFlagSpec => ({ arity, serve, owner });
+const managed = <T extends SyncFlagSpec>(spec: T): T & { managed: true } => ({ ...spec, managed: true });
export const SYNC_FLAGS = {
- '--source': { arity: 'value', field: 'sourceId', type: 'string', serve: 'client', owner: 'forward' },
+ '--source': managed({ arity: 'value', field: 'sourceId', type: 'string', serve: 'client', owner: 'forward' }),
'--full': bool('full', 'forward', 'forward'),
- '--dry-run': bool('dryRun', 'forward', 'forward'),
- '--no-pull': bool('noPull', 'forward', 'forward'),
+ '--dry-run': managed(bool('dryRun', 'forward', 'forward')),
+ '--no-pull': managed(bool('noPull', 'forward', 'forward')),
'--no-embed': bool('noEmbed', 'forward', 'forward'),
'--no-extract': bool('noExtract', 'forward', 'forward'),
'--no-schema-pack': bool('noSchemaPack', 'forward', 'forward'),
'--skip-failed': bool('skipFailed', 'forward', 'forward'),
'--retry-failed': bool('retryFailed', 'forward', 'forward'),
'--include-gitignored': bool('includeGitignored', 'forward', 'forward'),
- '--no-bulk': bool('noBulk', 'forward', 'forward'),
+ '--no-bulk': managed(bool('noBulk', 'forward', 'forward')),
'--working-tree': bool('workingTree', 'refuse', 'forward'),
'--reset-checkpoint': bool('resetCheckpoint', 'refuse', 'forward'),
'--lanes': { arity: 'value', field: 'lanes', type: 'number', serve: 'forward', owner: 'client' },
- '--no-lanes': { arity: 'boolean', field: 'lanes', type: 'number', sets: 1, serve: 'forward', owner: 'client' },
+ '--no-lanes': managed({ arity: 'boolean', field: 'lanes', type: 'number', sets: 1, serve: 'forward', owner: 'client' }),
'--repo': { arity: 'value', field: 'repoPath', type: 'string', serve: 'refuse', owner: 'forward' },
'--src-subpath': { arity: 'value', field: 'srcSubpath', type: 'string', serve: 'refuse', owner: 'forward' },
'--strategy': { arity: 'value', field: 'strategy', type: 'string', serve: 'refuse', owner: 'forward' },
'--exclude': { arity: 'repeat', field: 'exclude', type: 'string[]', serve: 'refuse', owner: 'forward' },
'--include-hidden': { arity: 'repeat', field: 'includeHidden', type: 'string[]', serve: 'refuse', owner: 'forward' },
- '--timeout': local('value', 'client', 'client'),
- '--hard-deadline': local('value', 'client', 'client'),
+ '--timeout': managed(local('value', 'client', 'client')),
+ '--hard-deadline': managed(local('value', 'client', 'client')),
'--no-hard-deadline': local('boolean', 'client', 'client'),
- '--json': local('boolean', 'client', 'client'),
+ '--json': managed(local('boolean', 'client', 'client')),
'--yes': local('boolean', 'client', 'client'),
'--no-delegate': local('boolean', 'client', 'client'),
- '--all': local('boolean'),
+ '--all': managed(local('boolean')),
'--watch': local('boolean'),
'--interval': local('value'),
'--workers': local('value'),
@@ -74,7 +77,7 @@ export const SYNC_FLAGS = {
'--no-auto-embed': local('boolean'),
'--missing-path': local('value'),
'--acknowledge-managed': local('boolean'),
- '--break-lock': local('boolean'),
+ '--break-lock': managed(local('boolean')),
'--force-break-lock': local('boolean'),
'--max-age': local('value'),
} as const satisfies Record<string, SyncFlagSpec>;
@@ -82,6 +85,9 @@ export const SYNC_FLAGS = {
export type SyncFlag = keyof typeof SYNC_FLAGS;
type Lane = 'serve' | 'owner';
+/** #6712 PR 3 (L7): the flags `gbrain sync --help` lists under "Managed brains", in table order. */
+export const MANAGED_HELP_FLAGS: SyncFlag[] = (Object.keys(SYNC_FLAGS) as SyncFlag[]).filter(flag => (SYNC_FLAGS[flag] as SyncFlagSpec).managed);
+
/** The flags a hand-off takes the given route for. */
export function syncFlagsRouted(lane: Lane, route: SyncFlagRoute): SyncFlag[] {
return (Object.keys(SYNC_FLAGS) as SyncFlag[]).filter(flag => (SYNC_FLAGS[flag] as SyncFlagSpec)[lane] === route);
diff --git a/test/error-registry-retired.test.ts b/test/error-registry-retired.test.ts
index 3104b27736..5b5e4c33a8 100644
--- a/test/error-registry-retired.test.ts
+++ b/test/error-registry-retired.test.ts
@@ -9,6 +9,8 @@
* #6712 PR 2 extends it to the sync config-key table: no source line outside the table and the historical behavior
* notices names a retired key (help text, doctor messages, hold reasons and refusals included), and `gbrain sync --help`
* and `gbrain config --help` name neither a retired key nor a rollback key (rollback keys are not tunables).
+ * #6712 PR 3 (L7) extends it to `gbrain sync --retry-failed`, now a deprecated alias of the plain sync: no registered fix,
+ * fault-table reason, source string or sync help line outside the flag's own deprecation entry tells a Git sync to pass it.
*/
import { expect, test } from 'bun:test';
import { CODES, NOTICE_CODES, type CodeEntry } from '../src/core/error-registry.ts';
@@ -104,3 +106,41 @@ test('sync and config help name no retired key and no rollback key', async () =>
const named = [...RETIRED_KEYS, ...SYNC_ROLLBACK_KEYS].filter(key => new RegExp(`\\b${key.replace('.', '\\.')}\\b`).test(help));
expect(named).toEqual([]);
});
+
+/** #6712 PR 3 (L7): a source line that tells a Git sync to pass the deprecated alias. */
+const RETRY_FAILED_ADVICE = /\bgbrain sync\b[^'"`]*--retry-failed/;
+// The flag's parse and its deprecation notice; the historical notices; connector sources, where the flag still re-approves a failed item receipt.
+const RETRY_FAILED_ALLOWED = new Set(['src/commands/sync/args.ts', 'src/core/sync-flags.ts', 'src/core/behavior-change-notice.ts', 'src/core/persistence/connector-sync.ts',
+ 'src/core/cli-flag-registry.generated.ts']);
+
+test('no registered fix, fault reason or source line tells a sync to pass the deprecated --retry-failed', () => {
+ const texts: Array<[string, string]> = [
+ ...entries(CODES).map(([code, entry]) => [`CODES.${code}`, fixText(entry)] as [string, string]),
+ ...entries(NOTICE_CODES).filter(([code]) => code !== 'sync_retry_failed_deprecated').map(([code, entry]) => [`NOTICE_CODES.${code}`, fixText(entry)] as [string, string]),
+ ...SYNC_FAULT_TABLE.map(rule => [`SYNC_FAULT_TABLE.${rule.code}`, `${rule.human_reason ?? ''}\n${rule.escalate}`] as [string, string]),
+ ];
+ const named = texts.filter(([, text]) => /sync[^\n]*--retry-failed/.test(text) || text.includes("'sync', '--retry-failed'")).map(([where]) => where);
+ for (const [code, entry] of [...entries(CODES), ...entries(NOTICE_CODES)]) {
+ const argv = entry.fix?.argv ?? [];
+ if (argv[1] === 'sync' && argv.includes('--retry-failed')) named.push(`${code}.fix.argv`);
+ }
+ for (const file of sourceFiles('src').filter(path => !RETRY_FAILED_ALLOWED.has(path))) {
+ readFileSync(file, 'utf8').split('\n').forEach((line, i) => {
+ const code = line.trim();
+ if (code.startsWith('//') || code.startsWith('*') || code.startsWith('/*')) return;
+ if (RETRY_FAILED_ADVICE.test(line) && !line.includes('sync_retry_failed_deprecated:')) named.push(`${file}:${i + 1}`);
+ });
+ }
+ expect(named).toEqual([]);
+});
+
+test('sync --help mentions --retry-failed only as its own deprecated entry', async () => {
+ const captured: string[] = [];
+ const log = console.log;
+ console.log = (...parts: unknown[]) => { captured.push(parts.join(' ')); };
+ try { (await import('../src/commands/sync/args.ts')).printSyncHelp(); } finally { console.log = log; }
+ const lines = captured.join('\n').split('\n');
+ const mentions = lines.map((line, i) => [line, i] as const).filter(([line]) => line.includes('--retry-failed'));
+ expect(mentions.map(([line]) => line.trim().split(/\s+/)[0])).toEqual(['--retry-failed']);
+ expect(mentions[0]![0]).toContain('Deprecated');
+});
diff --git a/test/persistence-sync-failures.serial.test.ts b/test/persistence-sync-failures.serial.test.ts
index 783b78aa39..f5c94b4f0c 100644
--- a/test/persistence-sync-failures.serial.test.ts
+++ b/test/persistence-sync-failures.serial.test.ts
@@ -16,6 +16,7 @@ import { loadSyncFailures, acknowledgeFailures, autoSkipFailures } from '../src/
import { printSyncResult, runSync } from '../src/commands/sync.ts';
import { buildSingleSyncJsonEnvelope } from '../src/core/sync-embed-backfill.ts';
import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';
+import { classifyManagedSyncOrphans, retireManagedSyncOrphan } from '../src/core/persistence/managed-sync-orphans.ts';
import { checkSyncFailures } from '../src/commands/doctor/checks/sync-failures.ts';
import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
@@ -57,7 +58,8 @@ beforeAll(async () => {
for (const engine of engines) await engine.setConfig('sync.holds', 'fail');
}, 120_000);
-test('withdrawal-conflicted sync resumes only through explicit guarded rediscovery and cannot restore the fact', async () => withEnv(env, async () => {
+// #6712 PR 3 (L7): the next plain sync retries a recorded failure through the guarded rediscovery --retry-failed used to run.
+test('withdrawal-conflicted sync resumes through guarded rediscovery on the next plain sync and cannot restore the fact', async () => withEnv(env, async () => {
for (const engine of engines) {
const body = renderFactsTable([{ rowNum: 1, claim: 'synthetic sync withdrawal', visibility: 'world', kind: 'fact', confidence: 1,
notability: 'medium', active: true }]);
@@ -73,8 +75,7 @@ test('withdrawal-conflicted sync resumes only through explicit guarded rediscove
await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => recordFactWithdrawal(tx, fact.id, f.id), TEST_WRITE_ATTRIBUTION));
await expect(performManagedSync(engine, options)).rejects.toMatchObject({ code: 'revision_conflict' });
expect(await readManagedSyncFailures(engine, [f.id])).toEqual([expect.objectContaining({ phase: 'freeze', path: 'z.md', code: 'revision_conflict' })]);
- await expect(performManagedSync(engine, options)).rejects.toMatchObject({ code: 'revision_conflict' });
- const repaired = await performManagedSync(engine, { ...options, retryFailed: true });
+ const repaired = await performManagedSync(engine, options);
expect(repaired.status).toBe('synced');
const current = (await engine.readPageSnapshot('z', { sourceId: f.id }))!;
expect(current.page.compiled_truth).toContain('Preserve this new prose.');
@@ -88,7 +89,8 @@ afterAll(async () => {
await closePostgres?.(); rmSync(home, { recursive: true, force: true });
});
-test('failed managed receipt stays diagnostic across replay, restart, and explicit repaired admission', async () => withEnv(env, async () => {
+// #6712 PR 3 (L7): an unchanged file replays its recorded failure (no new request); once the fix is committed, the plain sync retries it.
+test('failed managed receipt stays diagnostic across replay and restart, and the plain sync admits it again once repaired', async () => withEnv(env, async () => {
for (const engine of engines) {
const f = await fixture(engine, { 'a.md': 'Useful stable first observation.\n', 'bad.md': '---\ntitle: [broken\n---\nBroken content.\n' });
const options = { sourceId: f.id, noPull: true };
@@ -101,8 +103,6 @@ test('failed managed receipt stays diagnostic across replay, restart, and explic
expect(ledger[0]).toMatchObject({ code: failed.failureCodes![0].code, request_id: failed.failures![0].request_id });
expect(acknowledgeFailures(f.id).count).toBe(0); expect(autoSkipFailures(f.id, ['bad.md']).count).toBe(0);
await disposePersistenceConsumer(engine);
- writeFileSync(join(f.root, 'bad.md'), 'Repaired useful second observation.\n');
- const repairedHead = commit(f.root);
const replay = await performManagedSync(engine, options);
expect(replay).toEqual(failed);
expect(loadSyncFailures().filter(r => r.source_id === f.id)).toEqual(ledger);
@@ -110,8 +110,11 @@ test('failed managed receipt stays diagnostic across replay, restart, and explic
expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();
expect(buildSingleSyncJsonEnvelope(f.id, failed)).toMatchObject({ failures: (failed as any).failures, failure_codes: failed.failureCodes });
let output = ''; printSyncResult(failed, { write: (text: string) => { output += text; } } as any);
- expect(output).toContain('bad.md'); expect(output).toContain('--retry-failed'); expect(output).not.toContain('--skip-failed');
- const repaired = await performManagedSync(engine, { ...options, retryFailed: true });
+ expect(output).toContain('bad.md'); expect(output).toContain(`After repair, run gbrain sync --source ${f.id} --no-pull to retry it under a new request.`);
+ expect(output).not.toContain('--retry-failed'); expect(output).not.toContain('--skip-failed');
+ writeFileSync(join(f.root, 'bad.md'), 'Repaired useful second observation.\n');
+ const repairedHead = commit(f.root);
+ const repaired = await performManagedSync(engine, options);
expect(repaired).toMatchObject({ status: 'first_sync', toCommit: repairedHead });
expect(loadSyncFailures().filter(r => r.source_id === f.id)).toHaveLength(0);
expect((await engine.getPage('bad', { sourceId: f.id }))?.compiled_truth).toContain('Repaired');
@@ -169,7 +172,7 @@ test('CRLF checkout of a newer commit does not replace the stale blob pinned by
const pinned = commit(f.root);
expect(await performManagedSync(engine, options, { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial', filesImported: 1, toCommit: pinned });
const newer = 'Newer last observation.\n';
- writeFileSync(join(f.root, 'z.md'), newer); commit(f.root);
+ writeFileSync(join(f.root, 'z.md'), newer); const newerHead = commit(f.root);
writeFileSync(join(f.root, 'z.md'), newer.replace(/\n/g, '\r\n'));
const blocked = await performManagedSync(engine, options);
expect(blocked).toMatchObject({ status: 'blocked_by_failures', toCommit: pinned, failureCodes: [{ code: 'source_changed', count: 1 }] });
@@ -177,7 +180,11 @@ test('CRLF checkout of a newer commit does not replace the stale blob pinned by
expect((await engine.getPage('z', { sourceId: f.id }))?.compiled_truth).toBe('Original last observation.');
expect(readFileSync(join(f.root, 'z.md'), 'utf8')).toBe(newer.replace(/\n/g, '\r\n'));
expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
- expect(await performManagedSync(engine, options)).toEqual(blocked);
+ // #6712 PR 3 (L7): the next plain sync retries the recorded failure as --retry-failed did: it rediscovers at HEAD, so the
+ // newer bytes import under their own commit and the pinned run never publishes them.
+ expect(await performManagedSync(engine, options)).toMatchObject({ status: 'synced', toCommit: newerHead });
+ expect((await engine.getPage('z', { sourceId: f.id }))?.compiled_truth).toBe('Newer last observation.');
+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(newerHead);
}
}), 120_000);
@@ -196,11 +203,8 @@ test('full sync cannot hide an older failed incremental cursor or repeat its com
const replay = await performManagedSync(engine, options);
expect(replay).toEqual(blocked);
expect(await engine.executeRaw('SELECT id,state,intent,error_code FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id])).toEqual(receipts);
- writeFileSync(join(f.root, 'bad.md'), 'Repaired valid source observation.\n');
- const fullTarget = commit(f.root);
- // #6712 PR 1: one cursor per source, so `--full` resumes the failed cursor instead of starting its own: it stays
- // blocked on the same failure and moves nothing (before, a full run synced under a separate key beside it).
- expect(fullTarget).not.toBe(target);
+ // #6712 PR 1: one cursor per source, so `--full` resumes the failed cursor instead of starting its own; with the file
+ // unchanged it replays the same failure and moves nothing (before, a full run synced under a separate key beside it).
expect(await performManagedSync(engine, { ...options, full: true })).toMatchObject({ status: 'blocked_by_failures', runId: blocked.runId, toCommit: target });
const [source] = await engine.executeRaw('SELECT last_commit,last_sync_at FROM sources WHERE id=$1', [f.id]);
expect(await performManagedSync(engine, options)).toEqual(blocked);
@@ -217,8 +221,13 @@ test('full sync cannot hide an older failed incremental cursor or repeat its com
await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '10 days' WHERE op LIKE 'managed-sync%'");
await purgeStaleCheckpoints(engine);
expect(await performManagedSync(engine, options)).toEqual(blocked);
- const repaired = await performManagedSync(engine, { ...options, retryFailed: true });
- expect(repaired.status).toBe('synced'); expect(repaired.runId).not.toBe(blocked.runId);
+ // #6712 PR 3 (L7): once the file's fix is committed, the `--full` run retries the recorded failure by rediscovering from
+ // HEAD: it converges at the new commit under a new run and does not repeat the committed deletion.
+ writeFileSync(join(f.root, 'bad.md'), 'Repaired valid source observation.\n');
+ const fullTarget = commit(f.root);
+ expect(fullTarget).not.toBe(target);
+ const repaired = await performManagedSync(engine, { ...options, full: true });
+ expect(repaired).toMatchObject({ status: 'synced', toCommit: fullTarget, deleted: 0 }); expect(repaired.runId).not.toBe(blocked.runId);
expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(0);
expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);
}
@@ -248,7 +257,7 @@ test('managed failure retry hints name the failed cursor options locally, shell-
const recorded = { full: true, workingTree: false, srcSubpath: null, exclude: [QUOTED_EXCLUDE], includeHidden: [], strategy: null };
expect(blocked.failures).toEqual([expect.objectContaining({ syncOptions: recorded, processingOptions: expect.objectContaining({ noEmbed: true }) })]);
expect(await readManagedSyncFailures(engine, [f.id])).toEqual([expect.objectContaining({ syncOptions: recorded })]);
- const retry = `gbrain sync --source ${f.id} --no-pull --retry-failed --no-embed --full --exclude 'it'\\''s a dir/**'`;
+ const retry = `gbrain sync --source ${f.id} --no-pull --no-embed --full --exclude 'it'\\''s a dir/**'`;
const local = await checkSyncFailures(engine, { sourceIds: [f.id], remote: false });
expect(local?.message).toContain(`Fix the cause, then run ${retry}.`);
@@ -258,7 +267,7 @@ test('managed failure retry hints name the failed cursor options locally, shell-
expect(remote?.message).not.toContain('--exclude');
const printed = await captureCli(() => printSyncResult(blocked));
- expect(printed).toContain(`After repair, run ${retry} to start a new request.`);
+ expect(printed).toContain(`After repair, run ${retry} to retry it under a new request.`);
const { managedWrite: _diagnostic, ...bare } = blocked;
const printedBare = await captureCli(() => printSyncResult(bare));
expect(printedBare).toContain(`Fix the cause, then run: ${retry} (this admits a fresh run after active work drains).`);
@@ -266,7 +275,7 @@ test('managed failure retry hints name the failed cursor options locally, shell-
const legacy = { ...blocked.failures![0] };
delete legacy.syncOptions; delete legacy.processingOptions;
const printedLegacy = await captureCli(() => printSyncResult({ ...bare, failures: [legacy] }));
- expect(printedLegacy).toContain(`Fix the cause, then run: gbrain sync --source ${f.id} --no-pull --retry-failed with the same options as the failed run (this receipt no longer records them)`);
+ expect(printedLegacy).toContain(`Fix the cause, then run: gbrain sync --source ${f.id} --no-pull with the same options as the failed run (this receipt no longer records them)`);
const d = await fixture(engine, { 'note.md': 'A stable discovery observation.\n' });
const execute = engine.executeRaw;
@@ -278,7 +287,7 @@ test('managed failure retry hints name the failed cursor options locally, shell-
try { await performManagedSync(engine, { sourceId: d.id, noPull: true, exclude: [QUOTED_EXCLUDE] }); }
catch (error) { thrown = error as Error; }
finally { engine.executeRaw = execute; }
- expect(thrown?.message).toContain(`Fix the cause, then run: gbrain sync --source ${d.id} --no-pull --retry-failed --exclude 'it'\\''s a dir/**'`);
+ expect(thrown?.message).toContain(`Fix the cause, then run: gbrain sync --source ${d.id} --no-pull --exclude 'it'\\''s a dir/**'`);
}
}), 120_000);
@@ -307,7 +316,13 @@ test('checkpoint, discovery, and freeze failures remain diagnosable without a fi
const blocked = await performManagedSync(engine, options);
expect(blocked).toEqual(expect.objectContaining({ status: 'blocked_by_failures', failures: [expect.objectContaining({ path: '<checkpoint>', phase: 'checkpoint', code: 'revision_conflict' })] }));
expect(await performManagedSync(engine, options)).toEqual(blocked);
- expect(await performManagedSync(engine, { ...options, retryFailed: true })).toMatchObject({ status: 'synced' });
+ // #6712 PR 3 (L7): --retry-failed is a plain sync now, and no sync rediscovers a checkpoint the source's last_commit moved
+ // away from (#6834); the orphan repair retires the cursor and the next sync discovers from the commit the source records.
+ expect(await performManagedSync(engine, { ...options, retryFailed: true })).toEqual(blocked);
+ const [moved] = (await classifyManagedSyncOrphans(engine, [f.id])).orphans;
+ expect(moved).toMatchObject({ kind: 'unfinished_cursor', reason: 'checkpoint_moved' });
+ expect((await retireManagedSyncOrphan(engine, moved!)).cursor).toBe(true);
+ expect(await performManagedSync(engine, options)).toMatchObject({ status: 'synced' });
expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(0);
const d = await fixture(engine, { 'note.md': 'A stable discovery observation.\n' });
@@ -321,7 +336,7 @@ test('checkpoint, discovery, and freeze failures remain diagnosable without a fi
await expect(performManagedSync(engine, { sourceId: d.id, noPull: true })).rejects.toMatchObject({ code: 'storage_error' });
} finally { engine.executeRaw = execute; }
expect(await readManagedSyncFailures(engine, [d.id])).toEqual([expect.objectContaining({ phase: 'discovery', path: '<discovery>', request_id: null, target: d.head, attempts: 1 })]);
- await performManagedSync(engine, { sourceId: d.id, noPull: true, retryFailed: true });
+ await performManagedSync(engine, { sourceId: d.id, noPull: true });
expect(await readManagedSyncFailures(engine, [d.id])).toHaveLength(0);
const c = await fixture(engine, { 'a.md': 'First enumerated page.\n', 'b.md': 'Second enumerated page.\n' });
@@ -377,7 +392,8 @@ test('local single and all-source CLI JSON carry durable diagnostics and fail th
await runSync(engine, [...flags, '--source', f.id]);
const single = JSON.parse(stdout.trim());
expect(single).toEqual(expect.objectContaining({ sync_status: 'blocked_by_failures', failures: [expect.objectContaining({ path: 'bad.md', source_id: f.id, request_id: expect.any(String), phase: 'receipt' })], counts_scope: 'run_cumulative' }));
- expect(currentExitCode()).toBe(1); expect(stderr).toContain('--retry-failed'); expect(stderr).not.toContain('--skip-failed');
+ expect(currentExitCode()).toBe(1); expect(stderr).toContain(`After repair, run gbrain sync --source ${f.id} --no-pull --no-embed --no-extract --no-schema-pack to retry it under a new request.`);
+ expect(stderr).not.toContain('--retry-failed'); expect(stderr).not.toContain('--skip-failed');
stdout = ''; stderr = '';
try { await runSync(engine, [...flags, '--all', '--serial']); } catch (error) { if ((error as Error).message !== 'fixture-cli-exit') throw error; }
const all = JSON.parse(stdout.trim());
@@ -481,18 +497,21 @@ test('missing manifest re-discovers against HEAD on the next sync; the page the
}
}), 120_000);
+// #6712 PR 3 (L7): an unchanged file replays its recorded failure; a changed one is admitted again by the plain sync.
test('a new failed admission increments attempts but repeating retry during repaired progress does not reset the run', async () => withEnv(env, async () => {
for (const engine of engines) {
const f = await fixture(engine, { 'a.md': 'Useful successful first observation.\n', 'bad.md': '---\ntitle: [broken\n---\nFailed observation.\n' });
const options = { sourceId: f.id, noPull: true };
const first = await performManagedSync(engine, options);
- const second = await performManagedSync(engine, { ...options, retryFailed: true });
+ expect(await performManagedSync(engine, { ...options, retryFailed: true })).toEqual(first);
+ writeFileSync(join(f.root, 'bad.md'), '---\ntitle: [still broken\n---\nFailed observation.\n');
+ const second = await performManagedSync(engine, options);
expect(second.failures![0].request_id).not.toBe(first.failures![0].request_id);
expect(second.failures![0].attempts).toBe(2);
expect(await performManagedSync(engine, options)).toEqual(second);
writeFileSync(join(f.root, 'bad.md'), 'Repaired successful second observation.\n'); commit(f.root);
const slice = { maxPages: 1, maxMs: 1000 };
- const start = await performManagedSync(engine, { ...options, retryFailed: true }, slice);
+ const start = await performManagedSync(engine, options, slice);
expect(start.status).toBe('partial'); expect(start.filesImported).toBe(1);
const continued = await performManagedSync(engine, { ...options, retryFailed: true }, slice);
expect(continued.runId).toBe(start.runId); expect(continued.filesImported).toBe(2);
diff --git a/test/sync-cancelled-knock-on.test.ts b/test/sync-cancelled-knock-on.test.ts
index 9cbc73d7c8..ab788dfafd 100644
--- a/test/sync-cancelled-knock-on.test.ts
+++ b/test/sync-cancelled-knock-on.test.ts
@@ -22,7 +22,7 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';
import { managedSyncRetryCommand, readManagedSyncFailures, recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';
-import { claimedHeadOrder, laneFaultBlockedReason, laneFaultCancelMessage, laneFaultInMessage, laneFaultOf, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';
+import { claimedHeadOrder, laneFaultBlockedReason, laneFaultCancelMessage, laneFaultInMessage, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';
import { submissionAuthority } from '../src/core/persistence/authority.ts';
import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
@@ -127,8 +127,6 @@ test('#6712: a head whose window predecessor was never admitted publishes on its
test('#6402 residual (P4.3) / #6712: a lane group released after a lock timeout keeps the fault on its rows and publishes after a failed predecessor', async () => withEnv({ GBRAIN_HOME: home }, async () => {
expect(laneFaultBlockedReason('lock_timeout')).toBe('lane_lock_timeout');
- expect(laneFaultOf('lane_statement_timeout')).toBe('statement_timeout');
- expect(laneFaultOf('group_member_waiting')).toBeNull();
await registerLocalWriter(engine, 'cli');
const f = await fixture({ 'seed.md': note('Seed.') });
const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [f.id]);
diff --git a/test/sync-checkpoint-moved-6834.test.ts b/test/sync-checkpoint-moved-6834.test.ts
index 24b6f6ea84..3946d8dc4b 100644
--- a/test/sync-checkpoint-moved-6834.test.ts
+++ b/test/sync-checkpoint-moved-6834.test.ts
@@ -230,7 +230,7 @@ describe('#6834 a managed-sync checkpoint whose source checkpoint moved', () =>
expect(await unfinished(engine, f)).toBe(0);
}), 180_000);
- test.each([['the run\'s own target'], ['a newer commit']] as const)('a path slice short of its target whose checkpoint moved to %s is listed, and retiring it clears its slice record', moved => each(async engine => {
+ test.each([['the run\'s own target'], ['a newer commit']] as const)('a path slice short of its target whose checkpoint moved to %s is listed, no sync rediscovers it, and retiring it clears its slice record', moved => each(async engine => {
_setCursorBoundForTest();
await disposePersistenceConsumer(engine);
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
@@ -256,6 +256,14 @@ describe('#6834 a managed-sync checkpoint whose source checkpoint moved', () =>
await moveCheckpoint(engine, f, moved === 'a newer commit' ? newer : target);
expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('blocked_by_failures');
expect((await classifyManagedSyncOrphans(engine, [id])).orphans.map(orphan => orphan.reason)).toEqual(['checkpoint_moved']);
+ // #6712 PR 3 (L7): neither a plain sync nor its --retry-failed alias rediscovers it. Rediscovering would resume the slice
+ // record and finish at the slice's target, moving last_commit back from a newer commit; the repair clears the record.
+ _setCursorBoundForTest();
+ for (const retryFailed of [false, true]) {
+ expect((await outcome(performManagedSync(engine, { ...f.opts, retryFailed }))).status).toBe('blocked_by_failures');
+ expect(await lastCommit(engine, f)).toBe(moved === 'a newer commit' ? newer : target);
+ expect(await slices()).toBe(1);
+ }
const preview = await repair(engine, f);
expect((await repair(engine, f, preview.preview_hash)).applied).toBe(1);
expect(await slices()).toBe(0);
@@ -275,11 +283,13 @@ describe('#6834 a managed-sync checkpoint whose source checkpoint moved', () =>
expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('blocked_by_failures');
const preview = await repair(engine, f);
const previewed = (await classifyManagedSyncOrphans(engine, [f.id])).orphans[0]!;
- // --retry-failed replaces the run under the same key; the replacement stops before its checkpoint, which moves too.
+ // A run replaced under the same key (here: its manifest is lost, so the next sync re-discovers at HEAD; #6712 PR 3 took
+ // that rediscovery away from --retry-failed); the replacement stops before its checkpoint, which moves too.
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [previewed.run_id]);
writeFileSync(join(f.root, 'notes', 'beta.md'), note('beta', 'A revised observation'));
const head = commit(f.repo, 'beta');
const abort = new AbortController();
- expect((await outcome(performManagedSync(engine, { ...f.opts, retryFailed: true, signal: abort.signal, onProgress: p => { if (p.total && p.bankedFiles === p.total) abort.abort(); } }))).status).toBe('partial');
+ expect((await outcome(performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (p.total && p.bankedFiles === p.total) abort.abort(); } }))).status).toBe('partial');
await moveCheckpoint(engine, f, f.seed);
expect((await outcome(performManagedSync(engine, f.opts))).status).toBe('blocked_by_failures');
const current = (await classifyManagedSyncOrphans(engine, [f.id])).orphans[0]!;
diff --git a/test/sync-knock-on-recovery-6643.test.ts b/test/sync-knock-on-recovery-6643.test.ts
index b0e5baa986..2ce9d1dd3e 100644
--- a/test/sync-knock-on-recovery-6643.test.ts
+++ b/test/sync-knock-on-recovery-6643.test.ts
@@ -195,7 +195,8 @@ test('the checkpoint waits on every receipt the cursor did not settle, a legacy
} finally { await clearConfig(); }
}), 120_000);
-for (const retryFailed of [false, true]) test(`#6712: a checkpoint a legacy knock-on still blocks ${retryFailed ? 'is rediscovered by the --retry-failed repro command and finishes' : 'stays blocked under the plain sync, naming the knock-on'}`, async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+// #6712 PR 3 (L7): --retry-failed is a deprecated alias of the plain sync, so both rediscover the run and finish.
+for (const retryFailed of [false, true]) test(`#6712: a checkpoint a legacy knock-on still blocks is rediscovered by the next ${retryFailed ? '--retry-failed (plain sync alias)' : 'plain'} sync and finishes`, async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
try {
const f = await stoppedRun();
// The pre-#6643 shape: the cursor passed the stopped page (no settled ranges recorded) and froze its checkpoint.
@@ -210,11 +211,6 @@ for (const retryFailed of [false, true]) test(`#6712: a checkpoint a legacy knoc
await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, null);
expect((await readSyncStatus(engine, f.id)).checkpoint_blockers).toEqual([expect.objectContaining({ request_id: f.stopped, slug: 'b', knock_on: true })]);
const resumed = await performManagedSync(engine, { ...f.opts, retryFailed });
- if (!retryFailed) {
- expect(resumed.status).toBe('blocked_by_failures');
- expect((await readSyncStatus(engine, f.id)).cursor?.done).not.toBe(true);
- return;
- }
expect(resumed.status).not.toBe('blocked_by_failures');
expect((await readSyncStatus(engine, f.id)).cursor).toMatchObject({ done: true });
const [source] = await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]);
diff --git a/test/sync-managed-help-l7-6712.test.ts b/test/sync-managed-help-l7-6712.test.ts
new file mode 100644
index 0000000000..f2ac2ba639
--- /dev/null
+++ b/test/sync-managed-help-l7-6712.test.ts
@@ -0,0 +1,209 @@
+/**
+ * #6712 PR 3 (L7): the managed sync surface an operator or a cron needs.
+ *
+ * - `gbrain sync --help` lists the "Managed brains" flags first (at most 10, exactly `MANAGED_HELP_FLAGS`), then a
+ * "Classic brains / advanced" section with every other flag; no flag is listed twice.
+ * - Doctor's printed managed cron recipe passes the managed flag validator (parse, the managed-forbidden refusal, the
+ * hard-deadline resolution) and syncs every source of a managed brain. `--all`, `--hard-deadline`, `--no-bulk` and
+ * `--no-lanes` stay accepted on a managed source.
+ * - `--retry-failed` is a deprecated alias of the plain sync: it prints the `sync_retry_failed_deprecated` coaching
+ * notice once and syncs exactly like the plain command.
+ * - Every removed state renders `superseded`: retired registry codes and the legacy knock-on receipts older builds wrote.
+ * - The plain sync replays a content refusal without a new request while the file and the gbrain version that recorded it
+ * are unchanged, and retries a failure an older build recorded (it carries no `gbrain_version`).
+ *
+ * Regression guarded: a managed flag dropped from the managed section or left out of `MANAGED_HELP_FLAGS`, the
+ * cron recipe naming a flag the managed validator refuses, or `--retry-failed` silently changing what a sync does.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { runSync } from '../src/commands/sync.ts';
+import { noteRetryFailedDeprecated, parseSyncFlags, printSyncHelp, RETRY_FAILED_DEPRECATED } from '../src/commands/sync/args.ts';
+import { refuseManagedForbiddenFlags } from '../src/commands/sync/managed-no-pull.ts';
+import { checkSyncConsolidation } from '../src/commands/doctor.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';
+import { VERSION } from '../src/version.ts';
+import { managedForbiddenFlag } from '../src/core/persistence/managed-sync-flags.ts';
+import { MANAGED_HELP_FLAGS, SYNC_FLAGS } from '../src/core/sync-flags.ts';
+import { resolveSyncHardDeadline } from '../src/core/sync-reconcile.ts';
+import { CODES, NOTICE_CODES } from '../src/core/error-registry.ts';
+import { publicCategory } from '../src/core/persistence/public-category.ts';
+import { classifyTerminal } from '../src/core/persistence/terminal-classify.ts';
+import { BULK_GROUP_CANCEL_MESSAGE, knockOnDetail, LEGACY_KNOCK_ON_CANCEL_MESSAGES } from '../src/core/persistence/sync-knock-on.ts';
+import { laneFaultCancelMessage, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-help-'));
+let engine: BrainEngine;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_BACKUP_CHECK: 'off', GBRAIN_SYNC_NO_EXTRACT_NUDGE: '1', OPENAI_API_KEY: undefined };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ // The recipe carries no --no-embed, so the embedding preflight needs a configured key; the sync itself never calls the provider.
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test-not-a-key' } });
+}, 120_000);
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+ resetGateway();
+ rmSync(home, { recursive: true, force: true });
+});
+
+/** Managed sources, each a one-commit checkout; every other source is left out of `--all`. */
+async function managedSources(count: number): Promise<Array<{ id: string; head: string }>> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("UPDATE sources SET config=jsonb_set(config,'{syncEnabled}','false'::jsonb)");
+ const made: Array<{ id: string; head: string }> = [];
+ for (let i = 0; i < count; i++) {
+ const id = `help-${randomUUID().slice(0, 12)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ writeFileSync(join(root, 'a.md'), '---\ntitle: a\n---\nA durable observation about acme-example.\n');
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ made.push({ id, head: git(root, 'rev-parse', 'HEAD') });
+ }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return made;
+}
+const lastCommit = async (id: string) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]?.last_commit ?? null;
+async function captured<T>(fn: () => Promise<T>): Promise<{ value: T; stderr: string; exitCode?: number }> {
+ const origError = console.error, origLog = console.log, origWrite = process.stderr.write.bind(process.stderr), origOut = process.stdout.write.bind(process.stdout);
+ let stderr = '';
+ console.error = (...parts: unknown[]) => { stderr += parts.join(' ') + '\n'; }; console.log = () => {};
+ process.stderr.write = ((chunk: string | Uint8Array) => { stderr += String(chunk); return true; }) as typeof process.stderr.write;
+ process.stdout.write = (() => true) as typeof process.stdout.write;
+ const origExit = process.exit;
+ let exitCode: number | undefined;
+ process.exit = ((code?: number) => { exitCode = code ?? 0; throw new Error('fixture-cli-exit'); }) as typeof process.exit;
+ try {
+ const value = await fn().catch((error: unknown) => { if ((error as Error)?.message === 'fixture-cli-exit') return undefined as T; throw error; });
+ return { value, stderr, exitCode };
+ } finally { console.error = origError; console.log = origLog; process.stderr.write = origWrite; process.stdout.write = origOut; process.exit = origExit; }
+}
+
+/** The option flags printed under each help section, in order. */
+function helpSections(): { managed: string[]; classic: string[]; order: string[] } {
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(...parts.join(' ').split('\n')); };
+ try { printSyncHelp(); } finally { console.log = log; }
+ const managedAt = lines.findIndex(line => line.startsWith('Managed brains'));
+ const classicAt = lines.findIndex(line => line.startsWith('Classic brains / advanced'));
+ const flags = (from: number, to: number) => lines.slice(from + 1, to).flatMap(line => /^ (--[a-z][a-z-]*)/.exec(line)?.[1] ?? []);
+ const end = lines.findIndex((line, i) => i > classicAt && /^\S/.test(line));
+ return { managed: flags(managedAt, classicAt), classic: flags(classicAt, end === -1 ? lines.length : end), order: [String(managedAt), String(classicAt)] };
+}
+
+test('sync --help lists the managed flags first (at most 10, exactly MANAGED_HELP_FLAGS), then every other flag under Classic', () => {
+ const { managed, classic, order } = helpSections();
+ expect(Number(order[0])).toBeGreaterThan(0);
+ expect(Number(order[1])).toBeGreaterThan(Number(order[0]));
+ expect(managed.length).toBeLessThanOrEqual(10);
+ expect([...managed].sort()).toEqual([...MANAGED_HELP_FLAGS].sort());
+ expect(managed.filter(flag => classic.includes(flag))).toEqual([]);
+ expect(new Set(managed).size).toBe(managed.length);
+ expect(new Set(classic).size).toBe(classic.length);
+ // The flags a managed source refuses, and the deprecated alias, are classic.
+ for (const flag of ['--skip-failed', '--include-gitignored', '--retry-failed', '--full', '--no-embed']) expect(classic).toContain(flag);
+ // Every flag the help documents is a parsed sync flag.
+ const parsed = Object.keys(SYNC_FLAGS);
+ expect([...managed, ...classic].filter(flag => !parsed.includes(flag) && !['--help', '--watch', '--interval', '--repo', '--force-break-lock', '--max-age', '--yes', '--missing-path', '--parallel', '--workers', '--concurrency', '--serial'].includes(flag))).toEqual([]);
+ // No managed flag is one a managed source refuses.
+ for (const flag of managed) expect(['--skip-failed', '--include-gitignored']).not.toContain(flag);
+});
+
+test("doctor's managed cron recipe passes the managed flag validator and syncs every source", async () => withEnv(env, async () => {
+ const sources = await managedSources(2);
+ const check = await checkSyncConsolidation(engine);
+ const recipe = /`(gbrain sync [^`]+)`/.exec(check.message)?.[1];
+ expect(recipe).toBe('gbrain sync --all --no-pull --hard-deadline 13m');
+ const args = recipe!.split(' ').slice(2);
+ for (const flag of args.filter(arg => arg.startsWith('--'))) expect(MANAGED_HELP_FLAGS as string[]).toContain(flag);
+ const flags = parseSyncFlags(args);
+ expect(flags).toMatchObject({ syncAll: true, noPull: true, skipFailed: false, includeGitignored: false });
+ expect(managedForbiddenFlag(flags)).toBeNull();
+ await refuseManagedForbiddenFlags(engine, flags, args);
+ expect(resolveSyncHardDeadline(args, { isTty: false, env: {} })).toMatchObject({ deadlineMs: 13 * 60_000, reason: 'flag:--hard-deadline' });
+ expect((await captured(() => runSync(engine, args))).exitCode).toBeUndefined();
+ for (const source of sources) expect(await lastCommit(source.id)).toBe(source.head);
+}), 120_000);
+
+test('--all, --hard-deadline, --no-bulk and --no-lanes stay accepted on a managed source', async () => withEnv(env, async () => {
+ const [source] = await managedSources(1);
+ await captured(() => runSync(engine, ['--source', source!.id, '--no-pull', '--no-bulk', '--no-lanes', '--hard-deadline', '13m']));
+ expect(await lastCommit(source!.id)).toBe(source!.head);
+ const [other] = await managedSources(1);
+ await captured(() => runSync(engine, ['--all', '--no-pull', '--no-bulk', '--no-lanes', '--hard-deadline', '13m']));
+ expect(await lastCommit(other!.id)).toBe(other!.head);
+}), 120_000);
+
+test('--retry-failed is a deprecated alias of the plain sync: it prints the coaching notice once and syncs the same', async () => withEnv(env, async () => {
+ expect(NOTICE_CODES.sync_retry_failed_deprecated).toMatchObject({ kind: 'coaching' });
+ expect(RETRY_FAILED_DEPRECATED).toContain('a plain gbrain sync now retries');
+ const plainSource = (await managedSources(1))[0]!;
+ const plain = await captured(() => runSync(engine, ['--source', plainSource.id, '--no-pull']));
+ expect(plain.stderr).not.toContain('sync_retry_failed_deprecated');
+ const aliasSource = (await managedSources(1))[0]!;
+ const alias = await captured(() => runSync(engine, ['--source', aliasSource.id, '--no-pull', '--retry-failed']));
+ expect(alias.stderr.match(/\[gbrain notice sync_retry_failed_deprecated\]/g)).toHaveLength(1);
+ expect(alias.stderr).toContain(RETRY_FAILED_DEPRECATED);
+ expect(await lastCommit(plainSource.id)).toBe(plainSource.head);
+ expect(await lastCommit(aliasSource.id)).toBe(aliasSource.head);
+ // Once per process: the CLI pipeline and the sync command both call it.
+ const again = await captured(async () => noteRetryFailedDeprecated(['--retry-failed']));
+ expect(again.stderr).toBe('');
+}), 120_000);
+
+test('every removed state renders superseded: retired codes, and the legacy knock-on receipts older builds wrote', () => {
+ const retired = Object.entries(CODES).filter(([, entry]) => (entry as { retired_in?: string }).retired_in).map(([code]) => code);
+ expect(retired.length).toBeGreaterThan(0);
+ for (const code of retired) expect([code, publicCategory({ code })]).toEqual([code, 'superseded']);
+ const row = (state: string, code: string, message: string | null, detail: object | null = null) => classifyTerminal({ request_id: 'r', source_id: 'default', slug: 's',
+ operation: 'submit_job', state, error_code: code, error_detail: detail, recovery: null, blocked_reason: null, compacted: false, publication_started: false,
+ intent_kind: 'managed_sync_import', error_message: message });
+ const legacy = [
+ row('cancelled', 'cancelled', WINDOW_CANCEL_MESSAGE),
+ row('cancelled', 'cancelled', laneFaultCancelMessage('lock_timeout')),
+ row('cancelled', 'cancelled', BULK_GROUP_CANCEL_MESSAGE),
+ ...LEGACY_KNOCK_ON_CANCEL_MESSAGES.map(message => row('cancelled', 'cancelled', message)),
+ row('cancelled', 'storage_error', null, knockOnDetail('window_predecessor', null)),
+ ];
+ for (const verdict of legacy) expect(verdict).toMatchObject({ public_category: 'superseded' });
+});
+
+
+test('a content refusal replays without a new request while the file and the recording version are unchanged, and a failure an older build recorded is retried once', async () => withEnv(env, async () => {
+ const [source] = await managedSources(1);
+ const root = (await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM sources WHERE id=$1', [source!.id]))[0]!.local_path;
+ writeFileSync(join(root, 'bad.md'), '---\ntitle: [broken\n---\nBroken content.\n');
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'bad');
+ await engine.setConfig('sync.holds', 'fail');
+ const opts = { sourceId: source!.id, noPull: true, noEmbed: true, noExtract: true };
+ const requestOf = async () => (await readManagedSyncFailures(engine, [source!.id]))[0]?.request_id;
+ try {
+ expect((await performManagedSync(engine, opts)).status).toBe('blocked_by_failures');
+ const first = await requestOf();
+ expect(first).toBeTruthy();
+ expect((await readManagedSyncFailures(engine, [source!.id]))[0]).toMatchObject({ gbrain_version: VERSION });
+ expect((await performManagedSync(engine, opts)).status).toBe('blocked_by_failures');
+ expect(await requestOf()).toBe(first);
+ // A row an older build recorded carries no gbrain_version: its parser may have refused what this one reads, so it is retried.
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0}',(completed_keys->0)-'gbrain_version') WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$1", [source!.id]);
+ expect((await performManagedSync(engine, opts)).status).toBe('blocked_by_failures');
+ const retried = await requestOf();
+ expect(retried).not.toBe(first);
+ expect((await performManagedSync(engine, opts)).status).toBe('blocked_by_failures');
+ expect(await requestOf()).toBe(retried);
+ } finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'"); }
+}), 120_000);
+
diff --git a/test/sync-slug-root-mode-6694.test.ts b/test/sync-slug-root-mode-6694.test.ts
index eb30458960..82bae84295 100644
--- a/test/sync-slug-root-mode-6694.test.ts
+++ b/test/sync-slug-root-mode-6694.test.ts
@@ -21,6 +21,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';
+import { classifyManagedSyncOrphans, retireManagedSyncOrphan } from '../src/core/persistence/managed-sync-orphans.ts';
import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';
import { CODES } from '../src/core/error-registry.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
@@ -123,12 +124,18 @@ describe('#6694 managed-sync checkpoint under a pinned slug_root_mode', () => {
expect(await slugs(engine, f)).toEqual(['notes/alpha', 'notes/beta', 'notes/gamma']);
}), 120_000);
- test('keeping a changed pin, --retry-failed discovers the subdirectory source again under it, beside the pages the refused run wrote', async () => each(async engine => {
+ // #6712 PR 3 (L7): --retry-failed is a plain sync now, so keeping the pin is the orphan repair's preview-first retirement.
+ test('keeping a changed pin: no sync rediscovers it, and retiring the slug_mode_refused cursor discovers the subdirectory source again under it, beside the pages the refused run wrote', async () => each(async engine => {
const f = await fixture(engine, 'brain', 'source-root');
await beforeCheckpoint(engine, f, 3);
await engine.executeRaw(`UPDATE sources SET config=jsonb_set(config,'{slug_root_mode}','"git-root"') WHERE id=$1`, [f.id]);
expect(JSON.stringify(await outcome(performManagedSync(engine, f.opts)))).toContain('slug_root_mode_mismatch');
- const retried = await outcome(performManagedSync(engine, { ...f.opts, retryFailed: true }));
+ for (const retryFailed of [false, true]) expect(JSON.stringify(await outcome(performManagedSync(engine, { ...f.opts, retryFailed })))).toContain('slug_root_mode_mismatch');
+ expect(await source(engine, f)).toEqual({ last_commit: null, mode: 'git-root' });
+ const [refused] = (await classifyManagedSyncOrphans(engine, [f.id])).orphans;
+ expect(refused).toMatchObject({ kind: 'unfinished_cursor', reason: 'slug_mode_refused' });
+ expect((await retireManagedSyncOrphan(engine, refused!)).cursor).toBe(true);
+ const retried = await outcome(performManagedSync(engine, f.opts));
expect(retried).not.toHaveProperty('thrown');
expect(await source(engine, f)).toEqual({ last_commit: f.head, mode: 'git-root' });
// The pages the refused run wrote under source-root keep their slugs beside the git-root ones; that is the cost the user accepts.