Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): status agrees with itself (#7189 status half); held budget pages read pending_embedding in resolve-path

garrytan19a69f4a6af4
diff --git a/docs/architecture/key-files/commit-notifier.md b/docs/architecture/key-files/commit-notifier.md
index 2b22b7f532..41030cfbe1 100644
--- a/docs/architecture/key-files/commit-notifier.md
+++ b/docs/architecture/key-files/commit-notifier.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/notifier/store.ts` — the durable rows (migration `v262-commit-notifier.ts`): `sync_wanted_markers` (source + intent freshness|pull|full, `generation` bumped on every upsert, `first_due_at` kept), `sync_notifier_leases` (one owner per host, fence bumped on takeover, release expires it now), `sync_notifier_sources` (state, retry schedule, last error and trace path, classic syncer host, coverage record). A drainer deletes only `WHERE generation =` the value it read (`clearMarker`, `settleMarkers`); freshness is due while `wanted_head IS DISTINCT FROM last_commit` (no ancestry assumption). `recordLocalSyncer` runs where `writeSyncAnchor` advances `last_commit`: records the syncer host and prunes satisfied markers (the CLI's re-check). `missingTable` lets callers on a pre-v262 brain read "nothing monitored".
- `src/core/notifier/resident.ts` + `src/core/notifier/detect.ts` — production seams and the one start path for every resident (`startResidentNotifier`: serve, serve --http through `src/core/serve-head-watcher.ts`, `gbrain jobs work`, the autopilot daemon). Never awaits: the first pass runs in the background. `GBRAIN_NOTIFIER=0` turns it off per process. Lists managed sources whose worktree this host owns and classic sources whose recorded syncer is this host (or `GBRAIN_NOTIFIER_CLASSIC_SOURCES`), skipping the rest with a reason. Starts syncs through the in-process delegated runner. Trace per source at `<gbrain home>/notifier/<source>.jsonl`. `detect.ts` resolves `--absolute-git-dir` / `--git-common-dir` (linked worktrees) and the quiet predicate. Tests: `test/pathological/s-notifier-classic-serve.test.ts`, `test/pathological/s-notifier-residents.test.ts`.
- `src/core/notifier/nudge.ts` + `src/core/notifier/handoff.ts` + `src/commands/sync/trigger.ts` — submitters and drainers of wanted markers. `recordTriggerMarker` picks the intent (managed: freshness at the checkout HEAD; classic: pull) and `recordSyncNudge` answers the versioned, acknowledged `sync_nudge` IPC kind (`src/core/context/sync-ipc.ts`, `resolve-ipc.ts`, bound in `src/mcp/resolve-ipc-binding.ts`). `handoff.ts` is the post-run re-check of the `sync` job handler and the serve's delegated runner: read before the run, settle after, at most one follow-up (a queued job with `maxWaiting: 1`, or a nudge); a lock-busy skip records a marker and completes. `gbrain sync trigger` answers queued / coalesced (`maxPending: 1`) / nudged, exit 0, with the `no_resident` notice when no resident watches the source; on PGLite a live serve takes it over IPC (`maybeTriggerThroughServe` in `src/commands/sync-delegate.ts`, which also records a busy delegated sync). The GitHub push webhook (`submitGitHubPush` in `src/commands/serve-http-webhooks.ts`) records the pushed sha first; a managed source answers 409 `refresh_required`. Tests: `test/pathological/s-notifier-marker-handoff.test.ts`.
-- `src/core/notifier/status.ts` — what users and agents see, from rows only (no git call): `readSourceFreshness` feeds the `freshness` entry of search and query responses (`src/core/ops/search.ts` `buildRetrievalResponseMeta`; current, behind, syncing, unknown, not_monitored), and `readNotifierBlock` / `formatNotifierBlock` the notifier block for sync status and doctor (resident or none with the `gbrain sync --source <id> --no-pull` fix; remote callers get no trace path, pid or host id). An owner is live by its unexpired lease (Postgres) or a running pid on this host (PGLite). Tests: `test/pathological/s-notifier-freshness-status.test.ts`.
+- `src/core/notifier/status.ts` — what users and agents see, from rows only (no git call): `readSourceFreshness` feeds the `freshness` entry of search and query responses (`src/core/ops/search.ts` `buildRetrievalResponseMeta`; current, behind, syncing, unknown, not_monitored), and `readNotifierBlock` / `formatNotifierBlock` the notifier block for sync status and doctor (resident or none with the `gbrain sync --source <id> --no-pull` fix; remote callers get no trace path, pid or host id). An owner is live by its unexpired lease (Postgres) or a running pid on this host (PGLite). Tests: `test/pathological/s-notifier-freshness-status.test.ts`. #7189: with no live notifier owner, `readNotifierBlock` reads the drain lease holder (`readDrainHolder`, `drain_holder`, redacted by `publicDrainHolder` for remote callers) and offers no fix while it progresses, the sync-now fix only once `holderStalled`; `formatNotifierBlock` names it (`test/sync-status-coherence-7189.test.ts`).
## Autopilot and the jobs worker
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index c7874f2494..08f3e86970 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -44,4 +44,4 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/soak-counters.ts` — #6712 PR 2: the soak counters doctor `sync_soak_counters` reports (one `op_checkpoints` row per UTC day under op `sync-soak-counters`). Interventions: `sync_non_plain` (`nonPlainSyncFlags`, from `sync/run.ts`), `repair_apply` (`repair.ts`), `unblock_apply` (`sync/operator.ts`), `retry_held` (`sources-retry-held.ts`) and `needs_human` (`sweepNeedsHumanHolds`, run after each managed sync: stamps `needs_human_at` on a hold the fault table now calls `needs_human` and counts it once; the stamp survives same-code re-holds). Content decisions: `file_drift_apply` and `file_drift_hold`. `readSoakCounters` sums the last seven days. Counting never fails the command that counts. Test: `test/sync-exits-l4-6712.test.ts`.
- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark: one probe of the partial index `persistence_requests_sync_watermark`, v223; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the writer-status command beside `data_moving: false`; doctor `managed_sync_not_moving` (warn, scored for `not_moving` only) uses the same rule and command as its fix, and fails on a parked cursor whose admitted queue has no consumer past the ceiling (#6552; fix: the resume sync); `serve` prints one `[gbrain notice]` when a source flips. A failed backlog read is `unknown`, never `nothing_pending` (doctor warns). `/health` stays liveness-only.
- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). The printed step is `MOVEMENT_SUPERVISOR_STEP` from the import-free leaf `src/commands/movement-step.ts` (re-exported here), so upgrade loads it before the swap (#6604). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` (backlog unreadable) exits 1 with `movement_unknown`; other read failures keep their code. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.
-- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`.
+- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`. #7189: each `SourceFreshness` carries `behind` (`readGitBehind`, injectable `BehindReader`: `rev-list --count <last_commit>..HEAD` and the oldest of those commits' committer age; null without a checkout or a synced commit), printed by `formatSyncFreshness`.
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index d965f5eda4..0669380074 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -35,7 +35,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks with `identity: 'reservation'` (#5914: it publishes nothing, so a recreated directory whose reservation names the worktree and whose stamp carries the same token releases; a token mismatch refuses), then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.
- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.
- `src/core/persistence/sync-page-fault.ts` — #6340: a page that moved under a managed catch-up holds the page, not the run. `headCommittedBytes` returns the working-tree bytes of a path when their blob id equals `HEAD:<path>` (sha1 or sha256 by HEAD's id length), so `freezeEntry` imports bytes committed past the pinned target as HEAD has them (the later pin..HEAD diff re-imports them as a no-op; idea and first test from PR #6323, which this supersedes) and `prepareManagedSyncMutation`'s `newerWorkingTree` screen never sees them. `pageChangeProof` is #6194's revision-linked proof usable at freeze time; `pageChangedHold` builds the `concurrent_write` hold for a database page that was edited, deleted or re-bound after enumeration (with the competing request when proven, else `page_revision` + `expected_revision`), `worktreeDirtyHold` the new `worktree_dirty` hold (pinned `blob_oid`, `working_hash`) for uncommitted bytes that match neither the pin nor the page, `pinnedWorktreeConflict` recognizes that receipt and `pageMovedSinceAdmission` a `revision_conflict` receipt whose page really moved (a run-level conflict with the page where it was still blocks). In `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws (`page_identity_changed`, `revision_conflict`, the renamed-source conflict) into holds when holds are on (a page that still holds exactly what the import carries is re-bound to its new revision and passed by the waiver screen; `sync.holds=fail` and company-brain cursors keep the refusals), `holdFailedFenceRequest` converts the two receipts (imports and deletes) through `receiptPageFaultHold`, re-freezes an entry once under a fresh request when its file changed between admission and publication (`fileChangedAfterAdmission`, the `raw_file_changed` receipt: committed bytes then import as HEAD has them, a second change under the re-frozen request is held `worktree_dirty`; `holdUnderGate` takes `refrozen` in place of `hold` and records the conversion as `refrozen`), `convertBlockedCursor` converts a cursor an older release left blocked (re-freezing a dirty file that is committed now), `originFaultHold` holds an entry whose recorded origin no longer identifies the enumerated page (`assertSyncPageOrigin` at freeze), every page-fault hold marks the cursor `overtaken` (#5522: another cursor may have checkpointed this target), and the `--retry-failed` start tries that conversion before rediscovering, so the frozen manifest survives. `writeGitHold` counts `meta.attempts` per re-hold with the same code; `HOLD_ATTEMPTS_NEEDS_HUMAN` (3) turns a page hold into `needs_human`. The run's catch skips the failure ledger for `isRetryableConnError` / statement timeouts. Tests: `test/managed-sync-page-fault-holds.test.ts` (freeze-time DB edit → hold, same content → re-bind, dirty → `worktree_dirty` → commit → import, committed past pin → HEAD bytes, old blocked cursor → in-place conversion with attempts, connection death → no ledger row, same run on relaunch, one extra pass), the updated expectations in `test/persistence-managed-sync.test.ts` and `test/managed-sync-concurrent-write-hold.test.ts`.
-- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate; #6518: the newest cursor recorded under the source's *current* incarnation, the only one a current sync can select), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). When no current-incarnation cursor or failure exists but an unfinished cursor stands under an older incarnation, the status is `cursor: null` with `last_error.code: cursor_incarnation_retired` (table row: systemic, `repair`, no human) and `next` is the `gbrain repair managed-sync-orphans --source <id>` preview, never a sync that selects nothing. #6712 PR 2 (L5): `state`/`reason` (`SYNC_STATUS_REASONS`), the bounded `oldest_blocker` (the drain's head probe) and `recovery` probes; `readSyncStatus(…, { detail })` skips the terminal summary, blocker list and cursor join when false (the plain CLI), each with a `<field>_read` `not_read` sibling; `syncStatusHeadline` is the text headline. `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them; `syncOperatorVerb` makes `sync --status` the status read) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`). GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`).
+- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate; #6518: the newest cursor recorded under the source's *current* incarnation, the only one a current sync can select), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). When no current-incarnation cursor or failure exists but an unfinished cursor stands under an older incarnation, the status is `cursor: null` with `last_error.code: cursor_incarnation_retired` (table row: systemic, `repair`, no human) and `next` is the `gbrain repair managed-sync-orphans --source <id>` preview, never a sync that selects nothing. #6712 PR 2 (L5): `state`/`reason` (`SYNC_STATUS_REASONS`), the bounded `oldest_blocker` (the drain's head probe) and `recovery` probes; `readSyncStatus(…, { detail })` skips the terminal summary, blocker list and cursor join when false (the plain CLI), each with a `<field>_read` `not_read` sibling; `syncStatusHeadline` is the text headline. `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them; `syncOperatorVerb` makes `sync --status` the status read) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`). GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error.
- `src/core/persistence/sync-drain.ts` (#6340 additions) — `isConnectionDrop` (a retryable connection error that is not #6329's `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` settle discard; `retry-matcher.ts` now matches `ECONNABORTED`, `ETIMEDOUT` and `EPIPE` beside `ECONNRESET`); `runDrain` reconnects (`DrainInput.reconnect`, `engine.reconnect` from `drainManagedSync`) and retries a dropped pass on `CONNECTION_RETRY_MS` (5/15/45 s), resets the count on every committed page, and after `CONNECTION_STRIKES` drops with no commit between them ends `blocked` / `connection_lost` with `drain.connection { drops, last_error }` (URLs stripped) and the resume command as a loopable `next` (`sync_drain_connection_lost` in the catalogue, `connection_lost` in the registry). `drainManagedSync` takes exactly one extra pass (`drain.extra_pass { from, to }`, counts merged by `mergeExtraPass`) when HEAD moved past the pinned target during a `synced` run, so a live checkout ends at HEAD without looping. Tests: `test/sync-drain-connection.test.ts`. In-pass governor: `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted with `DrainPassAbandoned` (the pass's `assertActive` / `stampDrainStep` boundaries throw it, so it admits and writes nothing more; `stampDrainStep` does not throw the caller's own cancel, which still banks admitted work) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_progress` / `owner_missing` (#6712 PR 2 retired `no_admission`); a live preparation is left to its own budget and ceiling. The pass returns at the checkpoint commit (`managed_sync.finish` counts as a commit); its tail runs after the lease is released (`sync-tail.ts`). `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts` reports a delegated stop as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-drain-finish-tail.test.ts`, `test/sync-waivers-chunk.test.ts`.
- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). #6510: `trackedBytes` checks for symlinks with `lstat` on every directory component between the canonical root and the leaf, then the leaf, on every read (no cache across files: a parent swapped to a symlink after the first file would otherwise let a later leaf read outside the root), reading through the Git spelling; the former `realpath(path) === path` proxy refused a checkout whose volume spells a name differently (APFS NFC/NFD, case-insensitive volumes) with no symlink anywhere. Tests: `test/persistence-manifest-git-scope.test.ts`, `test/worktree-manifest-unicode.test.ts` (synthetic realpath-spelling spy on Linux, parent-swap, case-spelling where the tmpdir is case-insensitive), `test/hardened-git-filters.test.ts`.
- `src/core/git-checkout.ts` — #6210 (fix wave 12): `classifyGitCheckout(dir, env = process.env): 'git' | 'not_git' | 'unknown'` decides from the filesystem alone whether a directory is inside a Git checkout: `not_git` only when the directory exists and no `.git` entry (directory or gitdir file) is at or above it and `GIT_DIR` is unset; `unknown` for a missing directory or any lookup error other than absence. Git's own exit 128 is locale-dependent and also means a damaged HEAD, a bad gitdir or dubious ownership, so callers that soften "not a checkout" use this instead. `isDurabilityHardenedAsync` (`brain-repo-durability.ts`) returns false only for `not_git` or an absent hook; every other failure (a git probe run with `LC_ALL=C` failing, a timeout, an unreadable hook) rejects `git_unavailable`, and `runPersistenceEffects` (`persistence/effects.ts`) settles each cached per-root probe to `{durable}|{error}` and records the error on every coalesced effect, so the effects stay queued (and park after repeated failures) instead of completing as `durability_not_enabled`. Tests: `test/git-checkout.test.ts`, `test/persistence-git-durability-probe-6210.slow.test.ts` (Postgres via `test/e2e/persistence-git-durability-probe-6210-postgres.test.ts`; fix wave 16 split it out of the 5530 coalescing file, whose fixture both share through `test/helpers/git-coalescing-fixture.ts`).
diff --git a/docs/guides/resolve-paths.md b/docs/guides/resolve-paths.md
index e056f65dee..f853578649 100644
--- a/docs/guides/resolve-paths.md
+++ b/docs/guides/resolve-paths.md
@@ -25,7 +25,7 @@ are relative to the source root, or to the Git top level when they start with th
and bounded lookups on existing indexes; nothing is scheduled or written.
Each path returns the `slug` sync gives it, `in_synced_commit` / `at_head`, `skipped` (with `typed_frontmatter` for a metafile),
-`hold`, `page` (id, chunks, unembedded), `slug_owner` (a live page that owns the slug with another origin), `frontmatter_slug`
+`hold`, `page` (id, chunks, unembedded), `embedding_hold` (a large page's held or capped embedding budget), `slug_owner` (a live page that owns the slug with another origin), `frontmatter_slug`
(a `slug:` line that differs from the path slug: sync holds that file), `searchable` (`true`, `"keyword"` or `false`), a `why`
sentence and a `fix` (an existing command, never run here; null when nothing is owed).
@@ -34,7 +34,7 @@ sentence and a `fix` (an existing command, never run here; null when nothing is
| state | meaning | fix |
|---|---|---|
| `searchable` | live page, every chunk has a vector | none |
-| `pending_embedding` | found by keyword; some chunks still wait for a vector | `gbrain embed --stale --catch-up` (paid, asks first); none on a brain keyless by choice |
+| `pending_embedding` | found by keyword; some chunks still wait for a vector (with `embedding_hold` set: a large page's budget waits for approval) | `gbrain embed --stale --catch-up` (paid, asks first), or `gbrain embed --held --dry-run --source <id>` for a held page; none on a brain keyless by choice |
| `chunkless` | page with body text and no chunk rows | `gbrain embed --stale --catch-up` |
| `keyword_only` | an `embed_skip` page: keyword search only, by design | see `gbrain pages unsearchable` |
| `quarantined` | hidden from search by the import gate | doctor `quarantined_pages` |
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index 72cf30fe87..659960bbf3 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -165,7 +165,7 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis
if (notifierBlock) console.log(` ${formatNotifierBlock(sourceId, notifierBlock)}`);
console.log(` holds: ${status.holds.length}${status.holds.length ? ` (${status.holds.filter(h => h.needs_human).length} need a person)` : ''}; last error: ${status.last_error ? `${status.last_error.code} [${status.last_error.class}]` : 'none'}`);
for (const hold of status.holds) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);
- if (status.last_error) console.log(` ${status.last_error.path ?? ''}: ${status.last_error.code} safe: ${status.last_error.safe_actions.join(',')}${status.last_error.needs_human ? ` NEEDS HUMAN: ${status.last_error.human_reason}` : ''}`);
+ if (status.last_error) console.log(` ${status.last_error.path ?? ''}: ${status.last_error.code}${status.last_error.superseded ? ` (superseded: the sync committed a page at ${status.last_error.superseded.at}, after this error)` : ` safe: ${status.last_error.safe_actions.join(',')}${status.last_error.needs_human ? ` NEEDS HUMAN: ${status.last_error.human_reason}` : ''}`}`);
const ob = status.oldest_blocker;
console.log(` oldest unfinished request: ${ob.status === 'unknown' ? `unknown (${ob.reason})` : ob.request ? `${ob.request.request_id} (${ob.request.state}${ob.request.step ? `, step ${ob.request.step}` : ''}${ob.request.blocked_by ? `, blocked by ${ob.request.blocked_by.predicate}` : ''})` : 'none'}`
+ `; recovery records: ${status.recovery.status === 'unknown' ? `unknown (${status.recovery.reason})` : status.recovery.count}`);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 2e5ae0769e..7b28037cc3 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1026,6 +1026,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// GBRA-150 (synced-but-not-searchable landing checks). `since` is restamped at the merge slot.
{ since: 'TBD', id: 'sync_status_blocked_means_source_stopped', text: '`gbrain sync status` now reads `blocked` only when the source cannot advance without a person or an operator, the meaning a sync run\'s drain outcome and a sync job\'s `blocked` progress already had. A file hold that waits on a person while the rest of the source keeps syncing now reads `synced` with the new reason `held_needs_human` (it read `blocked` before); `needs_human`, `next` and the hold rows are unchanged, so a client acting on `needs_human` sees no difference.' },
{ since: 'TBD', id: 'sources_resolve_path', text: 'New read-only `gbrain sources resolve-path <id> <path...> [--stdin] [--json]` (MCP `sources_resolve_path`, read scope, at most 200 paths) says what gbrain did with each file path of a source by its own rules: the slug sync gives it, whether it is skipped, held, not synced yet, deleted, or a live page, and whether search can find it (`searchable` true, `keyword` or false), with a `why` and a `fix`. Landing checks should call it instead of copying gbrain\'s path-to-slug rules. `gbrain sync status --detail` adds a `landing` block, and the new cheap doctor check `sync_landing_gaps` warns when pages a managed sync committed more than the freshness target ago still cannot be fully searched.' },
+ { since: 'TBD', id: 'sync_status_coherent_7189', text: '`gbrain sync status --json` no longer contradicts itself while a source falls behind (#7189). `freshness` adds `behind` (commits on the checkout HEAD after the last synced commit, and the oldest one\'s age), because its latency samples date only commits that already synced. The `notifier` block adds `drain_holder`: with no notifier running, the process holding the source\'s drain lease is named and no fix is offered while it makes progress, instead of "No resident … watches this source". A `last_error` the source\'s sync has committed a page past now carries `superseded: { at }` and no longer sets `needs_human`, `state` or `next`. New `needs_human_from` says whether `needs_human` comes from a hold or the last error. In `gbrain sources resolve-path`, a large page whose embedding budget is held or capped reads `pending_embedding` with `embedding_hold`, never `keyword_only`, which means `embed_skip`.' },
// GBRA-150 (nested typed metafiles become pages): maintainer-approved default (2026-10-20). `since` is stamped at the merge slot.
{ since: 'TBD', text: 'Sync now imports a folder-scaffolding file below a source\'s root (`index.md`, `README.md`, `log.md`, `schema.md` or `RESOLVER.md`) as a page when its frontmatter has `type:` or `title:`, for example `projects/acme-example/index.md`. A bare one at any depth and every one at the source root stay skipped. The first sync after the upgrade imports the existing typed files once and deletes or rewrites nothing else; deleting such a file later soft-deletes its page. `gbrain config set sync.metafile_pages off` restores the old skip.' },
];
diff --git a/src/core/notifier/status.ts b/src/core/notifier/status.ts
index 22416829e3..46db6ec5a5 100644
--- a/src/core/notifier/status.ts
+++ b/src/core/notifier/status.ts
@@ -14,6 +14,7 @@ import { missingTable, type DetectionMode, type NotifierState } from './store.ts
import { residentNotifier } from './resident.ts';
import { parseOnCommit } from '../commit-notifier.ts';
import { SYNC_ON_COMMIT_KEY } from '../sync-config-keys.ts';
+import { HOLDER_STALL_MS, holderStalled, publicDrainHolder, readDrainHolder, type DrainHolder } from '../persistence/sync-lease.ts';
type Exec = Pick<BrainEngine, 'executeRaw' | 'kind'>;
type FreshnessExec = Exec & Pick<BrainEngine, 'getConfig'>;
@@ -43,7 +44,12 @@ export interface NotifierBlock {
observed_at: string | null;
pending_markers: Array<{ intent: string; wanted_head: string | null; first_due_at: string; requested_by: string }>;
stalled: boolean;
- /** Set when nothing will sync the source on its own or the notifier stalled. */
+ /**
+ * #7189: with no live notifier owner, the process holding the source's drain lease (a serve pass, a sync job, a CLI
+ * sync), which is syncing it now; null when none holds it. Remote callers get no host, pid or job id.
+ */
+ drain_holder: DrainHolder | null;
+ /** Set when nothing will sync the source on its own, the lease holder made no progress, or the notifier stalled. */
fix: Action | null;
}
@@ -125,7 +131,7 @@ const syncNowFix = (sourceId: string, why: string): Action => ({ argv: ['gbrain'
* its state, the retry schedule, the last error and, for a local caller, the trace file. Remote callers get no trace
* path, pid or host id (the sync_status projection rule).
*/
-export async function readNotifierBlock(engine: Exec, sourceId: string, opts: { remote?: boolean } = {}): Promise<NotifierBlock | null> {
+export async function readNotifierBlock(engine: BrainEngine, sourceId: string, opts: { remote?: boolean } = {}): Promise<NotifierBlock | null> {
let row: Row | undefined;
let markers: Array<{ intent: string; wanted_head: string | null; first_due_at: unknown; requested_by: string }> = [];
try {
@@ -137,8 +143,11 @@ export async function readNotifierBlock(engine: Exec, sourceId: string, opts: {
const live = ownerLive(engine, row);
const stalled = row.reason === 'notifier_stalled' || row.state === 'operator_blocked';
const resident = live ? { kind: row.owner_kind ?? 'unknown', pid: remote ? null : row.owner_pid === null ? null : Number(row.owner_pid), host_id: remote ? null : row.owner_host_id, live } : null;
- const fix = !live
+ const holder = live ? null : await readDrainHolder(engine, sourceId).catch(() => null);
+ const fix = !live && !holder
? syncNowFix(sourceId, 'No resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches this source; this syncs the checkout HEAD now. A resident started later catches up on its own.')
+ : !live ? (holderStalled(holder) ? syncNowFix(sourceId, `No notifier watches this source, and the ${holder!.kind} process holding its drain lease has made no commit or cursor save for ${HOLDER_STALL_MS / 60_000} min or more; `
+ + 'a foreground sync follows it and takes over when its lease lapses.') : null)
: stalled ? syncNowFix(sourceId, `The notifier made no progress after ${Number(row.attempts ?? 0)} attempts (${row.last_error_code ?? row.reason ?? 'blocked'}); a foreground sync shows the error`
+ `${!remote && row.trace_path ? `, and the trace is ${row.trace_path}` : ''}.`) : null;
return {
@@ -147,13 +156,14 @@ export async function readNotifierBlock(engine: Exec, sourceId: string, opts: {
last_error: row.last_error_code || row.last_error ? { code: row.last_error_code, message: row.last_error, at: iso(row.last_error_at), ...(remote ? {} : { trace_path: row.trace_path }) } : null,
observed_head: row.observed_head, observed_at: iso(row.observed_at),
pending_markers: markers.map(m => ({ intent: m.intent, wanted_head: m.wanted_head, first_due_at: iso(m.first_due_at)!, requested_by: m.requested_by })),
- stalled, fix,
+ stalled, drain_holder: remote ? publicDrainHolder(holder) : holder, fix,
};
}
/** One line for the human sync status and doctor. */
export function formatNotifierBlock(sourceId: string, b: NotifierBlock): string {
- const who = b.resident ? `${b.resident.kind}${b.resident.pid ? ` (PID ${b.resident.pid})` : ''}, ${b.detection_mode ?? 'not observed yet'}` : 'none running';
+ const who = b.resident ? `${b.resident.kind}${b.resident.pid ? ` (PID ${b.resident.pid})` : ''}, ${b.detection_mode ?? 'not observed yet'}`
+ : b.drain_holder ? `none running; ${b.drain_holder.kind}${b.drain_holder.pid ? ` (PID ${b.drain_holder.pid})` : ''} holds the drain lease and is syncing it` : 'none running';
const state = b.state ? `${b.state}${b.reason ? ` (${b.reason})` : ''}${b.next_retry_at && b.state === 'retry' ? `, next retry ${b.next_retry_at}` : ''}${b.attempts ? `, ${b.attempts} attempt(s)` : ''}` : 'idle';
const markers = b.pending_markers.length ? `; wanted: ${b.pending_markers.map(m => `${m.intent}${m.wanted_head ? ` ${m.wanted_head.slice(0, 8)}` : ''}`).join(', ')}` : '';
const fix = b.fix ? `. Fix: ${b.fix.argv?.join(' ')}` : '';
diff --git a/src/core/persistence/resolve-paths.ts b/src/core/persistence/resolve-paths.ts
index 216e199493..3af8cd2a79 100644
--- a/src/core/persistence/resolve-paths.ts
+++ b/src/core/persistence/resolve-paths.ts
@@ -36,6 +36,10 @@ import { loadSyncEligibility, syncGit } from './sync-discovery.ts';
import { readBlobContents } from './sync-blobs.ts';
import { readGitHold } from './sync-holds.ts';
import { persistenceEnabledForHealth } from './ownership.ts';
+import { budgetRowAppliesFilter } from '../page-size-policy.ts';
+import { chunkGenerationFilter } from '../search/safe-chunks.ts';
+import { quoteIdentifier } from '../search/embedding-column.ts';
+import { embeddingWriteTarget } from '../page-state/projections.ts';
/** Paths one call resolves. */
export const RESOLVE_PATHS_MAX = 200;
@@ -57,6 +61,11 @@ export interface ResolvedPath {
skipped: { reason: SyncableReason; typed_frontmatter?: boolean } | null;
hold: { code: string; message: string } | null;
page: { id: number; slug: string; deleted: boolean; chunks: number; unembedded: number } | null;
+ /**
+ * The page's embedding budget hold (a large page held for approval or stopped at its cap, never an `embed_skip`), or
+ * null. A held page reads `pending_embedding` with `unembedded` its chunks with no vector: it waits for approval.
+ */
+ embedding_hold: { state: 'held' | 'capped'; reason: string; updated_at: string } | null;
/** A live page that owns this slug with another origin (a case-folded or hyphen-folded twin), or null. */
slug_owner: { slug: string; source_path: string | null } | null;
/** A frontmatter `slug:` that differs from the path slug (sync holds such a file as SLUG_MISMATCH). */
@@ -149,6 +158,19 @@ export async function resolveSourcePaths(engine: BrainEngine, sourceId: string,
const state = prior && PAGE_STATE_ORDER.indexOf(prior.state) < PAGE_STATE_ORDER.indexOf(row.state) ? prior.state : row.state;
embedding.set(row.slug, { state, chunks, unembedded });
}
+ const keywordOnly = [...embedding].filter(([, emb]) => emb.state === 'keyword_only').map(([slug]) => slug);
+ const budgetHolds = new Map<string, NonNullable<ResolvedPath['embedding_hold']> & { unembedded: number }>();
+ if (keywordOnly.length) {
+ const column = `cc.${quoteIdentifier((await embeddingWriteTarget(engine)).column.name)}`;
+ for (const row of await engine.executeRaw<{ slug: string; state: 'held' | 'capped'; reason: string; updated_at: Date | string; unembedded: number | string }>(
+ `SELECT p.slug, b.state, COALESCE(b.reason, 'awaiting_approval') AS reason, b.updated_at,
+ (SELECT count(*) FROM content_chunks cc WHERE cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc')} AND ${column} IS NULL) AS unembedded
+ FROM pages p JOIN page_embedding_budget b ON b.page_id = p.id
+ WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) AND p.deleted_at IS NULL AND ${budgetRowAppliesFilter('b', 'p')}
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`, [sourceId, keywordOnly])) {
+ budgetHolds.set(row.slug, { state: row.state, reason: row.reason, updated_at: new Date(row.updated_at).toISOString(), unembedded: Number(row.unembedded) });
+ }
+ }
const sync = ['gbrain', 'sync', '--source', sourceId, '--no-pull'];
const syncStatus = ['gbrain', 'sync', 'status', '--source', sourceId, '--json'];
const verify = (path: string) => ['gbrain', 'sources', 'resolve-path', sourceId, path, '--json'];
@@ -169,7 +191,7 @@ export async function resolveSourcePaths(engine: BrainEngine, sourceId: string,
const emb = live ? embedding.get(live.slug) : undefined;
const base = { path: p.input, source_path: p.origin, slug, in_synced_commit: !!committed, at_head: atHead ? !!current : null, slug_owner: slugOwner, frontmatter_slug: declared,
page: page ? { id: Number(page.id), slug: page.slug, deleted: page.deleted, chunks: emb?.chunks ?? 0, unembedded: emb?.unembedded ?? 0 } : null,
- skipped: null as ResolvedPath['skipped'], hold: null as ResolvedPath['hold'] };
+ skipped: null as ResolvedPath['skipped'], hold: null as ResolvedPath['hold'], embedding_hold: null as ResolvedPath['embedding_hold'] };
const push = (state: ResolvePathState, searchable: ResolvedPath['searchable'], why: string, fix: Action | null, extra: Partial<ResolvedPath> = {}) =>
out.push({ ...base, state, searchable, why, fix, ...extra });
const liveSearch: ResolvedPath['searchable'] = emb ? SEARCHABLE[emb.state] : false;
@@ -205,6 +227,14 @@ export async function resolveSourcePaths(engine: BrainEngine, sourceId: string,
then: readFix('Imports the scheduled files.', sync, verify(p.input)) });
continue;
}
+ const budget = budgetHolds.get(live.slug);
+ if (budget) {
+ const { unembedded, ...embeddingHold } = budget;
+ push('pending_embedding', 'keyword', `Page ${live.slug} is searchable by keyword; its embedding budget is ${budget.state} (${budget.reason}), so ${unembedded} chunk(s) wait for a vector until the hold is approved.`,
+ readFix('Lists the held and capped large pages with the cost to finish and the approve command; read-only.', ['gbrain', 'embed', '--held', '--dry-run', '--source', sourceId], verify(p.input)),
+ { embedding_hold: embeddingHold, page: { ...base.page!, unembedded } });
+ continue;
+ }
const state = emb ? PAGE_STATE[emb.state as Exclude<EmbeddingState, 'deleted_page_chunks'>] ?? 'searchable' : 'chunkless';
const fix = emb && emb.state !== 'embedded' ? embeddingStateFix(emb.state, { sourceId, slug: live.slug, embeddingsEnabled: !disabled, verify: { argv: verify(p.input) } }) : null;
push(state, liveSearch, state === 'searchable' ? `Page ${live.slug} is live and every chunk has a vector.`
diff --git a/src/core/persistence/sync-freshness.ts b/src/core/persistence/sync-freshness.ts
index 8e01024412..60f6532ca9 100644
--- a/src/core/persistence/sync-freshness.ts
+++ b/src/core/persistence/sync-freshness.ts
@@ -40,8 +40,17 @@ export interface SourceFreshness {
commits: number;
/** Targets in the window git could not date here (no checkout on this host, or the commit is not in it); their pages are not sampled. */
unresolved_commits: number;
+ /**
+ * #7189: the current lag, which the latency samples above cannot show (they date only commits that already synced):
+ * commits on this host's checkout HEAD after the source's last synced commit, and the committer age of the oldest
+ * of them. Null when this host has no checkout, the source has not synced yet, or git could not answer.
+ */
+ behind: { commits: number; oldest_seconds: number | null } | null;
}
+/** The commits after `from` up to HEAD of the checkout at `root`, oldest committer time first (unix seconds), or null when git cannot say. */
+export type BehindReader = (root: string, from: string) => Promise<{ commits: number; oldest: number | null } | null>;
+
/** Commit time (unix seconds) of each sha that the checkout at `root` can resolve. */
export type CommitTimeReader = (root: string, shas: string[]) => Promise<Map<string, number>>;
@@ -68,23 +77,38 @@ export const readGitCommitTimes: CommitTimeReader = async (root, shas) => {
return out;
};
+export const readGitBehind: BehindReader = async (root, from) => {
+ if (!SHA.test(from)) return null;
+ const run = (args: string[]) => execFileBounded('git', ['-C', root, ...args], { timeout: 10_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });
+ const count = await run(['rev-list', '--count', `${from}..HEAD`]);
+ const commits = Number(count.stdout.trim());
+ if (count.error || !Number.isInteger(commits)) return null;
+ if (!commits) return { commits: 0, oldest: null };
+ const oldest = await run(['log', '--reverse', '--format=%ct', `${from}..HEAD`]);
+ const at = Number(oldest.stdout.slice(0, oldest.stdout.indexOf('\n') >>> 0).trim());
+ return { commits, oldest: !oldest.error && Number.isFinite(at) && at > 0 ? at : null };
+};
+
const num = (value: unknown): number | null => value === null || value === undefined || !Number.isFinite(Number(value)) ? null : Math.round(Number(value) * 10) / 10;
-interface BindingRow { source_id: string; worktree_id: string; source_incarnation: string; root: string | null }
+interface BindingRow { source_id: string; worktree_id: string; source_incarnation: string; root: string | null; last_commit: string | null }
interface AggregateRow { samples: number | string; s50: unknown; s95: unknown; embedded: number | string; e50: unknown; e95: unknown; pending: number | string }
/** The freshness of every bound managed source (or of `sourceIds`); a source without a binding is omitted. */
-export async function readSyncFreshness(engine: BrainEngine, opts: { sourceIds?: string[]; commitTimes?: CommitTimeReader } = {}): Promise<SourceFreshness[]> {
+export async function readSyncFreshness(engine: BrainEngine, opts: { sourceIds?: string[]; commitTimes?: CommitTimeReader; behind?: BehindReader } = {}): Promise<SourceFreshness[]> {
const { existingLocalHostId } = await import('./identity.ts');
- const bindings = await engine.executeRaw<BindingRow>(`SELECT b.source_id, b.worktree_id::text AS worktree_id, b.source_incarnation::text AS source_incarnation, COALESCE(h.local_path, s.local_path) AS root
+ const bindings = await engine.executeRaw<BindingRow>(`SELECT b.source_id, b.worktree_id::text AS worktree_id, b.source_incarnation::text AS source_incarnation, COALESCE(h.local_path, s.local_path) AS root, s.last_commit
FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation
LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id::text=$2
WHERE ($1::text[] IS NULL OR b.source_id=ANY($1::text[])) ORDER BY b.source_id`, [opts.sourceIds ?? null, existingLocalHostId()]);
const commitTimes = opts.commitTimes ?? readGitCommitTimes;
+ const behindOf = opts.behind ?? readGitBehind;
const out: SourceFreshness[] = [];
for (const b of bindings) {
+ const lag = b.root && b.last_commit ? await behindOf(b.root, b.last_commit).catch(() => null) : null;
+ const behind = lag && { commits: lag.commits, oldest_seconds: lag.oldest === null ? null : Math.max(0, Math.round(Date.now() / 1000 - lag.oldest)) };
const empty: SourceFreshness = { source_id: b.source_id, window_hours: FRESHNESS_WINDOW_HOURS, commit_to_searchable: { samples: 0, p50_seconds: null, p95_seconds: null },
- commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0 };
+ commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0, behind };
const targets = (await engine.executeRaw<{ target: string }>(`SELECT r.intent->>'target' AS target FROM persistence_requests r WHERE ${SAMPLE_WHERE}
GROUP BY 1 ORDER BY max(r.completed_at) DESC LIMIT ${FRESHNESS_MAX_TARGETS}`, [b.worktree_id, b.source_incarnation, FRESHNESS_WINDOW_HOURS]))
.map(row => row.target).filter(target => typeof target === 'string' && SHA.test(target));
@@ -129,10 +153,11 @@ export function formatLatency(value: number | null): string {
/** One human line per source: `commit→searchable p50 8s, p95 14s (12 page(s), last 24 h); commit→embedded ...`. */
export function formatSyncFreshness(f: SourceFreshness): string {
+ const behind = f.behind?.commits ? `; ${f.behind.commits} commit(s) not synced yet${f.behind.oldest_seconds !== null ? `, oldest ${formatLatency(f.behind.oldest_seconds)} old` : ''}` : '';
if (!f.commit_to_searchable.samples) {
- return `no commit→searchable samples in the last ${f.window_hours} h${f.unresolved_commits ? `, ${f.unresolved_commits} commit(s) not datable from this host's checkout` : ''}`;
+ return `no commit→searchable samples in the last ${f.window_hours} h${f.unresolved_commits ? `, ${f.unresolved_commits} commit(s) not datable from this host's checkout` : ''}${behind}`;
}
const s = f.commit_to_searchable, e = f.commit_to_embedded;
return `commit→searchable p50 ${formatLatency(s.p50_seconds)}, p95 ${formatLatency(s.p95_seconds)} (${s.samples} page(s), last ${f.window_hours} h); `
- + `commit→embedded ${e.samples ? `p50 ${formatLatency(e.p50_seconds)}, p95 ${formatLatency(e.p95_seconds)}` : 'no samples'} (${e.samples} page(s), ${e.pending} pending)`;
+ + `commit→embedded ${e.samples ? `p50 ${formatLatency(e.p50_seconds)}, p95 ${formatLatency(e.p95_seconds)}` : 'no samples'} (${e.samples} page(s), ${e.pending} pending)${behind}`;
}
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 9b5e3f16c5..26dbb9d00f 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -84,6 +84,11 @@ export interface SyncStatusError extends SyncFaultVerdict {
repeats?: number;
/** #6643: what caused this failure (a knock-on's root request, or the receipt blocking a checkpoint). */
root_cause?: ManagedSyncFailure['root_cause'];
+ /**
+ * #7189: this source's sync committed a page write at `at`, after the failure was last recorded, so the failure no
+ * longer says where the sync stands. It stays listed, but sets neither `needs_human`, `state` nor `next`.
+ */
+ superseded?: { at: string };
}
export interface SyncStatus {
@@ -107,6 +112,8 @@ export interface SyncStatus {
/** Whether anything (a hold or the last error) waits on a person; the first such reason. */
needs_human: boolean;
human_reason?: string;
+ /** #7189: what `needs_human` comes from: a hold (named, so a `last_error.needs_human: false` beside it is not a contradiction) or the last error. */
+ needs_human_from: { kind: 'hold'; path: string; slug: string | null; code: string } | { kind: 'last_error'; code: string } | null;
/** The resume arguments after `gbrain sync` for this source's cursor (its stored options when one exists). */
resume_argv: string[];
/**
@@ -308,6 +315,14 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message, repeated: failure.repeats ? { path: failure.path, runs: failure.repeats } : null }) }
: retired ? { code: 'cursor_incarnation_retired', category: 'sync_fault', public_category: 'superseded', message: `An unfinished sync cursor of ${sourceId} was recorded under an incarnation the source no longer has; no current sync selects it, and it says nothing about whether the current files are imported. `
+ `Retire it with ${repairPreview.argv!.join(' ')} (preview, then --apply with the printed hash).`, phase: 'resume', first_seen: retired.first_seen, attempts: 1, ...classifySyncFault({ code: 'cursor_incarnation_retired' }) } : null;
+ if (failure && lastError) {
+ const [seen] = await engine.executeRaw<{ failure_at: Date | string | null; committed_at: Date | string | null }>(`SELECT
+ (SELECT f.updated_at FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=$2) AS failure_at,
+ (SELECT max(r.completed_at) FROM persistence_source_bindings b JOIN persistence_requests r ON r.worktree_id=b.worktree_id AND r.source_incarnation=b.source_incarnation
+ WHERE b.source_id=$1 AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS committed_at`, [sourceId, failure.cursor_key]);
+ if (seen?.failure_at && seen.committed_at && new Date(seen.committed_at) > new Date(seen.failure_at)) lastError.superseded = { at: new Date(seen.committed_at).toISOString() };
+ }
+ const liveError = lastError?.superseded ? null : lastError;
const unfinished = !!header && !header.done;
const remaining = header ? Math.max(0, Number(header.total) - Number(header.index)) : null;
const p = header?.progress;
@@ -317,9 +332,9 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
const withheld = passRow ? source.withheld : null;
const passState = passRow ? passStatusState(passRow, withheld, source.writeback_failed) : null;
const resume = !header && passRow ? passResumeArgs(sourceId, passRow) : managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });
- const human = holds.find(hold => hold.needs_human) ?? (lastError?.needs_human ? lastError : undefined);
+ const human = holds.find(hold => hold.needs_human) ?? (liveError?.needs_human ? liveError : undefined);
// #6643: a knock-on or a superseded run is not a failure of its page: the resume re-freezes the entry.
- const selfHealing = lastError?.detail === 'knock_on' || lastError?.detail === 'run_replaced';
+ const selfHealing = liveError?.detail === 'knock_on' || liveError?.detail === 'run_replaced';
const actionable = holds.filter(hold => !hold.needs_human && hold.safe_actions[0] !== 'none');
const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };
// #6706: a live sync job already drains this cursor; the agent watches it instead of starting a second drainer beside it.
@@ -336,10 +351,10 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
+ `${repairable ? `, repairs the ${repairable} content hold(s) the content-repair lane clears (hash-bound repairs under the fences.repair caps, one receipt per file, then the re-screen)` : ''}`
+ ' and names the sync to run; it refuses the rest by name and drops nothing.' }
: retired ? { ...repairPreview, verify }
- : unfinished || lastError
+ : unfinished || liveError
? { 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.`
+ why: liveError && selfHealing ? `The last run stopped on a page that only waited on another page of the same sync (${liveError.detail}); the same sync re-freezes it under a fresh request${liveError.root_cause?.request_id ? `, and request ${liveError.root_cause.request_id} is what it waited on` : ''}.`
+ : liveError ? `The last run recorded ${liveError.code} (${liveError.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)]);
@@ -351,13 +366,14 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
: { status: 'unknown' as const, reason: 'not_read: run sync status with --detail', recovery_next: recovery.status === 'ok' && recovery.first ? recoveryAction(sourceId, recovery.first) : undefined };
const connectorLastError = await (await import('./connector-status.ts')).readConnectorLastError(engine, sourceId);
const gitPushHolds = committed?.git_push_held ? await readGitPushHolds(engine, [sourceId]) : [];
- const [state, stateReason] = statusState({ human: !!(lastError?.needs_human), heldForHuman: holds.some(hold => hold.needs_human), oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0, pass: passState });
+ const [state, stateReason] = statusState({ human: !!(liveError?.needs_human), heldForHuman: holds.some(hold => hold.needs_human), oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!liveError, actionable: actionable.length > 0, holds: holds.length > 0, pass: passState });
const admission = await syncAdmissionStatus(engine, sourceId, source.incarnation,
{ stored: source.admission_stored, row_value: source.admission_row_value, set_at: source.admission_set_at });
const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume, source.writeback_failed) : null;
return { source_id: sourceId, run_id: header?.runId ?? null,
cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,
committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
+ needs_human_from: !human ? null : 'path' in human && 'held_since' in human ? { kind: 'hold', path: human.path, slug: human.slug, code: human.code } : { kind: 'last_error', code: human.code },
resume_argv: resume, ...blockers, cursors: detail ? await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures) : [],
terminal_failures: terminal, connector_last_error: connectorLastError, git_push_holds: gitPushHolds, next: next ?? recovery_next ?? passNext ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,
why: `Write request ${oldest.request.request_id} of this source is still ${oldest.request.state}${oldest.request.step ? ` (step ${oldest.request.step})` : ''}; a running owner finishes it on its own, and the next sync of this source drains it.` } satisfies Action
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 018765dc95..7dfbfc3b32 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -2209,6 +2209,7 @@
"on_commit": false,
"sources": [
{
+ "behind": null,
"commit_to_embedded": {
"p50_seconds": null,
"p95_seconds": null,
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 7c4af26b28..e5a8516a06 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -2265,6 +2265,7 @@
"on_commit": false,
"sources": [
{
+ "behind": null,
"commit_to_embedded": {
"p50_seconds": null,
"p95_seconds": null,
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 04c0b8eae7..2ef45f189d 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -2269,6 +2269,7 @@
"on_commit": false,
"sources": [
{
+ "behind": null,
"commit_to_embedded": {
"p50_seconds": null,
"p95_seconds": null,
diff --git a/test/sources-resolve-path.test.ts b/test/sources-resolve-path.test.ts
index 72ceb48a40..334b224006 100644
--- a/test/sources-resolve-path.test.ts
+++ b/test/sources-resolve-path.test.ts
@@ -155,3 +155,20 @@ test('the operation is read-scoped, takes paths relative to the source root, and
await expect(s.resolve()).rejects.toMatchObject({ code: 'invalid_params' });
await expect(s.resolve(...Array.from({ length: RESOLVE_PATHS_MAX + 1 }, (_, i) => `notes/${i}.md`))).rejects.toMatchObject({ code: 'invalid_params' });
}), 240_000);
+
+test('a large page whose embedding budget is held reads pending_embedding with the hold, never keyword_only (which means embed_skip)', () => each(async engine => {
+ const { PAGE_INLINE_MAX_BYTES } = await import('../src/core/page-size-policy.ts');
+ const body = 'Weekly notes from acme-example with alice-example. '.repeat(Math.ceil((PAGE_INLINE_MAX_BYTES + 4096) / 51));
+ const s = await source(engine, { 'notes/large-example.md': `---\ntitle: Large\n---\n${body}\n`, 'notes/skip-example.md': '---\ntitle: Skip\nembed_skip:\n reason: operator\n---\nSkipped by choice.\n' });
+ await s.sync();
+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [s.id, 'notes/large-example']);
+ await engine.executeRaw(`INSERT INTO page_embedding_budget (page_id, state, reason) VALUES ($1, 'held', 'upgrade_backfill')
+ ON CONFLICT (page_id) DO UPDATE SET state='held', reason='upgrade_backfill'`, [page!.id]);
+ const { paths: [held, skipped] } = await s.resolve('notes/large-example.md', 'notes/skip-example.md');
+ expect(held).toMatchObject({ state: 'pending_embedding', searchable: 'keyword', embedding_hold: { state: 'held', reason: 'upgrade_backfill' } });
+ expect(held!.page!.unembedded).toBe(held!.page!.chunks);
+ expect(held!.page!.chunks).toBeGreaterThan(0);
+ expect(held!.fix!.argv).toEqual(['gbrain', 'embed', '--held', '--dry-run', '--source', s.id]);
+ expect(skipped).toMatchObject({ state: 'keyword_only', searchable: 'keyword', embedding_hold: null });
+}), 240_000);
+
diff --git a/test/sync-freshness-6858.test.ts b/test/sync-freshness-6858.test.ts
index ab4f3336ef..3ff4b6235c 100644
--- a/test/sync-freshness-6858.test.ts
+++ b/test/sync-freshness-6858.test.ts
@@ -99,7 +99,7 @@ describe('sync freshness (#6858 ask 6)', () => {
const f = await managedSource(engine, 60);
const [fresh] = await readSyncFreshness(engine, { sourceIds: [f.id] });
expect(fresh).toEqual({ source_id: f.id, window_hours: 24, commit_to_searchable: { samples: 0, p50_seconds: null, p95_seconds: null },
- commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0 });
+ commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0, behind: null });
expect(formatSyncFreshness(fresh!)).toBe('no commit→searchable samples in the last 24 h');
await engine.setConfig('sync.on_commit', 'true');
expect(await doctor(engine)).toMatchObject({ name: 'managed_sync_latency', status: 'ok', message: expect.stringContaining('No commit→searchable samples') });
@@ -124,7 +124,7 @@ describe('sync freshness (#6858 ask 6)', () => {
// searchable: [10, 20, 30, 400] -> p50 25, p95 30 + 0.85 * 370; embedded: [18, 22] (the page waiting on a chunk is pending).
expect(fresh, name).toEqual({ source_id: f.id, window_hours: 24, commits: 1, unresolved_commits: 0,
commit_to_searchable: { samples: 4, p50_seconds: 25, p95_seconds: 344.5 },
- commit_to_embedded: { samples: 2, p50_seconds: 20, p95_seconds: 21.8, pending: 1 } });
+ commit_to_embedded: { samples: 2, p50_seconds: 20, p95_seconds: 21.8, pending: 1 }, behind: null });
expect(formatSyncFreshness(fresh!)).toBe('commit→searchable p50 25s, p95 5.7m (4 page(s), last 24 h); commit→embedded p50 20s, p95 21.8s (2 page(s), 1 pending)');
}
}), 120_000);
diff --git a/test/sync-status-blocked-definition.test.ts b/test/sync-status-blocked-definition.test.ts
index da77e15b63..ed57d178cb 100644
--- a/test/sync-status-blocked-definition.test.ts
+++ b/test/sync-status-blocked-definition.test.ts
@@ -55,6 +55,7 @@ test('a file hold that waits on a person reads synced/held_needs_human, like the
expect(status.holds.map(hold => [hold.path, hold.needs_human])).toEqual([['d.md', true]]);
expect([status.state, status.reason]).toEqual(['synced', 'held_needs_human']);
expect(status.needs_human).toBe(true);
+ expect(status.needs_human_from).toEqual({ kind: 'hold', path: 'd.md', slug: 'd', code: 'file_drift' });
expect(status.next).toMatchObject({ argv: ['gbrain', 'repair', 'file-drift', '--source', id, '--slug', 'd', '--prefer', 'database'] });
expect(status.next!.user_message).toContain('page d');
expect(syncStatusHeadline(status)).toBe(`Source ${id} is synced except 1 held file(s), some waiting on a person (see NEEDS HUMAN below); the rest keeps syncing.`);
diff --git a/test/sync-status-coherence-7189.test.ts b/test/sync-status-coherence-7189.test.ts
new file mode 100644
index 0000000000..c36ad76270
--- /dev/null
+++ b/test/sync-status-coherence-7189.test.ts
@@ -0,0 +1,115 @@
+/**
+ * #7189 (status half): `gbrain sync status` contradicted itself while a large source fell behind. Each case below is
+ * red on master:
+ * - freshness counted only commits that already synced (`commits`, `unresolved_commits: 0`, a healthy p50) while
+ * commits sat unsynced on HEAD; it now reports `behind` (commits after the last synced one, the oldest one's age);
+ * - the notifier said "No resident … watches this source" while a sync held the source's drain lease; it now names the
+ * holder (`drain_holder`) and owes no fix while the holder makes progress;
+ * - `last_error` kept driving `needs_human`, `state` and `next` after the source's sync committed a page past it;
+ * it now reads `superseded` and drives none of them;
+ * - a top-level `needs_human: true` from a hold sat beside `last_error.needs_human: false` with nothing saying which
+ * one it came from; `needs_human_from` names it.
+ */
+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 type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.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 { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';
+import { readSyncFreshness, formatSyncFreshness } from '../src/core/persistence/sync-freshness.ts';
+import { withDrainLease } from '../src/core/persistence/sync-lease.ts';
+import { formatNotifierBlock, readNotifierBlock } from '../src/core/notifier/status.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-status-7189-'));
+let engine: BrainEngine;
+const git = (root: string, args: string[], env?: Record<string, string>) =>
+ execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } }).trim();
+const commit = (root: string, message: string, at?: number) => {
+ const env = at ? { GIT_COMMITTER_DATE: `@${at} +0000`, GIT_AUTHOR_DATE: `@${at} +0000` } : undefined;
+ git(root, ['add', '.'], env);
+ git(root, ['-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message], env);
+ return git(root, ['rev-parse', 'HEAD']);
+};
+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;
+
+/** A managed source with one synced commit. */
+async function syncedSource(): Promise<{ id: string; root: string }> {
+ const id = `st-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ mkdirSync(root); git(root, ['init', '-q']);
+ writeFileSync(join(root, 'alice-example.md'), note('Alice one.'));
+ commit(root, 'fixture', Math.floor(Date.now() / 1000) - 7200);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect((await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ return { id, root };
+}
+
+beforeAll(async () => { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; }, 60_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+
+test('freshness reports the commits on HEAD that have not synced yet and the oldest one\'s age', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { id, root } = await syncedSource();
+ const [before] = await readSyncFreshness(engine, { sourceIds: [id] });
+ expect(before!.behind).toEqual({ commits: 0, oldest_seconds: null });
+ const now = Math.floor(Date.now() / 1000);
+ writeFileSync(join(root, 'bob-example.md'), note('Bob.')); commit(root, 'two', now - 3600);
+ writeFileSync(join(root, 'carol-example.md'), note('Carol.')); commit(root, 'three', now - 60);
+ const [after] = await readSyncFreshness(engine, { sourceIds: [id] });
+ expect(after!.behind!.commits).toBe(2);
+ expect(after!.behind!.oldest_seconds).toBeGreaterThanOrEqual(3600);
+ expect(after!.behind!.oldest_seconds).toBeLessThan(3600 + 300);
+ expect(formatSyncFreshness(after!)).toMatch(/; 2 commit\(s\) not synced yet, oldest 6\d(\.\d)?m old$/);
+}), 240_000);
+
+test('the notifier names the process holding the drain lease instead of saying nothing watches the source', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { id } = await syncedSource();
+ const idle = await readNotifierBlock(engine, id);
+ expect(idle!.resident).toBeNull();
+ expect(idle!.drain_holder).toBeNull();
+ expect(idle!.fix!.why).toContain('No resident');
+ const seen: Array<Awaited<ReturnType<typeof readNotifierBlock>>> = [];
+ await withDrainLease(engine, id, { holder: { kind: 'serve', id: 'serve-example' } }, async () => {
+ seen.push(await readNotifierBlock(engine, id), await readNotifierBlock(engine, id, { remote: true }));
+ return { status: 'synced' } as never;
+ });
+ const [held, remote] = seen;
+ expect(held!.resident).toBeNull();
+ expect(held!.drain_holder).toMatchObject({ kind: 'serve', id: 'serve-example', pid: process.pid });
+ expect(held!.fix).toBeNull();
+ expect(formatNotifierBlock(id, held!)).toContain('serve (PID');
+ expect(formatNotifierBlock(id, held!)).toContain('holds the drain lease');
+ expect(remote!.drain_holder).toMatchObject({ kind: 'serve', id: null, host: null, pid: null });
+}), 240_000);
+
+test('a last error the source\'s sync has committed past reads superseded and sets neither needs_human, state nor next', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { id } = await syncedSource();
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ const key = `${id}:cursor-example`;
+ await recordManagedSyncFailure(engine, { source_id: id, source_incarnation: incarnation, path: 'big-example.md', code: 'file_too_large', message: 'The file is over the page size limit.',
+ request_id: null, run_id: 'run-example', target: null, cursor_key: key, phase: 'receipt', state: 'failed', observation_id: 'run-example:0' });
+ const live = await readSyncStatus(engine, id);
+ expect(live.last_error).toMatchObject({ code: 'file_too_large', needs_human: true });
+ expect(live.last_error!.superseded).toBeUndefined();
+ expect(live.needs_human).toBe(true);
+ expect(live.needs_human_from).toEqual({ kind: 'last_error', code: 'file_too_large' });
+ expect(live.state).toBe('blocked');
+
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at = now() - interval '2 hours' WHERE op='managed-sync-failure' AND fingerprint=$1", [key]);
+ const past = await readSyncStatus(engine, id);
+ expect(past.last_error).toMatchObject({ code: 'file_too_large', superseded: { at: expect.any(String) } });
+ expect(past.needs_human).toBe(false);
+ expect(past.needs_human_from).toBeNull();
+ expect(past.state).not.toBe('blocked');
+ expect(past.reason).not.toBe('last_error');
+ expect(past.next?.user_message).toBeUndefined();
+}), 240_000);