Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): sources resolve-path, landing gaps, and one meaning of blocked (GBRA-150)

garrytand11b4c85e1af
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index f999fc141d..5958d57b16 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -4,7 +4,7 @@
<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->
<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->
-Every non-localOnly operation on the MCP surface: 157 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
+Every non-localOnly operation on the MCP surface: 158 tools across 26 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
## admin
@@ -164,6 +164,12 @@ Every non-localOnly operation on the MCP surface: 157 tools across 25 areas. **S
| `ontology_get` | Life Chronicle: the current resolved per-entity ontology (dimension → value) at `asof` (default now), with provenance + confidence + validity. | read | | |
| `ontology_propose` | Life Chronicle: record one ontology observation (entity has dimension=value), sourced + confidence-weighted + bi-temporal. | write | | |
+## other
+
+| Tool | Description | Scope | Starter | Gate |
+|---|---|---|---|---|
+| `sources_resolve_path` | Read-only: what gbrain did with each file path of a source, by its own rules. | read | | |
+
## pages
| Tool | Description | Scope | Starter | Gate |
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 64744c0580..499235fd3b 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -37,6 +37,9 @@
- `src/core/repair/legacy-twins.ts` — `gbrain repair legacy-twins --source <id>` (#6885): explicit-only, preview-bound, destructive consent (`LEGACY_TWINS_CONSENT_TEXT`). `scanLegacyTwins` reads a source's live pages with no recorded origin and no `database_only_reason` in id batches (at most `LEGACY_TWINS_SCAN_LIMIT`), keeps those whose slug `slugifyPath` folds differently, and pairs each with the live page at the folded slug that records a file (at most `LEGACY_TWINS_LIMIT` pairs and decisions). `pairVerdict` lists a pair as a decision (never merged) for differing `content_hash`, several legacy candidates, a twin file `liveFileDrift` does not call `agrees`, a file at the twin's own slug path, twin withdrawals, a legacy `file:` URI or a twin slug outside the op grammar. The preview binds pairs to the owner (host, worktree, owner epoch, incarnation) and both pages' ids, slugs and revisions; the apply refuses `not_owner_host`, `legacy_twins_storage_unknown`, `preview_changed` and `legacy_twin_mass_merge_refused` (`massTwins`, the sync valve). Each pair re-checks with `pairNow`, then a managed brain submits one `managed_maintenance_merge_legacy_twin` request on the twin (`prepareLegacyTwinMerge`, dispatched from `prepared-maintenance.ts`: no file target, `databaseOnlyReason: 'shared_origin'`, the legacy key in `additionalPageKeys`, `pairLocked` under the publication locks); an unmanaged brain merges in `maintenanceTransaction` under both page locks. `applyTwinMerge` records the twin's `source_path` on the legacy page, clears the twin's origin (so its tombstone's retention purge is database-only, never a `shared_origin` refusal), moves links (deduplicated; pair links stay), timeline rows, raw data, attachments, page aliases and facts about the twin, records the twin slug as a `slug_aliases` row, versions and soft-deletes the twin, and moves the twin's `sync-import-provenance` record to the legacy page at its post-write revision. Outcomes `merged`, `changed_since_preview`. Tests: `test/repair-legacy-twins-6885.test.ts` (Postgres: `test/e2e/repair-legacy-twins-6885-postgres.test.ts`).
- `src/core/persistence/unindexed-files.ts` — #6865 the unindexed-file detector: `findUnindexedFiles(engine, sourceId, opts)` streams `git ls-tree -r -l -z` of the source's last synced commit, filters it through discovery's own `loadSyncEligibility`, and in batches (one `pages.source_path = ANY` read on `pages_source_path_idx`, one hold read by fingerprint) keeps files with no live page recording their origin (source-path space, with the legacy Git-root spelling in source-root mode), no hold and no scheduled re-screen (`readGitHoldRetryPaths`; those count as `scheduled`); a file whose path slug belongs to a live page with another or no origin is still unindexed and counted `slug_taken`. Found files are screened read-only with `screenImportContent` (at most 2,000 per pass, the rest `unscreened`). Folder-scaffolding names sync skips on purpose (`isSyncMetafile`) that would otherwise be eligible (checked against a probe name in the same directory plus `sync.exclude` and the reserved skill paths) and carry a frontmatter `type:` or `title:` are counted apart as `metafile_skipped` with samples, and never scheduled. A time or count budget stops it with `complete: false` and a cursor (the last Git path, compared in byte order, which is Git's recursive tree order). `refreshUnindexedFiles` continues an incomplete stored result, schedules the found paths (`requestGitHoldRetry`, a scheduling write only) and stores one `op_checkpoints` row per source (op `unindexed-files`, fingerprint the source id; the 7-day checkpoint purge applies). `judgeUnindexedFiles` is doctor's read: unscheduled finds, scheduled paths still in the retry row (waiting for a sync), and consumed paths that still have no page and no hold, without scanning. Test: `test/unindexed-files.test.ts`.
- `src/commands/doctor/checks/unindexed-files.ts` — #6865 doctor `unindexed_files` (BRAIN, after `missing_recorded_files`): reads `judgeUnindexedFiles` for each bound managed Git source; `ok` when every result is complete, recent and nothing is missing; `warn` with counts by code, samples and age when files are unindexed (fix `gbrain sources retry-held <id> --unindexed`, `then` the follow-up sync from `gitFollowUpSync`, verify `gbrain doctor --only unindexed_files --json`) or scheduled and waiting (fix the sync); info `unknown` when a result is missing, older than 7 days or incomplete with nothing found, naming the maintenance phase and the command; info `not_applicable` on a classic brain. `metafile_skipped` files are named in the message and details and never make it warn; alone they are info `degraded` with a `user` fix (rename the file, then the sync). Test: `test/unindexed-files.test.ts`.
+- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. Tests: `test/sources-resolve-path.test.ts`.
+- `src/core/persistence/landing-gaps.ts` — GBRA-150 `readLandingGaps`: committed managed_sync receipts of the last 24 h (at most 2,000, newest first through the watermark index, 2 s statement probe; a timeout reads `unknown`, never ok) whose page is still missing, has chunks waiting for vectors, has no chunks, or is quarantined past `sync.freshness_target_seconds`; one row per page with reason and fix. Consumers: `sync status --detail` `landing` / `landing_read` (`sync-status.ts`) and doctor `sync_landing_gaps`. Tests: `test/sync-landing-gaps.test.ts`.
+- `src/commands/doctor/checks/landing-gaps.ts` — GBRA-150 doctor `sync_landing_gaps` (registered after `partial_embedding`, one of `CHEAP_INCIDENT_CHECKS`): warns per source with the gap count by reason and the first fix from `readLandingGaps`; `unknown` read stays a warning, never ok. Tests: `test/doctor-sync-landing-gaps.test.ts`.
- `src/commands/doctor/checks/missing-recorded-files.ts` — #6609 doctor `missing_recorded_files` (BRAIN, after `ghost_pages`): the classic-brain counterpart of `ghost_pages`. Read-only; per source with a checkout on this host and managed persistence off it runs `scanMissingRecordedFiles` (`src/core/persistence/detached-pages.ts`) and warns with counts, samples and an `ask_user` fix (put the file back and sync, or `gbrain delete` then `gbrain restore <slug> --source-id <id> --detach`) for live pages whose recorded file a `gbrain sync --full` would not find; `ok` + `not_applicable` when no source qualifies. Test: `test/restore-detach-6609.test.ts`.
- `src/core/persistence/overwritten-edits.ts` — #6712 follow-up: `scanOverwrittenEdits` finds live pages whose database-only revision a managed-sync import replaced with different content and no hold, from durable rows only (it survives receipt compaction): `page_versions.write_request_id` / `archived_write_request_id`, the writer's committed receipt (`outcome.persistence.mode = 'database'`, not an import, no `git` effect for that revision, not a read-only mirror write), the archiving request recognised as a managed-sync import by intent kind or, once compacted, by operation `submit_job` + `outcome.imported_file` without `connector_database`, and `reconcileCanonical` digests (the import's own revision differs; no later revision holds the edit again). `high` or `unknown` (`no_persistence_outcome`, `import_content_unreadable`, `segmented`); the newest open overwrite per page; at most `OVERWRITE_SCAN_LIMIT` candidate versions per source. Revisions with no recorded writer are not reported.
- `src/commands/doctor/checks/overwritten-edits.ts` — doctor `sync_overwritten_db_edits` (BRAIN, after `missing_recorded_files`): per source count and first slugs from `scanOverwrittenEdits`; `warn` only for `high` findings, with the read-only `gbrain repair overwritten-edits --source <id>` preview as an `ask_user` fix; `unknown` findings are counted in `details` and never warn.
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index b188b331bc..5cd602e8d0 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -37,6 +37,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/sources-reset-upstream.ts` — `gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> [--dry-run] [--json]`, the fix for `upstream_rewritten` / `upstream_unknown` (`src/core/sync-upstream-rewrite.ts`). Refuses a managed canonical worktree (`writer_coordinator_required`) and an in-progress git operation (`git_operation_in_progress`); under the checkout's commit lock (none on `--dry-run`) refuses with `reset_upstream_refused` a HEAD or upstream other than the expected SHAs (`expect_mismatch`), no upstream (`no_upstream`), tracked edits (`dirty_tree`, names the paths) and local commits not reachable from the upstream, the recorded baseline or any old or new value of the tracking ref's reflog (`local_commits`, names them and the backup ref). Otherwise writes `refs/gbrain/backup/<UTC stamp>-<sha12>` (create-only), runs `git reset --keep <upstream>`, verifies HEAD, records the baseline and clears the divergence; never fetches. Pinned by `test/pathological/s-58-upstream-rewrite.test.ts`.
- `src/commands/sources-retry-held.ts` — `gbrain sources retry-held <id> [--dry-run] [--json]`: records a re-attempt request for a source's held connector items (and, on a managed brain, their retry-pointer rows) or a re-screen request (op `sync-hold-retry`) for its held Git files, which the next sync adds to its manifest; nothing runs now, the receipt prints the sync to run. #6278: on a managed brain that follow-up sync is built by `gitFollowUpSync`: the unfinished managed cursor's resume arguments (`readManagedSyncBacklog`, `managedSyncResumeArgs`), so `--no-embed` and the other processing options carry over instead of starting a second cursor, else the arguments a `preparation_stalled` hold recorded (`meta.stall.sync_argv`), else `--source <id> --no-pull`. `preparation_stalled` holds count under `stalled` in the repair route and need no file repair: the receipt and help point to `gbrain sources writer status --source <id> --json` first. #6865: `--unindexed` (`retryUnindexed`) runs one bounded pass of the unindexed-file detector (`persistence/unindexed-files.ts`, 60 s) for a managed Git source, schedules the found files through the same re-screen request, stores the result doctor `unindexed_files` reads (continuing an incomplete stored scan) and prints the follow-up sync with `gbrain doctor --only unindexed_files --json` as its verify; `--dry-run` lists them and writes nothing; connector and company-brain sources refuse `invalid_params`; a complete pass with nothing found prints `No unindexed files for <id>.`, an incomplete one says the scan continues. Both modes build the receipt through `receiptOf`. Tests: `test/held-files-walkthrough.test.ts`, `test/managed-sync-preparation-stalled-holds.test.ts`, `test/unindexed-files.test.ts`.
+- `src/commands/sources-resolve-path.ts` — GBRA-150: `gbrain sources resolve-path <id> <path...> [--stdin] [--json]`, the CLI face of op `sources_resolve_path` (`core/ops/sources.ts`). Paths come from argv or `--stdin` (one per line, at most `RESOLVE_PATHS_MAX` = 200); the human print is one line per path (state, slug, why, fix), `--json` the op's result. Read-only. Tests: `test/sources-resolve-path.test.ts`. Harness guide: `docs/guides/resolve-paths.md`.
- `src/commands/sources-set-path.ts` — `gbrain sources set-path <id> <path> [--force]`: unmanaged installations retain the legacy pointer repair and overlap check. Managed installations use the verified lifecycle rebind; force never bypasses ownership or manifest checks. Relative paths and MSYS spellings are normalized before routing. The `default_source_local_path` doctor check names this as the repair.
- `src/commands/sources-strategy.ts` — `gbrain sources set-strategy <id> <markdown|code|auto>` (#4899, PR #5955): writes `sources.config.strategy` through `updateSourceConfig` (single-key merge; every other config key survives), the value `sync --all`, autopilot, the dream cycle and the MCP `sync` op pass to the per-source sync when the caller names no `--strategy`; unset means `markdown`. The one writer of that key (no `sources add --strategy`, no op param). Connector kinds refuse it. [R26]: refuses with `sync_run_unfinished` (exit 1) while the source has an unfinished `managed-sync` cursor, naming the resume and the orphan repair, because the frozen manifest was classified under the old strategy; re-stating the current value is allowed. `sources list --json` and `listSources` report `strategy` (`null` when unset). Pinned by `test/sources-strategy.test.ts`.
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index 242766d0cd..d965f5eda4 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`).
+- `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-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
new file mode 100644
index 0000000000..4a314dfeac
--- /dev/null
+++ b/docs/guides/resolve-paths.md
@@ -0,0 +1,65 @@
+# Resolve a file path the way gbrain does
+
+A harness that checks whether a commit "landed" in search (a landing check, an agent that just wrote a page, a CI step) should
+ask gbrain what it did with each file, not re-implement gbrain's rules. A copied rule drifts. Three real shapes of that drift:
+
+- **Slug folding.** gbrain lowercases each path segment and strips leading and trailing hyphens, so
+ `articles/outlet-example/a-headline-.md` is the page `articles/outlet-example/a-headline`. A copy that only lowercases looks
+ for a page that never exists.
+- **Case-folded twins.** A deleted `notes/Call-AbC.md` and a live `notes/call-abc.md` share one slug. Checked by slug, the
+ delete looks failed because the twin's page is live. Checked by origin (the page that records the file as its
+ `source_path`), it is a clean delete.
+- **Skipped scaffolding.** Sync skips folder scaffolding names (`index.md`, `README.md`, `schema.md`, `log.md`, `RESOLVER.md`; root
+ `AGENTS.md` and `CLAUDE.md`). Waiting for a page there waits forever.
+
+## The command
+
+```bash
+gbrain sources resolve-path <source-id> <path...> [--stdin] [--json]
+git diff --name-only HEAD~1 | gbrain sources resolve-path default --stdin --json
+```
+
+MCP: `sources_resolve_path` with `{ id, paths }` (read scope, confined to the caller's sources). At most 200 paths per call. Paths
+are relative to the source root, or to the Git top level when they start with the source's subpath. Read-only: Git object reads
+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`
+(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).
+
+## States
+
+| 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 |
+| `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` |
+| `empty` | live page with no body | none |
+| `held` | a sync hold waits on the file | `gbrain sync status --source <id> --json` lists the hold's own fix |
+| `skipped` | sync never imports this path (`skipped.reason`) | none: no page by design |
+| `not_synced_yet` | the file at HEAD differs from the last synced commit | `gbrain sync --source <id> --no-pull` |
+| `missing` | committed and eligible, no page, no hold, no skip: a real gap | `gbrain sources retry-held <id> --unindexed`, then the sync |
+| `slug_taken` | no page because another file's page owns the slug | rename one of the two files |
+| `page_deleted` | committed, but its page was deleted and sync keeps it deleted | restore the page, or delete the file |
+| `deleted` | the file is gone and no live page records it as its origin | none (a `slug_owner` twin is not this file's page) |
+| `stale_page` | the file is gone but its page is still live | the sync |
+
+A landing check treats `searchable`, `keyword_only`, `empty`, `skipped` and `deleted` as landed, `pending_embedding` as landed for
+keyword search, `not_synced_yet` as lag, and every other state as an alert carrying its `why` and `fix`.
+
+## Synced but not searchable
+
+`gbrain sync status --source <id> --detail --json` adds a `landing` block, and doctor `sync_landing_gaps` (a cheap incident
+check, so it answers even when a full doctor run cannot finish) reads the same thing: pages a managed sync committed more than
+the source's freshness target ago (`sync.freshness_target_seconds`, default 300 s) that search still cannot fully see, one row per
+page with its reason (`pending_embedding`, `chunkless`, `quarantined`, `page_missing`) and fix. It reads at most the newest 2,000
+committed sync receipts of the last 24 h and says `unknown`, never `ok`, when its read times out.
+
+## What "blocked" means
+
+`gbrain sync status` reads `blocked` only when the source cannot advance without a person or an operator, the same meaning as a
+sync run's drain outcome and a sync job's `blocked` progress. A file hold that waits on a person while the rest of the source
+keeps syncing reads `synced` with reason `held_needs_human`; `needs_human` and `next` still carry that decision.
diff --git a/plugin/README.md b/plugin/README.md
index f5dadb3091..94292202c2 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -8,7 +8,7 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs `gbrain serve --surface full` — 178
+The plugin's MCP server runs `gbrain serve --surface full` — 179
operations, the same surface every stdio registration gbrain writes pins.
Every gbrain operation the bundled skills name is on it. A harness that caps
its tool count can narrow this machine's plugin surface with
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 1da2fb613d..a39afa7a48 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 conne
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
src/core/minions/worker.ts 1788 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts)
-src/commands/sources.ts 2062 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured
+src/commands/sources.ts 2065 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts)
src/core/link-extraction.ts 2421 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1)
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
diff --git a/src/commands/doctor/checks/landing-gaps.ts b/src/commands/doctor/checks/landing-gaps.ts
new file mode 100644
index 0000000000..71d3042124
--- /dev/null
+++ b/src/commands/doctor/checks/landing-gaps.ts
@@ -0,0 +1,61 @@
+/**
+ * GBRA-150 `sync_landing_gaps`: pages a managed sync committed more than the source's freshness target ago
+ * (`sync.freshness_target_seconds`, 300 s) that search still cannot fully see: chunks with no vector, no chunk rows,
+ * quarantined, or removed by a write outside sync after it synced (`persistence/landing-gaps.ts`). Bounded reads only
+ * (the last 24 h of receipts, at most 2,000 per source), so it is a cheap incident check that runs before the full scans
+ * and still answers on a brain whose default doctor run cannot finish.
+ *
+ * ok when no bound source has a gap; warn naming each source's gaps and the first page's fix (the paid catch-up drain
+ * for vectors asks first); info when a read did not answer (unknown, never ok) or no managed source is bound.
+ */
+import type { Check } from '../../doctor.ts';
+import { infoCheck } from '../check-fix.ts';
+import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { managedPersistenceEnabled } from '../../../core/persistence/ownership.ts';
+import { readLandingGaps, type LandingGaps } from '../../../core/persistence/landing-gaps.ts';
+
+const DOCS = 'docs/guides/resolve-paths.md#synced-but-not-searchable';
+
+async function runLandingGaps(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ const engine = connectedEngine(ctx);
+ if (!(await managedPersistenceEnabled(engine))) {
+ checks.push(infoCheck('sync_landing_gaps', 'Not applicable: managed persistence is off, so no sync receipts say when a page landed.', 'not_applicable', undefined, { docs: DOCS }));
+ return checks;
+ }
+ const sources = (await engine.executeRaw<{ id: string }>(`SELECT s.id FROM sources s WHERE s.archived IS NOT TRUE
+ AND EXISTS (SELECT 1 FROM persistence_source_bindings b WHERE b.source_id=s.id AND b.source_incarnation=s.incarnation)
+ AND ($1::text[] IS NULL OR s.id=ANY($1::text[])) ORDER BY s.id`, [doctorSourceIds(ctx) ?? null])).map(row => row.id);
+ const read: Array<{ source_id: string; gaps: LandingGaps }> = [];
+ for (const id of sources) read.push({ source_id: id, gaps: await readLandingGaps(engine, id) });
+ const details = { docs: DOCS, sources: read.map(({ source_id, gaps }) => ({ source_id, ...gaps })) };
+ const found = read.filter(entry => entry.gaps.status === 'ok' && entry.gaps.gaps > 0);
+ if (found.length) {
+ const first = found[0]!.gaps.status === 'ok' ? found[0]!.gaps.pages.find(page => page.fix) : undefined;
+ const lines = found.map(({ source_id, gaps }) => gaps.status === 'ok'
+ ? `${source_id}: ${gaps.gaps} page(s) (${Object.entries(gaps.by_state).map(([state, n]) => `${state} ${n}`).join(', ')}; e.g. ${gaps.pages.slice(0, 3).map(page => `${page.slug} [${page.state}]`).join(', ')})` : '');
+ checks.push({ name: 'sync_landing_gaps', status: 'warn', details, ...(first?.fix ? { fix: first.fix } : { fix_unavailable_reason: 'operator_judgement' as const }),
+ message: `Pages synced more than their freshness target ago are not fully searchable: ${lines.join('; ')}. `
+ + 'pending_embedding pages are found by keyword but not by vector search; chunkless pages have no searchable body; quarantined pages are hidden; page_missing pages were removed outside sync. '
+ + `gbrain sync status --source <id> --detail --json lists each page with its fix.` });
+ return checks;
+ }
+ const unknown = read.filter(entry => entry.gaps.status === 'unknown');
+ if (unknown.length) {
+ checks.push(infoCheck('sync_landing_gaps', `Landing gaps are unknown for ${unknown.map(entry => `${entry.source_id} (${entry.gaps.status === 'unknown' ? entry.gaps.reason : ''})`).join(', ')}; this is not a clean result.`,
+ 'unknown', undefined, details));
+ return checks;
+ }
+ if (!read.some(entry => entry.gaps.status === 'ok')) {
+ checks.push(infoCheck('sync_landing_gaps', 'Not applicable: no managed source is bound to a checkout.', 'not_applicable', undefined, details));
+ return checks;
+ }
+ checks.push({ name: 'sync_landing_gaps', status: 'ok', details, message: 'Every page managed sync committed past its freshness target in the last 24 h is searchable.' });
+ return checks;
+}
+
+export const syncLandingGapsEntry: DoctorEntry = {
+ name: 'sync_landing_gaps',
+ emits: ['sync_landing_gaps'],
+ run: runLandingGaps,
+};
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index cc72c86ea7..1e14c2f9ca 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -121,6 +121,7 @@ import { ghostPagesEntry } from './checks/ghost-pages.ts';
import { originTwinsEntry } from './checks/origin-twins.ts';
import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgrades.ts';
import { unindexedFilesEntry } from './checks/unindexed-files.ts';
+import { syncLandingGapsEntry } from './checks/landing-gaps.ts';
import { purgeParkedPagesEntry } from './checks/purge-parks.ts';
import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';
import { overwrittenEditsEntry } from './checks/overwritten-edits.ts';
@@ -187,6 +188,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
// #6803 C2: then the cheap incident checks, before any full scan (CHEAP_INCIDENT_CHECKS, pinned by name in test/doctor-entry-deadline-6803.test.ts).
linksExtractionLagEntry,
partialEmbeddingEntry,
+ syncLandingGapsEntry,
pgvectorEntry,
rlsEntry,
schemaVersionEntry,
@@ -274,6 +276,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
*/
export const CHEAP_INCIDENT_CHECKS: ReadonlySet<string> = new Set([
'persistence_capacity', 'managed_sync_not_moving', 'managed_sync_blocked', 'text_projection_readiness', 'partial_embedding', 'links_extraction_lag',
+ // GBRA-150: bounded receipt and page reads, so a brain whose default run cannot finish still names its landing gaps.
+ 'sync_landing_gaps',
]);
const CONNECTION_LANE: ReadonlySet<DoctorEntry> = new Set([offlineConnectionEntry, dbChecksGateEntry, connectionEntry, connectionGateEntry]);
diff --git a/src/commands/sources-resolve-path.ts b/src/commands/sources-resolve-path.ts
new file mode 100644
index 0000000000..0ba69a2f7a
--- /dev/null
+++ b/src/commands/sources-resolve-path.ts
@@ -0,0 +1,35 @@
+/**
+ * GBRA-150: `gbrain sources resolve-path <id> <path...> [--stdin] [--json]`, the CLI face of the read-only
+ * `sources_resolve_path` operation (src/core/persistence/resolve-paths.ts): what gbrain did with each file path of a source.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { OperationError } from '../core/ops/contract.ts';
+import { resolveSourcePaths } from '../core/persistence/resolve-paths.ts';
+
+export const RESOLVE_PATH_USAGE = 'Usage: gbrain sources resolve-path <id> <path...> [--stdin] [--json]';
+
+export async function runResolvePath(engine: BrainEngine, args: string[]): Promise<void> {
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`${RESOLVE_PATH_USAGE}\n\n`
+ + 'Read-only. For each file path of a source (relative to the source root, or to the Git top level), print the slug\n'
+ + 'gbrain gives it, whether sync skips it (and why), its hold, its page and embedding state, whether search can find it\n'
+ + 'now, and the command that moves it on. A deleted path is checked by the page that records it as its origin, never by\n'
+ + 'slug, so a case-folded twin that owns the slug is not mistaken for a failed delete.\n'
+ + ' --stdin read further paths from standard input, one per line (for example from git diff --name-only)\n'
+ + ' --json print the result as JSON');
+ return;
+ }
+ const unknown = args.find(arg => arg.startsWith('--') && arg !== '--json' && arg !== '--stdin');
+ if (unknown) throw new OperationError('invalid_params', `Unknown option: ${unknown}.`, RESOLVE_PATH_USAGE);
+ const [sourceId, ...paths] = args.filter(arg => !arg.startsWith('--'));
+ if (args.includes('--stdin')) paths.push(...(await Bun.stdin.text()).split('\n').map(line => line.trim()).filter(Boolean));
+ if (!sourceId || !paths.length) throw new OperationError('invalid_params', 'Name one source and at least one path.', RESOLVE_PATH_USAGE);
+ const result = await resolveSourcePaths(engine, sourceId, paths);
+ if (args.includes('--json')) { console.log(JSON.stringify(result, null, 2)); return; }
+ console.log(`Source ${result.source_id} (${result.mode}), last synced commit ${result.last_commit?.slice(0, 12) ?? '(none)'}${result.head && result.head !== result.last_commit ? `, checkout HEAD ${result.head.slice(0, 12)}` : ''}`);
+ for (const p of result.paths) {
+ console.log(` ${p.path} -> ${p.slug}: ${p.state}${p.searchable === true ? ' (searchable)' : p.searchable === 'keyword' ? ' (keyword search only)' : ''}`);
+ console.log(` ${p.why}`);
+ if (p.fix?.argv) console.log(` next: ${p.fix.argv.join(' ')}`);
+ }
+}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 13b8440f44..6ba65150b6 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1921,6 +1921,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v
case 'set-path': { const { runSetPath } = await import('./sources-set-path.ts'); return runSetPath(engine, rest); }
case 'shared-skills': { const { runSourcesSharedSkills } = await import('./sources-shared-skills.ts'); return runSourcesSharedSkills(engine, rest); }
case 'retry-held': { const { runRetryHeld } = await import('./sources-retry-held.ts'); return runRetryHeld(engine, rest); }
+ case 'resolve-path': { const { runResolvePath } = await import('./sources-resolve-path.ts'); return runResolvePath(engine, rest); }
case 'reset-upstream': { const { runResetUpstream } = await import('./sources-reset-upstream.ts'); return runResetUpstream(engine, rest); }
case 'audit': return runAudit(engine, rest);
// v0.46 github-source demo (offline, privacy-clean fixtures)
@@ -2016,6 +2017,8 @@ Subcommands:
Runs nothing now. Most Git holds re-screen by themselves (file changed or deleted, newer gbrain); fix
frontmatter holds with gbrain repair frontmatter --source <id>; preview fence holds (invalid_fence) with gbrain repair fences --source <id>.
--unindexed instead schedules committed files with no page and no hold (doctor unindexed_files).
+ resolve-path <id> <path...> [--stdin] [--json]
+ Read-only: the slug, skip, hold, page and search state gbrain gives each file path (for landing checks).
reset-upstream <id> --expect-local <sha> --expect-upstream <sha> [--dry-run] [--json] After an upstream force-push (upstream_rewritten): back up HEAD, reset to upstream.
shared-skills <id> on|off|status [--json]
Opt a source out of (or back into) shared-skills adoption; status explains its effective policy.
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index d615a6c69e..72cf30fe87 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -153,6 +153,7 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis
const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })),
git_push_holds: status.git_push_holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null,
checkpoint_blockers_read: read(status.checkpoint_blockers_read), cursors_read: read(status.cursors_read), terminal_failures_read: read(status.terminal_failures_read),
+ landing_read: read(status.landing_read), landing: status.landing?.status === 'ok' ? { ...status.landing, pages: status.landing.pages.map(page => ({ ...page, fix: page.fix ? renderAction(page.fix, ctx) : null })) } : status.landing,
capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, freshness, notifier, ...(notices.length ? { notices } : {}) };
if (args.includes('--json')) return writeJsonDocument(JSON.stringify(rendered, null, 2));
const c = status.cursor;
@@ -178,6 +179,12 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis
for (const b of t.active_blockers) console.log(` BLOCKING ${b.kind}: request ${b.request_id}${b.slug ? ` (${b.slug})` : ''} [${b.category}]`);
if (t.active_blockers.length || t.unresolved.rows) console.log(` drill down: ${t.drill_down.join(' ')}`);
}
+ const landing = status.landing;
+ if (landing?.status === 'ok') {
+ console.log(` synced but not searchable after ${landing.after_seconds} s (last ${landing.window_hours} h, ${landing.checked} page(s)${landing.complete ? '' : ', newest receipts only'}): ${landing.gaps}`
+ + `${landing.gaps ? ` (${Object.entries(landing.by_state).map(([state, n]) => `${state} ${n}`).join(', ')})` : ''}`);
+ for (const page of landing.pages) console.log(` ${page.slug}: ${page.state}, synced ${page.age_seconds} s ago${page.fix?.argv ? `; fix: ${page.fix.argv.join(' ')}` : ''}`);
+ } else if (landing) console.log(` synced but not searchable: ${landing.status} (${landing.reason})`);
for (const hold of status.git_push_holds) console.log(` git backups not pushed: ${hold.retrying} retrying, ${hold.parked} parked (${hold.codes.join(', ')}) since ${hold.oldest_at}${hold.conflict ? `; CONFLICT in ${hold.conflict.paths.join(', ')} needs a person` : ''}`);
const connector = status.connector_last_error;
if (connector) console.log(` connector: ${connector.stopped ? 'STOPPED, ' : ''}the last ${connector.consecutive} run(s) ended on ${connector.code}${connector.slug ? ` at ${connector.slug}` : ''}: ${connector.message}`);
@@ -192,6 +199,7 @@ export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'state
switch (status.reason) {
case 'nothing_pending': return `Source ${status.source_id} is synced${c?.done ? ` (last run ${status.run_id?.slice(0, 8) ?? '?'} finished at ${c.index}/${c.total})` : ''}.`;
case 'held_by_design': return `Source ${status.source_id} is synced; ${status.holds.length} file(s) stay held by design.`;
+ case 'held_needs_human': return `Source ${status.source_id} is synced except ${status.holds.length} held file(s), some waiting on a person (see NEEDS HUMAN below); the rest keeps syncing.`;
case 'live_job': return `Source ${status.source_id} is resumable: sync job #${status.live_job_id} is draining it.`;
case 'cursor_unfinished': return `Source ${status.source_id} is resumable: run ${status.run_id?.slice(0, 8) ?? '?'} stands at ${c?.index ?? '?'}/${c?.total ?? '?'}; the next sync resumes it.`;
case 'last_error': return `Source ${status.source_id} is resumable: the last run recorded a failure that a rerun holds or retries.`;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1cb43d132a..e13d24c2b8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1019,6 +1019,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #7112 (Postgres 15 SQL compatibility, owner-exception error text). `since` is restamped at the merge slot.
{ since: '0.60.326.0', text: 'Managed sync, put_page, source config updates, archive and restore, and the dream-breaker reset work again on Postgres 15: they used the Postgres 16+ `IS JSON` predicate (and doctor jsonb_integrity and `gbrain repair-jsonb` used `pg_input_is_valid`), a syntax error (42601) on Postgres 15 that failed every managed sync checkpoint. They now use a new `gbrain_try_jsonb(text)` function (migration v263) on every server. The same guard no longer fails a config merge or a dream-breaker reset whose stored text is JSON but not jsonb (a \\u0000 escape); that value now reads as an empty object, like other unparseable text.' },
{ since: '0.60.326.0', text: 'A write that ends `storage_error` on an unexpected database server error now keeps, owner-side in the receipt, the server message with any quoted value replaced by … (`error_text`; object names stay only in known catalog messages or when the statement names them), the failing statement with every literal, number and comment replaced and never its parameters (`statement`), and the error position; a PL/pgSQL RAISE or ASSERT keeps no text. On the brain host `gbrain write-request <id> --json` now prints the receipt\'s `error_detail`, and the persistence consumer log line adds `error_text=`, `statement=` and `position=`. Remote readers see no new field.' },
+ // 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.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 765cfee9b0..c56ca30dba 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -213,6 +213,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'missing_recorded_files',
// #6865: committed files of a managed Git source with no page and no hold, from the stored detector result (doctor/checks/unindexed-files.ts).
'unindexed_files',
+ // GBRA-150: pages a managed sync committed past the freshness target that search cannot fully see (doctor/checks/landing-gaps.ts).
+ 'sync_landing_gaps',
// #6712: live pages whose database-only edit an incremental sync overwrote without a hold (doctor/checks/overwritten-edits.ts).
'sync_overwritten_db_edits',
'unified_multimodal_coverage',
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index 432eaebbf4..bd8a3b47c0 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -946,8 +946,8 @@ const normalizeStateRow = compileRowNormalizer<EmbeddingStateRow>({ chunks: 'big
* prints, to report completeness).
*/
export async function listEmbeddingStateRows(exec: ScopedRead, column: string,
- opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
- const scope = embeddingStateScope(opts.sourceIds);
+ opts: { sourceIds?: string[]; slugs?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
+ const scope = opts.slugs ? sqlFragment`${embeddingStateScope(opts.sourceIds)} AND p.slug = ANY(${opts.slugs}::text[])` : embeddingStateScope(opts.sourceIds);
const { rows } = await exec.run(sqlFragment`
SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue
FROM (
diff --git a/src/core/engine.ts b/src/core/engine.ts
index cf45e69609..aa35338127 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1364,7 +1364,7 @@ export interface BrainEngine {
/** #6696 B3: counts per embedding state over the ACTIVE column (contract and ops/full semantics: src/core/embedding-state.ts). */
readEmbeddingStateCounts(opts: { mode: 'ops' | 'full'; sourceIds?: string[]; purgeWindowHours: number }): Promise<EmbeddingStateCounts>;
/** #6696 B3: one row per (page, state) in `states`, ordered (state, source_id, slug), at most `limit` rows. */
- listEmbeddingStateRows(opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]>;
+ listEmbeddingStateRows(opts: { sourceIds?: string[]; slugs?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]>;
/**
* Delete every chunk for a page. Internal page-id lookup is sourceId-scoped
* when `opts.sourceId` is given; otherwise the bare-slug subquery returns
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index 84eadef04d..3d1b0c568a 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -170,6 +170,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"sources_remove": [load_sources, "sourcesOperations"],
"sources_status": [load_sources, "sourcesOperations"],
"sources_inspect": [load_sources, "sourcesOperations"],
+ "sources_resolve_path": [load_sources, "sourcesOperations"],
"request_tools": [load_request_tools, "requestToolsOperations"],
"get_recent_salience": [load_salience, "salienceOperations"],
"find_anomalies": [load_salience, "salienceOperations"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index b0aa76284b..4642f3d9ea 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -4506,6 +4506,33 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"hidden": true
}
},
+ {
+ "name": "sources_resolve_path",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Read-only: what gbrain did with each file path of a source, by its own rules. Per path: the slug sync gives it, whether sync skips it (metafile, excluded, pruned) and why, its sync hold, its page with chunk and embedding counts, whether search finds it now, and the command that moves it on. A deleted path is checked by the page that records it as its origin, never by slug. Use it in landing checks instead of re-implementing slugging. Confined to the caller's source scope.",
+ "params": {
+ "id": {
+ "type": "string",
+ "required": true,
+ "description": "Source id, as listed by sources_list (e.g. 'default')."
+ },
+ "paths": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "required": true,
+ "description": "File paths relative to the source root (or to the Git top level), at most 200, e.g. the paths a commit changed."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "sources_resolve_path",
+ "hidden": true
+ }
+ },
{
"name": "request_tools",
"idempotent": false,
diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.ts
index 741d6e0221..aff9fa7053 100644
--- a/src/core/ops/sources.ts
+++ b/src/core/ops/sources.ts
@@ -333,6 +333,29 @@ const sources_inspect: Operation = {
cliHints: { name: 'sources_inspect', hidden: true },
};
+const sources_resolve_path: Operation = {
+ name: 'sources_resolve_path',
+ mutating: false,
+ idempotent: true,
+ outputRedaction: 'no_stored_text',
+ description:
+ 'Read-only: what gbrain did with each file path of a source, by its own rules. Per path: the slug sync gives it, whether ' +
+ 'sync skips it (metafile, excluded, pruned) and why, its sync hold, its page with chunk and embedding counts, whether ' +
+ 'search finds it now, and the command that moves it on. A deleted path is checked by the page that records it as its ' +
+ 'origin, never by slug. Use it in landing checks instead of re-implementing slugging. Confined to the caller\'s source scope.',
+ params: {
+ id: { type: 'string', required: true, description: "Source id, as listed by sources_list (e.g. 'default')." },
+ paths: { type: 'array', items: { type: 'string' }, required: true, description: 'File paths relative to the source root (or to the Git top level), at most 200, e.g. the paths a commit changed.' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ assertSourceInCallerScope(ctx, p.id as string);
+ const { resolveSourcePaths } = await import('../persistence/resolve-paths.ts');
+ return resolveSourcePaths(ctx.engine, p.id as string, (p.paths as unknown[] ?? []).map(String));
+ },
+ cliHints: { name: 'sources_resolve_path', hidden: true },
+};
+
export const sourcesOperations: Operation[] = [
- whoami, sources_add, sources_list, sources_remove, sources_status, sources_inspect,
+ whoami, sources_add, sources_list, sources_remove, sources_status, sources_inspect, sources_resolve_path,
];
diff --git a/src/core/persistence/landing-gaps.ts b/src/core/persistence/landing-gaps.ts
new file mode 100644
index 0000000000..3bdb5b3ecd
--- /dev/null
+++ b/src/core/persistence/landing-gaps.ts
@@ -0,0 +1,90 @@
+/**
+ * GBRA-150: pages a managed sync committed more than `afterSeconds` ago (default: the source's freshness target,
+ * `sync.freshness_target_seconds`, 300 s) that search still cannot fully see, each with its reason and fix. A committed
+ * import receipt means the page write landed; this read says whether the page then became searchable: its chunks exist
+ * and carry a vector (or the brain is keyless by choice), it is not quarantined, and it is still live.
+ *
+ * Bounded and read-only: the newest committed managed-sync receipts of the source's current incarnation in the last
+ * 24 h (at most LANDING_RECEIPT_LIMIT, newest first, through the `persistence_requests_sync_watermark` partial index),
+ * the newest receipt per slug only (a later delete explains a missing page), then one page read and one embedding-state
+ * read for those slugs (`embedding-state.ts` classifier). A read that times out says `unknown`, never `ok`. Readers:
+ * `gbrain sync status` (`landing`) and doctor `sync_landing_gaps`.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.ts';
+import { embeddingsDisabled } from '../embedding-disabled.ts';
+import { embeddingStateFix, DELETED_PAGE_PURGE_WINDOW_HOURS, type EmbeddingState } from '../embedding-state.ts';
+import { readFreshnessTarget } from './sync-freshness.ts';
+
+export const LANDING_WINDOW_HOURS = 24;
+export const LANDING_RECEIPT_LIMIT = 2_000;
+export const LANDING_PAGE_LIMIT = 20;
+const LANDING_PROBE_MS = 2_000;
+
+export type LandingGapState = 'page_missing' | 'pending_embedding' | 'chunkless' | 'quarantined';
+export interface LandingGap {
+ slug: string;
+ state: LandingGapState;
+ /** Whether search finds the page now: by keyword only, or not at all. */
+ searchable: 'keyword' | false;
+ synced_at: string;
+ age_seconds: number;
+ why: string;
+ fix: Action | null;
+}
+export type LandingGaps = { status: 'ok'; window_hours: number; after_seconds: number; checked: number; complete: boolean; gaps: number;
+ by_state: Partial<Record<LandingGapState, number>>; pages: LandingGap[] } | { status: 'unknown'; reason: string } | { status: 'not_applicable'; reason: string };
+
+const GAP: Partial<Record<EmbeddingState, LandingGapState>> = { pending: 'pending_embedding', chunkless_healable: 'chunkless', quarantined: 'quarantined' };
+const ORDER: EmbeddingState[] = ['quarantined', 'chunkless_healable', 'pending'];
+
+/** The landing gaps of one managed source; `not_applicable` without a binding (classic or connector sources keep no receipts). */
+export async function readLandingGaps(engine: BrainEngine, sourceId: string, opts: { afterSeconds?: number; limit?: number } = {}): Promise<LandingGaps> {
+ const after = opts.afterSeconds ?? (await readFreshnessTarget(engine)).seconds;
+ const [binding] = await engine.executeRaw<{ worktree_id: string; incarnation: string }>(`SELECT b.worktree_id::text AS worktree_id, b.source_incarnation::text AS incarnation
+ FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation WHERE b.source_id=$1`, [sourceId]).catch(() => []);
+ if (!binding) return { status: 'not_applicable', reason: 'no_managed_binding' };
+ let receipts: Array<{ slug: string; kind: string; completed_at: Date | string; age: number | string }>;
+ try {
+ receipts = await engine.executeRaw(`SELECT DISTINCT ON (w.slug) w.slug, w.kind, w.completed_at, extract(epoch FROM now() - w.completed_at)::float8 AS age FROM (
+ SELECT r.slug, r.sequence, r.completed_at, r.intent->>'kind' AS kind FROM persistence_requests r
+ WHERE r.worktree_id=$1::uuid AND r.source_incarnation=$2::uuid AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%'
+ AND r.completed_at > now() - ($3::int * interval '1 hour') AND r.slug IS NOT NULL
+ ORDER BY r.completed_at DESC LIMIT ${LANDING_RECEIPT_LIMIT}) w
+ ORDER BY w.slug, w.sequence DESC`, [binding.worktree_id, binding.incarnation, LANDING_WINDOW_HOURS], { timeoutMs: LANDING_PROBE_MS, signal: AbortSignal.timeout(LANDING_PROBE_MS + 500) });
+ } catch (error) {
+ return { status: 'unknown', reason: `receipt read did not answer within ${LANDING_PROBE_MS / 1000} s: ${error instanceof Error ? error.message.slice(0, 120) : String(error)}` };
+ }
+ const imports = receipts.filter(r => r.kind === 'managed_sync_import' && Number(r.age) >= after);
+ const base = { status: 'ok' as const, window_hours: LANDING_WINDOW_HOURS, after_seconds: after, checked: imports.length, complete: receipts.length < LANDING_RECEIPT_LIMIT };
+ if (!imports.length) return { ...base, gaps: 0, by_state: {}, pages: [] };
+ const slugs = imports.map(r => r.slug);
+ const live = new Set((await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND slug = ANY($2::text[])', [sourceId, slugs])).map(p => p.slug));
+ const disabled = await embeddingsDisabled(engine);
+ const states = ORDER.filter(state => !(disabled && state === 'pending'));
+ const rows = live.size ? await engine.listEmbeddingStateRows({ sourceIds: [sourceId], slugs: [...live], states, limit: live.size * states.length, purgeWindowHours: DELETED_PAGE_PURGE_WINDOW_HOURS }) : [];
+ const worst = new Map<string, EmbeddingState>();
+ for (const row of rows) { const prior = worst.get(row.slug); if (!prior || ORDER.indexOf(row.state) < ORDER.indexOf(prior)) worst.set(row.slug, row.state); }
+ const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };
+ const gaps: LandingGap[] = [];
+ for (const receipt of imports) {
+ const synced_at = new Date(receipt.completed_at).toISOString(), age_seconds = Math.round(Number(receipt.age));
+ if (!live.has(receipt.slug)) {
+ gaps.push({ slug: receipt.slug, state: 'page_missing', searchable: false, synced_at, age_seconds, fix: null,
+ why: `Sync committed an import of ${receipt.slug}, but no live page has that slug now and no later sync receipt deleted it; a write outside sync removed or renamed it. gbrain sources resolve-path ${sourceId} <file> names the file's state.` });
+ continue;
+ }
+ const state = worst.get(receipt.slug);
+ const gap = state ? GAP[state] : undefined;
+ if (!state || !gap) continue;
+ gaps.push({ slug: receipt.slug, state: gap, searchable: state === 'pending' ? 'keyword' : false, synced_at, age_seconds,
+ fix: embeddingStateFix(state, { sourceId, slug: receipt.slug, embeddingsEnabled: !disabled, verify }),
+ why: state === 'pending' ? `${receipt.slug} synced ${age_seconds} s ago and is found by keyword, but some of its chunks still have no vector, so vector search misses it.`
+ : state === 'chunkless_healable' ? `${receipt.slug} synced ${age_seconds} s ago but has no chunk rows, so search cannot read its body.`
+ : `${receipt.slug} synced ${age_seconds} s ago and is quarantined, so search hides it (doctor quarantined_pages names why).` });
+ }
+ const by_state: Partial<Record<LandingGapState, number>> = {};
+ for (const gap of gaps) by_state[gap.state] = (by_state[gap.state] ?? 0) + 1;
+ gaps.sort((a, b) => b.age_seconds - a.age_seconds);
+ return { ...base, gaps: gaps.length, by_state, pages: gaps.slice(0, opts.limit ?? LANDING_PAGE_LIMIT) };
+}
diff --git a/src/core/persistence/resolve-paths.ts b/src/core/persistence/resolve-paths.ts
new file mode 100644
index 0000000000..e8506c13d1
--- /dev/null
+++ b/src/core/persistence/resolve-paths.ts
@@ -0,0 +1,215 @@
+/**
+ * GBRA-150: what gbrain did with each file path of a source, by gbrain's own rules, so a harness (a landing check, an
+ * agent that just committed a page) never re-implements slugging or the skip lists and drifts from them.
+ *
+ * A landing check that copies gbrain rules drifts in exactly this way: a copy of the path→slug rule that only
+ * lowercased (gbrain also strips leading and trailing hyphens), a deleted mixed-case file whose lowercase twin still
+ * owns the slug (a delete must be checked by the page's origin, never by its slug), and a nested `index.md` that sync
+ * skips as folder scaffolding (a page that will never exist). Resolving through here answers each with its reason.
+ *
+ * Per path (relative to the source root, or to the Git top level when it starts with the source's subpath):
+ * - `slug`: the slug sync gives the file (`resolveSlugForPath` of its origin under the source's slug mode).
+ * - `state`, one of RESOLVE_PATH_STATES, read in this order:
+ * not_synced_yet the file at the checkout's HEAD differs from the last synced commit (added, changed or removed since);
+ * skipped sync never imports this path (`skipped.reason`: a metafile, an excluded or pruned path, the strategy);
+ * held a sync hold waits on the file (`hold.code`; `gbrain sync status` carries its fix);
+ * deleted the file is gone from the synced commit and no live page records it as its origin (a live page
+ * that only shares the slug, a case-folded twin, is named in `slug_owner` and is not a failure);
+ * stale_page the file is gone from the synced commit but its page is still live;
+ * page_deleted the file is committed but its page was deleted and sync keeps it deleted;
+ * slug_taken the file is committed with no page because another file's page owns its slug;
+ * missing the file is committed and eligible with no page, no hold and no skip: a real gap;
+ * searchable | pending_embedding | chunkless | keyword_only | quarantined | empty: the page's embedding state
+ * (`embedding-state.ts`); `pending_embedding` is searchable by keyword on a brain keyless by choice.
+ * - `fix`: the existing command that moves the path on (never run here), or null when nothing is owed.
+ * Read-only: Git object reads and bounded lookups on existing indexes; nothing is scheduled or written.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.ts';
+import { existsSync, realpathSync } from 'node:fs';
+import { opError } from '../ops/contract.ts';
+import { resolveSlugForPath, unsyncableReason, type SyncableReason } from '../sync.ts';
+import { parseMarkdownHead } from '../markdown.ts';
+import { embeddingsDisabled } from '../embedding-disabled.ts';
+import { embeddingStateFix, DELETED_PAGE_PURGE_WINDOW_HOURS, type EmbeddingState } from '../embedding-state.ts';
+import { loadSyncEligibility, syncGit } from './sync-discovery.ts';
+import { readBlobContents } from './sync-blobs.ts';
+import { readGitHold } from './sync-holds.ts';
+import { persistenceEnabledForHealth } from './ownership.ts';
+
+/** Paths one call resolves. */
+export const RESOLVE_PATHS_MAX = 200;
+
+export const RESOLVE_PATH_STATES = ['searchable', 'pending_embedding', 'chunkless', 'keyword_only', 'quarantined', 'empty', 'held', 'skipped', 'not_synced_yet',
+ 'missing', 'slug_taken', 'page_deleted', 'deleted', 'stale_page'] as const;
+export type ResolvePathState = typeof RESOLVE_PATH_STATES[number];
+
+export interface ResolvedPath {
+ path: string;
+ /** The page origin the file maps to (`pages.source_path`). */
+ source_path: string;
+ slug: string;
+ state: ResolvePathState;
+ /** Whether search can find the page now: by keyword and vector (`true`), by keyword only (`'keyword'`), or not at all. */
+ searchable: true | 'keyword' | false;
+ in_synced_commit: boolean;
+ at_head: boolean | null;
+ 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;
+ /** 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). */
+ frontmatter_slug: string | null;
+ why: string;
+ fix: Action | null;
+}
+
+export interface ResolvedPaths {
+ source_id: string;
+ mode: 'managed' | 'classic';
+ last_commit: string | null;
+ head: string | null;
+ embeddings_enabled: boolean;
+ paths: ResolvedPath[];
+}
+
+const DOCS = 'docs/guides/resolve-paths.md';
+const SEARCHABLE: Record<EmbeddingState, true | 'keyword' | false> = { embedded: true, pending: 'keyword', keyword_only: 'keyword', quarantined: false, empty: false,
+ deleted_page_chunks: false, chunkless_healable: false };
+const PAGE_STATE: Record<Exclude<EmbeddingState, 'deleted_page_chunks'>, ResolvePathState> = { embedded: 'searchable', pending: 'pending_embedding',
+ keyword_only: 'keyword_only', quarantined: 'quarantined', empty: 'empty', chunkless_healable: 'chunkless' };
+/** Worst first: a page with some chunks embedded and some pending reads as pending. */
+const PAGE_STATE_ORDER: EmbeddingState[] = ['quarantined', 'chunkless_healable', 'pending', 'keyword_only', 'empty', 'embedded'];
+
+interface TreeRow { path: string; oid: string; size: number }
+
+function lsTree(gitRoot: string, commit: string | null, paths: string[]): Map<string, TreeRow> {
+ const out = new Map<string, TreeRow>();
+ if (!commit || !paths.length) return out;
+ const raw = syncGit(gitRoot, ['--literal-pathspecs', 'ls-tree', '-l', '-z', commit, '--', ...paths]);
+ for (const row of raw.split('\0')) {
+ const tab = row.indexOf('\t');
+ if (tab < 0) continue;
+ const [, kind, oid, size] = row.slice(0, tab).split(/\s+/);
+ if (kind === 'blob') out.set(row.slice(tab + 1), { path: row.slice(tab + 1), oid: oid!, size: Number(size) });
+ }
+ return out;
+}
+
+function headCommit(gitRoot: string): string | null {
+ try { return syncGit(gitRoot, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']).trim() || null; } catch { return null; }
+}
+
+const readFix = (why: string, argv: string[], verify: string[]): Action => ({ argv, consent: [], actor: 'agent', requires_exclusive: false, why, verify: { argv: verify }, docs: DOCS });
+
+/** Resolves `paths` of one source; refuses more than RESOLVE_PATHS_MAX paths and a source without a local Git checkout. */
+export async function resolveSourcePaths(engine: BrainEngine, sourceId: string, paths: string[]): Promise<ResolvedPaths> {
+ if (!paths.length) throw opError('invalid_params', 'Pass at least one file path.', 'Name the repo-relative paths a commit changed, for example projects/acme-example/index.md.');
+ if (paths.length > RESOLVE_PATHS_MAX) throw opError('invalid_params', `At most ${RESOLVE_PATHS_MAX} paths per call (got ${paths.length}).`, 'Split the paths into batches.');
+ const [source] = await engine.executeRaw<{ local_path: string | null; last_commit: string | null; config: Record<string, unknown> | null; archived: boolean | null }>(
+ 'SELECT local_path, last_commit, config, archived FROM sources WHERE id=$1', [sourceId]);
+ const status = ['gbrain', 'sources', 'status', sourceId, '--json'];
+ if (!source || source.archived) throw opError('not_found', `Source ${sourceId} is not registered or is archived.`, 'List the registered sources and pass one of their ids.',
+ { fix: readFix('Lists the registered sources.', ['gbrain', 'sources', 'list', '--json'], ['gbrain', 'sources', 'list', '--json']) });
+ if (!source.local_path || !existsSync(source.local_path)) throw opError('not_found', `Source ${sourceId} has no Git checkout on this host, so its paths cannot be resolved here.`,
+ 'Run this on the host that holds the checkout (gbrain sources status names its path).', { fix: readFix('Shows where the source checkout lives.', status, status) });
+ const root = realpathSync(source.local_path);
+ const gitRoot = realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim());
+ const context = { root, gitRoot, sourceId, source: { last_commit: source.last_commit, config: source.config ?? {} } };
+ const { scope, eligible, sourcePath } = await loadSyncEligibility(engine, context);
+ const managed = await persistenceEnabledForHealth(engine).catch(() => false);
+ const [{ incarnation } = { incarnation: '' }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const disabled = await embeddingsDisabled(engine);
+ const head = headCommit(gitRoot);
+ const normalized = paths.map(input => {
+ const clean = input.replace(/\\/g, '/').replace(/^\.?\//, '');
+ const gitPath = !scope || clean.startsWith(`${scope}/`) ? clean : `${scope}/${clean}`;
+ return { input, gitPath, rootPath: scope ? gitPath.slice(scope.length + 1) : gitPath, origin: sourcePath(gitPath) };
+ });
+ const gitPaths = normalized.map(p => p.gitPath);
+ const synced = lsTree(gitRoot, source.last_commit, gitPaths);
+ const atHead = head ? lsTree(gitRoot, head, gitPaths) : null;
+ const heads = readBlobContents(gitRoot, [...synced.values()].filter(row => row.size <= 256 * 1024));
+ const origins = normalized.map(p => p.origin);
+ const pages = await engine.executeRaw<{ id: number; slug: string; source_path: string; deleted: boolean }>(
+ 'SELECT id, slug, source_path, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND source_path = ANY($2::text[]) ORDER BY deleted_at IS NOT NULL, id DESC', [sourceId, origins]);
+ const byOrigin = new Map<string, typeof pages[number]>();
+ for (const page of pages) if (!byOrigin.has(page.source_path)) byOrigin.set(page.source_path, page);
+ const slugs = [...new Set(origins.map(origin => resolveSlugForPath(origin)).filter(Boolean))];
+ const owners = new Map((await engine.executeRaw<{ slug: string; source_path: string | null }>(
+ 'SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND slug = ANY($2::text[])', [sourceId, slugs])).map(row => [row.slug, row]));
+ const liveSlugs = [...new Set([...byOrigin.values()].filter(page => !page.deleted).map(page => page.slug))];
+ const rows = liveSlugs.length ? await engine.listEmbeddingStateRows({ sourceIds: [sourceId], slugs: liveSlugs, states: PAGE_STATE_ORDER, limit: liveSlugs.length * PAGE_STATE_ORDER.length,
+ purgeWindowHours: DELETED_PAGE_PURGE_WINDOW_HOURS }) : [];
+ const embedding = new Map<string, { state: EmbeddingState; chunks: number; unembedded: number }>();
+ for (const row of rows) {
+ const prior = embedding.get(row.slug);
+ const chunks = (prior?.chunks ?? 0) + Number(row.chunks), unembedded = (prior?.unembedded ?? 0) + (row.state === 'pending' ? Number(row.chunks) : 0);
+ 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 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'];
+ const out: ResolvedPath[] = [];
+ for (const p of normalized) {
+ const slug = resolveSlugForPath(p.origin);
+ const committed = synced.get(p.gitPath);
+ const current = atHead ? atHead.get(p.gitPath) : undefined;
+ const page = byOrigin.get(p.origin) ?? null;
+ const owner = owners.get(slug);
+ const slugOwner = owner && owner.source_path !== p.origin ? { slug: owner.slug, source_path: owner.source_path } : null;
+ const content = committed ? heads.get(committed.oid) : undefined;
+ const frontmatter = content !== undefined ? parseMarkdownHead(content).frontmatter as Record<string, unknown> : {};
+ const declared = typeof frontmatter.slug === 'string' && frontmatter.slug !== slug ? frontmatter.slug : null;
+ const reason = unsyncableReason(p.gitPath, { strategy: (source.config?.strategy as 'markdown') ?? 'markdown' });
+ const skippedBy: SyncableReason | null = eligible(p.gitPath) ? null : reason ?? 'exclude-glob-hit';
+ const live = page && !page.deleted ? page : null;
+ 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'] };
+ 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;
+ if (atHead && (current?.oid ?? null) !== (committed?.oid ?? null)) {
+ push('not_synced_yet', live ? liveSearch : false, `The file at HEAD ${current ? (committed ? 'changed' : 'was added') : 'was removed'} after the last synced commit ${source.last_commit?.slice(0, 12) ?? '(none)'}; the next sync of the source takes it.`,
+ readFix('Syncs the checkout as it is.', sync, verify(p.input)));
+ continue;
+ }
+ if (skippedBy) {
+ const typed = skippedBy === 'metafile' && content !== undefined ? frontmatter.type != null || frontmatter.title != null : undefined;
+ push('skipped', live ? liveSearch : false, skippedBy === 'metafile'
+ ? `Sync never imports ${p.rootPath.split('/').pop()} files: they are folder scaffolding (SYNC_SKIP_FILES), so this path has no page by design${typed ? ', even though its frontmatter has a type: or title:' : ''}.`
+ : `Sync does not import this path (${skippedBy}); it has no page by design.`, null, { skipped: { reason: skippedBy, ...(typed !== undefined ? { typed_frontmatter: typed } : {}) } });
+ continue;
+ }
+ const hold = managed && committed && incarnation ? await readGitHold(engine, sourceId, incarnation, p.rootPath) : null;
+ if (hold) {
+ push('held', live ? liveSearch : false, `A sync hold (${hold.code}) waits on this file; ${live ? 'search shows the page as it was before the held change' : 'it has no page until the hold clears'}.`,
+ readFix('Lists each hold with its fix and whether it needs a person.', syncStatus, verify(p.input)), { hold: { code: hold.code, message: hold.message } });
+ continue;
+ }
+ if (!committed) {
+ if (live) push('stale_page', liveSearch, `The file is gone from the synced commit, but its page ${live.slug} is still live.`, readFix('Syncs the source so the delete lands.', sync, verify(p.input)));
+ else push('deleted', false, slugOwner ? `The file is gone and no live page records it as its origin. The slug ${slug} belongs to another file (${slugOwner.source_path ?? 'no recorded origin'}), which is not this file's page.`
+ : 'The file is gone and no live page records it as its origin.', null);
+ continue;
+ }
+ if (page?.deleted) { push('page_deleted', false, `The file is committed, but its page ${page.slug} was deleted and sync keeps it deleted. Restore the page, or delete or rename the file.`, null); continue; }
+ if (!live) {
+ if (slugOwner) { push('slug_taken', false, `The file is committed with no page: its slug ${slug} belongs to another file (${slugOwner.source_path ?? 'no recorded origin'}). Rename one of the two files.`, null); continue; }
+ push('missing', false, 'The file is committed and eligible, with no page, no hold and no skip. A re-screen imports it or records why it cannot.',
+ { ...readFix('Schedules committed files that have no page and no hold for a re-screen, then names the follow-up sync.', ['gbrain', 'sources', 'retry-held', sourceId, '--unindexed'], verify(p.input)),
+ then: readFix('Imports the scheduled files.', sync, verify(p.input)) });
+ 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.`
+ : state === 'pending_embedding' ? (disabled ? `Page ${live.slug} is searchable by keyword; embeddings are off on this brain, so its chunks carry no vector.` : `Page ${live.slug} is searchable by keyword; ${emb!.unembedded} chunk(s) still wait for a vector.`)
+ : `Page ${live.slug} is ${state.replace('_', ' ')}.`, disabled && state === 'pending_embedding' ? null : fix);
+ }
+ return { source_id: sourceId, mode: managed ? 'managed' : 'classic', last_commit: source.last_commit, head, embeddings_enabled: !disabled, paths: out };
+}
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 3ccf108172..9b5e3f16c5 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -155,10 +155,17 @@ export interface SyncStatus {
convergence_read: SyncStatusRead;
/** #6712 PR 4b: `sync.admission` (brain-wide), when it was set, and whether it is in effect for this source (sync-admission.ts). */
admission: import('./sync-admission.ts').SyncAdmissionStatus;
+ /**
+ * GBRA-150: pages this source synced more than its freshness target ago that search still cannot fully see (no vector,
+ * no chunks, quarantined, or gone), each with its reason and fix (landing-gaps.ts). A heavy read: only `--detail`
+ * runs it (`landing_read`); null when not read.
+ */
+ landing: import('./landing-gaps.ts').LandingGaps | null;
+ landing_read: SyncStatusRead;
}
export type SyncStatusState = 'synced' | 'resumable' | 'blocked';
/** Why the source is in its state; one closed list. */
-export const SYNC_STATUS_REASONS = ['nothing_pending', 'held_by_design', 'cursor_unfinished', 'live_job', 'last_error', 'holds_actionable', 'recovery_pending', 'request_pending',
+export const SYNC_STATUS_REASONS = ['nothing_pending', 'held_by_design', 'held_needs_human', 'cursor_unfinished', 'live_job', 'last_error', 'holds_actionable', 'recovery_pending', 'request_pending',
'status_unknown', 'needs_human', 'head_blocked', 'recovery_blocked',
// #6712 PR 4b (design v3.2 §9): the live pass's reasons.
'pass_unfinished', 'not_converged', 'settle_mismatch', 'deletes_withheld', 'selection_scoped', 'admission_paused', 'writeback_failed'] as const;
@@ -344,7 +351,7 @@ 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: !!human, oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0, pass: passState });
+ 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 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;
@@ -363,11 +370,19 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
convergence: passRow ? await passConvergence(engine, { sourceId, incarnation: source.incarnation, row: passRow, holds: records, admission, withheld })
: detail ? await (await import('./sync-pass.ts')).statusConvergence(engine, sourceId) : null,
convergence_read: passRow || detail ? { status: 'read' } : notRead('convergence shadow'),
- admission };
+ admission, landing: detail ? await (await import('./landing-gaps.ts')).readLandingGaps(engine, sourceId) : null,
+ landing_read: detail ? { status: 'read' } : notRead('landing-gap') };
}
-/** #6712 PR 2: the state and its reason, from what this read saw; a probe that did not answer never yields `synced`. */
-function statusState(s: { human: boolean; oldest: SyncStatus['oldest_blocker']; recovery: SyncStatus['recovery']; liveJob: boolean; unfinished: boolean; lastError: boolean;
+/**
+ * #6712 PR 2: the state and its reason, from what this read saw; a probe that did not answer never yields `synced`.
+ * GBRA-150: `blocked` means the source cannot advance without a person or an operator, the same meaning as a sync run's
+ * drain outcome and a sync job's `blocked` progress. A run that stopped on a decision (`human`: the last error needs a
+ * person) blocks; a file hold that waits on a person while the rest of the source keeps syncing (`heldForHuman`) does
+ * not: it reads `synced` with reason `held_needs_human` (or whatever else is pending), and `needs_human`/`next` still
+ * carry the decision.
+ */
+function statusState(s: { human: boolean; heldForHuman: boolean; oldest: SyncStatus['oldest_blocker']; recovery: SyncStatus['recovery']; liveJob: boolean; unfinished: boolean; lastError: boolean;
actionable: boolean; holds: boolean; pass?: [SyncStatusState, SyncStatusReason] | null }): [SyncStatusState, SyncStatusReason] {
if (s.human) return ['blocked', 'needs_human'];
if (s.recovery.status === 'ok' && s.recovery.first?.blocked) return ['blocked', 'recovery_blocked'];
@@ -382,7 +397,7 @@ function statusState(s: { human: boolean; oldest: SyncStatus['oldest_blocker'];
if (s.oldest.status === 'ok' && s.oldest.request) return ['resumable', 'request_pending'];
if (s.oldest.status !== 'ok' || s.recovery.status !== 'ok') return ['resumable', 'status_unknown'];
if (s.pass) return s.pass;
- return ['synced', s.holds ? 'held_by_design' : 'nothing_pending'];
+ return ['synced', s.heldForHuman ? 'held_needs_human' : s.holds ? 'held_by_design' : 'nothing_pending'];
}
/** #6712 PR 2: the source's oldest unfinished request, read through the drain's own bounded head probe. */
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 066d197824..2089291c41 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1876,7 +1876,7 @@ export class PGLiteEngine implements BrainEngine {
return chunksImpl.readEmbeddingStateCounts(scopedRead(this.engineSql), column, opts);
}
- async listEmbeddingStateRows(opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
+ async listEmbeddingStateRows(opts: { sourceIds?: string[]; slugs?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
return chunksImpl.listEmbeddingStateRows(scopedRead(this.engineSql), column, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index af1b260aba..bc1c8940e5 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1637,7 +1637,7 @@ export class PostgresEngine implements BrainEngine {
return this.withScopedReadTransaction(opts.sourceIds, undefined, tx => chunksImpl.readEmbeddingStateCounts(scopedRead(this.engineSqlOn(tx)), column, opts));
}
- async listEmbeddingStateRows(opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
+ async listEmbeddingStateRows(opts: { sourceIds?: string[]; slugs?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
return this.withScopedReadTransaction(opts.sourceIds, undefined, tx => chunksImpl.listEmbeddingStateRows(scopedRead(this.engineSqlOn(tx)), column, opts));
}
diff --git a/test/doctor-sync-landing-gaps.test.ts b/test/doctor-sync-landing-gaps.test.ts
new file mode 100644
index 0000000000..758d7f2739
--- /dev/null
+++ b/test/doctor-sync-landing-gaps.test.ts
@@ -0,0 +1,62 @@
+/**
+ * GBRA-150 doctor `sync_landing_gaps`: warns per source for pages a managed sync committed past the freshness target
+ * that search cannot fully see, with the first page's fix; ok when there are none; not applicable when managed
+ * persistence is off. It is a cheap incident check (runs before the full scans). Red on master: the check does not exist.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Check } from '../src/commands/doctor.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.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 { syncLandingGapsEntry } from '../src/commands/doctor/checks/landing-gaps.ts';
+import { CHEAP_INCIDENT_CHECKS } from '../src/commands/doctor/registry.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-doctor-landing-'));
+let engine: PGLiteEngine;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation about ${title}.\n`;
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+
+const run = async (sourceIds: string[]) => (await syncLandingGapsEntry.run({ engine, sourceIds } as unknown as DoctorContext) as Check[])[0]!;
+
+test('warns with the per-page reason and fix once a synced page outlives the target unembedded; ok under the target; a cheap incident check', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ expect(CHEAP_INCIDENT_CHECKS.has('sync_landing_gaps')).toBe(true);
+ await engine.setConfig('embedding_disabled', 'false');
+ const id = `dlg-${randomUUID().replace(/-/g, '').slice(0, 20)}`, repo = join(home, id);
+ mkdirSync(join(repo, 'notes'), { recursive: true }); git(repo, 'init', '-q');
+ writeFileSync(join(repo, 'notes/a.md'), note('A'));
+ git(repo, 'add', '-A'); git(repo, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'a');
+ 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, repo]);
+ await claimWorktree(engine, id, repo);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ writeFileSync(join(repo, 'notes/b.md'), note('B'));
+ git(repo, 'add', '-A'); git(repo, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'b');
+ await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+
+ await engine.setConfig('sync.freshness_target_seconds', '3600');
+ expect(await run([id])).toMatchObject({ name: 'sync_landing_gaps', status: 'ok' });
+ await engine.setConfig('sync.freshness_target_seconds', '0.001');
+ const warn = await run([id]);
+ expect(warn).toMatchObject({ name: 'sync_landing_gaps', status: 'warn', fix: { argv: ['gbrain', 'embed', '--stale', '--catch-up', '--source', id, '--yes'], consent: ['paid'] } });
+ expect(warn.message).toContain(`${id}: `);
+ expect(warn.message).toContain('notes/b [pending_embedding]');
+ await engine.setConfig('sync.freshness_target_seconds', '');
+}), 120_000);
+
+test('not applicable when managed persistence is off', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { expect(await run([])).toMatchObject({ name: 'sync_landing_gaps', status: 'ok', severity: 'info', readiness_state: 'not_applicable' }); }
+ finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+}), 60_000);
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 2405d4d5c9..840ffec29a 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -783,6 +783,29 @@
"name": "partial_embedding",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/resolve-paths.md#synced-but-not-searchable",
+ "sources": [
+ {
+ "after_seconds": 300,
+ "by_state": {},
+ "checked": 0,
+ "complete": true,
+ "gaps": 0,
+ "pages": [],
+ "source_id": "default",
+ "status": "ok",
+ "window_hours": 24
+ }
+ ]
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "Every page managed sync committed past its freshness target in the last 24 h is searchable.",
+ "name": "sync_landing_gaps",
+ "status": "ok"
+ },
{
"category": "ops",
"elapsed_ms": "<volatile>",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 1b2d41942f..b2c568543f 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -830,6 +830,29 @@
"name": "partial_embedding",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/resolve-paths.md#synced-but-not-searchable",
+ "sources": [
+ {
+ "after_seconds": 300,
+ "by_state": {},
+ "checked": 0,
+ "complete": true,
+ "gaps": 0,
+ "pages": [],
+ "source_id": "default",
+ "status": "ok",
+ "window_hours": 24
+ }
+ ]
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "Every page managed sync committed past its freshness target in the last 24 h is searchable.",
+ "name": "sync_landing_gaps",
+ "status": "ok"
+ },
{
"category": "ops",
"elapsed_ms": "<volatile>",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index d8e4e0317f..adec4caa31 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -301,6 +301,10 @@
"category": "brain",
"name": "partial_embedding"
},
+ {
+ "category": "brain",
+ "name": "sync_landing_gaps"
+ },
{
"category": "ops",
"name": "pgvector"
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 15d79af331..6bcb0a5602 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -388,6 +388,7 @@ test/shared-skills-writer-boundary.test.ts
test/source-lifecycle-dry-run-physical-root-6849.test.ts
test/source-retire-missing-checkout.test.ts
test/source-row-diagnostics.test.ts
+test/sources-resolve-path.test.ts
test/stats-health-source-scope.test.ts
test/sync-absent-from-worktree-s27.test.ts
test/sync-admission-6712.test.ts
@@ -408,6 +409,7 @@ test/sync-group-member-order.test.ts
test/sync-handler-drain-6706.test.ts
test/sync-import-provenance-disk.test.ts
test/sync-inexact-rename-6729.test.ts
+test/sync-landing-gaps.test.ts
test/sync-legacy-holds.test.ts
test/sync-legacy-retry-actions-6696.test.ts
test/sync-legacy-slug-adoption-6727.test.ts
diff --git a/test/sources-resolve-path.test.ts b/test/sources-resolve-path.test.ts
new file mode 100644
index 0000000000..da53151e22
--- /dev/null
+++ b/test/sources-resolve-path.test.ts
@@ -0,0 +1,148 @@
+/**
+ * GBRA-150: `sources_resolve_path` / `gbrain sources resolve-path` answers what gbrain did with each file path by gbrain's
+ * own rules. The three shapes a copied slug rule gets wrong: a path whose slug
+ * gbrain folds (trailing hyphen), a deleted file whose case-folded twin owns the slug (checked by origin, never slug), and a
+ * nested `index.md` sync skips as folder scaffolding. Plus the states a harness must tell apart: missing (a real gap),
+ * held, not synced yet. Red on master: the module and the operation do not exist there.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SyncOpts } from '../src/commands/sync.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 { resolveSourcePaths, RESOLVE_PATHS_MAX } from '../src/core/persistence/resolve-paths.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-resolve-path-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content'); return git(root, 'rev-parse', 'HEAD'); };
+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation about ${title}.\n`;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+async function unmanaged<T>(engine: BrainEngine, run: () => Promise<T>): Promise<T> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { return await run(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+}
+
+async function source(engine: BrainEngine, files: Record<string, string>) {
+ const id = `rslv-${randomUUID().replace(/-/g, '').slice(0, 20)}`, repo = join(home, id);
+ const write = (path: string, content: string) => { mkdirSync(join(repo, path, '..'), { recursive: true }); writeFileSync(join(repo, path), content); };
+ mkdirSync(repo, { recursive: true }); git(repo, 'init', '-q');
+ for (const [path, content] of Object.entries(files)) write(path, content);
+ commit(repo);
+ 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,$3::text::jsonb)', [id, repo, '{}']);
+ await claimWorktree(engine, id, repo);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const sync = (extra: Partial<SyncOpts> = {}) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, ...extra });
+ return { id, repo, write, sync, remove: (path: string) => unlinkSync(join(repo, path)),
+ resolve: (...paths: string[]) => resolveSourcePaths(engine, id, paths),
+ legacy: async (added: Record<string, string>) => {
+ for (const [path, content] of Object.entries(added)) write(path, content);
+ await unmanaged(engine, () => engine.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [id, commit(repo)]));
+ } };
+}
+
+async function each(run: (engine: BrainEngine) => Promise<void>) {
+ await withEnv(env, async () => {
+ for (const engine of engines) {
+ try { await run(engine); } finally { await disposePersistenceConsumer(engine); }
+ }
+ });
+}
+
+const HYPHEN = 'articles/outlet-example/a-headline-.md';
+const TWIN_LOWER = 'sources/meetings/2026-10-19-call-abcdefghxyz.md';
+const TWIN_MIXED = 'sources/meetings/2026-10-19-call-AbCdEfGhXyZ.md';
+const NESTED_INDEX = 'projects/acme-example/index.md';
+
+test('the slug gbrain folds a trailing hyphen into resolves to the indexed page, not a missing one', () => each(async engine => {
+ const s = await source(engine, { [HYPHEN]: note('Headline') });
+ await s.sync();
+ const [p] = (await s.resolve(HYPHEN)).paths;
+ expect(p).toMatchObject({ path: HYPHEN, slug: 'articles/outlet-example/a-headline', in_synced_commit: true, at_head: true, skipped: null, hold: null });
+ expect(p!.page).toMatchObject({ slug: 'articles/outlet-example/a-headline', deleted: false });
+ expect(p!.page!.chunks).toBeGreaterThan(0);
+ expect(['searchable', 'pending_embedding']).toContain(p!.state);
+ expect(p!.searchable).not.toBe(false);
+}), 240_000);
+
+test('a deleted mixed-case file whose lowercase twin owns the slug reads deleted, with the twin named, never as a failed delete', () => each(async engine => {
+ const s = await source(engine, { [TWIN_LOWER]: note('Call') });
+ await s.sync();
+ const result = await s.resolve(TWIN_MIXED, TWIN_LOWER);
+ const [mixed, lower] = result.paths;
+ expect(mixed).toMatchObject({ path: TWIN_MIXED, slug: 'sources/meetings/2026-10-19-call-abcdefghxyz', state: 'deleted', in_synced_commit: false, page: null, fix: null,
+ slug_owner: { slug: 'sources/meetings/2026-10-19-call-abcdefghxyz', source_path: TWIN_LOWER } });
+ expect(mixed!.why).toContain(TWIN_LOWER);
+ expect(lower).toMatchObject({ slug: mixed!.slug, slug_owner: null, in_synced_commit: true });
+ expect(lower!.page).not.toBeNull();
+}), 240_000);
+
+test('a file deleted for real reads deleted once synced and stale_page before; a nested index.md reads skipped as a metafile with its typed frontmatter flagged', () => each(async engine => {
+ const s = await source(engine, { 'notes/gone.md': note('Gone'), 'notes/keep.md': note('Keep'), [NESTED_INDEX]: '---\ntype: project\nstatus: active\n---\nA synthetic project hub.\n',
+ 'people/README.md': 'Folder notes.\n' });
+ await engine.setConfig('sync.metafile_pages', 'off');
+ try {
+ await s.sync();
+ s.remove('notes/gone.md');
+ await s.legacy({});
+ expect((await s.resolve('notes/gone.md')).paths[0]).toMatchObject({ state: 'stale_page', in_synced_commit: false });
+ await s.sync();
+ expect((await s.resolve('notes/gone.md')).paths[0]).toMatchObject({ state: 'deleted', page: { deleted: true }, slug_owner: null, fix: null });
+ const [index, readme] = (await s.resolve(NESTED_INDEX, 'people/README.md')).paths;
+ expect(index).toMatchObject({ state: 'skipped', searchable: false, page: null, skipped: { reason: 'metafile', typed_frontmatter: true }, fix: null });
+ expect(readme).toMatchObject({ state: 'skipped', skipped: { reason: 'metafile', typed_frontmatter: false } });
+ } finally { await engine.setConfig('sync.metafile_pages', ''); }
+}), 240_000);
+
+test('a committed eligible file with no page and no hold is missing (a real gap) with the re-screen fix; a held file and a not-yet-synced commit read as such', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A') });
+ await s.sync();
+ await s.legacy({ 'notes/lost.md': note('Lost') });
+ const [lost] = (await s.resolve('notes/lost.md')).paths;
+ expect(lost).toMatchObject({ state: 'missing', searchable: false, page: null, fix: { argv: ['gbrain', 'sources', 'retry-held', s.id, '--unindexed'],
+ then: { argv: ['gbrain', 'sync', '--source', s.id, '--no-pull'] } } });
+ s.write('investors/fund-a.md', '---\ntitle: Fund A\nslug: fund-a\n---\nA synthetic fund page.\n');
+ commit(s.repo);
+ const [early] = (await s.resolve('investors/fund-a.md')).paths;
+ expect(early).toMatchObject({ state: 'not_synced_yet', in_synced_commit: false, at_head: true, fix: { argv: ['gbrain', 'sync', '--source', s.id, '--no-pull'] } });
+ await s.sync();
+ const [held] = (await s.resolve('investors/fund-a.md')).paths;
+ expect(held).toMatchObject({ state: 'held', searchable: false, hold: { code: 'frontmatter_slug_conflict' }, frontmatter_slug: 'fund-a',
+ fix: { argv: ['gbrain', 'sync', 'status', '--source', s.id, '--json'] } });
+}), 240_000);
+
+test('the operation is read-scoped, takes paths relative to the source root, and refuses an empty or oversized batch', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A') });
+ await s.sync();
+ const op = operationsByName.sources_resolve_path!;
+ expect(op).toMatchObject({ scope: 'read', mutating: false });
+ const out = await op.handler({ engine, remote: false } as never, { id: s.id, paths: ['./notes/a.md'] }) as Awaited<ReturnType<typeof resolveSourcePaths>>;
+ expect(out.paths[0]).toMatchObject({ slug: 'notes/a', in_synced_commit: true });
+ 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);
diff --git a/test/sync-landing-gaps.test.ts b/test/sync-landing-gaps.test.ts
new file mode 100644
index 0000000000..bdb85d7cac
--- /dev/null
+++ b/test/sync-landing-gaps.test.ts
@@ -0,0 +1,99 @@
+/**
+ * GBRA-150: `gbrain sync status --detail` names, per page, what a managed sync committed more than the freshness target
+ * ago that search still cannot fully see, with the reason and the fix: chunks with no vector (found by keyword only), a
+ * page a write outside sync removed after it synced, and on a brain keyless by choice nothing for missing vectors. A plain
+ * status does not read it and says so. Red on master: there is no `landing` block.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+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 { readLandingGaps } from '../src/core/persistence/landing-gaps.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-landing-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content'); };
+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation about ${title}.\n`;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+async function managedSource(engine: BrainEngine) {
+ const id = `land-${randomUUID().replace(/-/g, '').slice(0, 20)}`, repo = join(home, id);
+ mkdirSync(join(repo, 'notes'), { recursive: true }); git(repo, 'init', '-q');
+ writeFileSync(join(repo, 'notes/a.md'), note('A'));
+ commit(repo);
+ 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, repo]);
+ await claimWorktree(engine, id, repo);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ await sync();
+ for (const name of ['b', 'c']) writeFileSync(join(repo, `notes/${name}.md`), note(name.toUpperCase()));
+ commit(repo);
+ await sync();
+ return { id, repo, sync };
+}
+
+const each = (run: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) { try { await run(engine); } finally { await disposePersistenceConsumer(engine); } }
+});
+
+test('pages synced past the target with no vectors are named per page with the paid catch-up fix; a page removed outside sync is page_missing; younger pages are not gaps', () => each(async engine => {
+ await engine.setConfig('embedding_disabled', 'false');
+ const s = await managedSource(engine);
+ expect((await readLandingGaps(engine, s.id, { afterSeconds: 3600 }))).toMatchObject({ status: 'ok', gaps: 0, checked: 0 });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { await engine.executeRaw('UPDATE pages SET deleted_at=now() WHERE source_id=$1 AND slug=$2', [s.id, 'notes/c']); }
+ finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ const gaps = await readLandingGaps(engine, s.id, { afterSeconds: 0 });
+ expect(gaps).toMatchObject({ status: 'ok', complete: true, after_seconds: 0 });
+ if (gaps.status !== 'ok') throw new Error('unreachable');
+ const bySlug = Object.fromEntries(gaps.pages.map(page => [page.slug, page]));
+ expect(bySlug['notes/b']).toMatchObject({ state: 'pending_embedding', searchable: 'keyword', fix: { argv: ['gbrain', 'embed', '--stale', '--catch-up', '--source', s.id, '--yes'], consent: ['paid'] } });
+ expect(bySlug['notes/c']).toMatchObject({ state: 'page_missing', searchable: false, fix: null });
+ expect(gaps.by_state).toMatchObject({ page_missing: 1 });
+ expect(gaps.by_state.pending_embedding).toBeGreaterThanOrEqual(2);
+
+ const detail = await readSyncStatus(engine, s.id);
+ expect(detail.landing_read).toEqual({ status: 'read' });
+ expect(detail.landing).toMatchObject({ status: 'ok', after_seconds: 300, gaps: 0 });
+ const plain = await readSyncStatus(engine, s.id, { detail: false });
+ expect(plain.landing).toBeNull();
+ expect(plain.landing_read).toMatchObject({ status: 'not_read', fix: { argv: ['gbrain', 'sync', 'status', '--source', s.id, '--detail', '--json'] } });
+}), 240_000);
+
+test('on a brain keyless by choice, chunks without vectors are not gaps (keyword search is the configured retrieval)', () => each(async engine => {
+ await engine.setConfig('embedding_disabled', 'true');
+ try {
+ const s = await managedSource(engine);
+ expect(await readLandingGaps(engine, s.id, { afterSeconds: 0 })).toMatchObject({ status: 'ok', gaps: 0, pages: [] });
+ } finally { await engine.setConfig('embedding_disabled', 'false'); }
+}), 240_000);
+
+test('a source with no managed binding is not applicable', () => each(async engine => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES('land-classic-example','land-classic-example','{}') ON CONFLICT DO NOTHING"); }
+ finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ expect(await readLandingGaps(engine, 'land-classic-example')).toEqual({ status: 'not_applicable', reason: 'no_managed_binding' });
+}), 60_000);
diff --git a/test/sync-status-blocked-definition.test.ts b/test/sync-status-blocked-definition.test.ts
new file mode 100644
index 0000000000..da77e15b63
--- /dev/null
+++ b/test/sync-status-blocked-definition.test.ts
@@ -0,0 +1,61 @@
+/**
+ * GBRA-150: one meaning of "blocked". A sync run (its drain outcome) and a sync job's `blocked` progress call a source
+ * blocked only when it cannot advance without a person or an operator. `gbrain sync status` used to say
+ * `blocked / needs_human` for one file hold that waits on a person while the run that recorded it ended `synced` and
+ * the rest of the source kept syncing, so a landing check reading jobs and an agent reading status disagreed. Now a
+ * person-waiting file hold reads `synced` with reason `held_needs_human`; `needs_human` and `next` still carry the
+ * decision; a run that stopped on a decision still reads blocked. Red on master: the state there is ['blocked', 'needs_human'].
+ */
+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 { syncStatusHeadline } from '../src/commands/sync/operator.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-blocked-def-'));
+let engine: BrainEngine;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };
+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;
+
+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('a file hold that waits on a person reads synced/held_needs_human, like the run that recorded it, with the decision still in needs_human and next', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const id = `bd-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ writeFileSync(join(root, 'a.md'), note('Alpha one.')); writeFileSync(join(root, 'd.md'), note('Delta one.'));
+ commit(root, 'fixture');
+ 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');
+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };
+ expect((await performManagedSync(engine, opts)).status).toBe('first_sync');
+ writeFileSync(join(root, 'a.md'), note('Alpha two.')); writeFileSync(join(root, 'd.md'), note('Delta two.'));
+ commit(root, 'version two');
+ await engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.putPage('d', { type: 'note', title: 'Example', compiled_truth: 'Delta, edited in the database.', timeline: '', frontmatter: {}, content_hash: 'd-db' }, { sourceId: id }), TEST_WRITE_ATTRIBUTION));
+ const run = await performManagedSync(engine, opts);
+ expect(run.status).toBe('synced');
+ expect(run.held?.map(hold => [hold.path, hold.code])).toEqual([['d.md', 'file_drift']]);
+ expect((await engine.getPage('a', { sourceId: id }))?.compiled_truth).toContain('Alpha two.');
+
+ const status = await readSyncStatus(engine, id);
+ 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.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.`);
+}), 240_000);