Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(sync): #6865 part 3 unindexed-file detector, maintenance phase, doctor unindexed_files, sources retry-held --unindexed
garrytan70d785721689
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex fb0e57961d..f652027234 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -15,12 +15,14 @@- `src/core/persistence/managed-mode.ts` — the one reader of the brain's persistence mode (#6482). `readManagedMode` / `readPersistenceBrain` accept exactly one `persistence_brain` row with a boolean `enabled` (optionally `FOR SHARE` / `FOR UPDATE`) and refuse anything else (`storage_error`, `detail: persistence_mode_unknown`, fix `gbrain sources writer status --probe --json`); only a well-formed `enabled: false` row selects the unmanaged path, so a missing, duplicated or malformed row can never route a write around the owner. Every non-test reader of the mode goes through it (`test/persistence-mode-reader-guard.test.ts` lists the few schema and admin-intent files allowed their own statement); `ownership.ts` re-exports it for callers that already import ownership.- `src/core/persistence/sync-slices.ts` — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a `--full` tree walk, one commit above the bound). `sliceEntries` cuts the whole resolved manifest in `(phase, code-unit path)` order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor `{ phase, after, head, target }` lives in `op_checkpoints` (`managed-sync-slice`, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves `last_commit` untouched until the last slice settles; `sync-discovery.ts` resumes an unfinished target pinned at its recorded commit.-- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision/liveness snapshots. #6517: `selectOriginClaimant` (sync-origin.ts) is the one origin rule, applied by the discovery census and by `assertSyncPageOrigin` at preparation and publication: a live page wins over tombstones, several live pages refuse `page_identity_changed` naming the soft-delete exit (`sharedOriginExit`), a single tombstone may be reused, several tombstones stay ambiguous. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032). `resolveManagedSyncContext` refuses `skipFailed` / `includeGitignored` on a managed source with `managed_sync_flag_refused` (`managed-sync-flags.ts`, `detail` = the flag, fix = the same `gbrain sync` argv without it), the one refusal jobs, MCP and the cycle reach; `gbrain sync` raises it at parse, before the legacy ledger acknowledgement and the cost gate, `--all` included (#6696).+- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision/liveness snapshots. #6517: `selectOriginClaimant` (sync-origin.ts) is the one origin rule, applied by the discovery census and by `assertSyncPageOrigin` at preparation and publication: a live page wins over tombstones, several live pages refuse `page_identity_changed` naming the soft-delete exit (`sharedOriginExit`), a single tombstone may be reused, several tombstones stay ambiguous. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032). `resolveManagedSyncContext` refuses `skipFailed` / `includeGitignored` on a managed source with `managed_sync_flag_refused` (`managed-sync-flags.ts`, `detail` = the flag, fix = the same `gbrain sync` argv without it), the one refusal jobs, MCP and the cycle reach; `gbrain sync` raises it at parse, before the legacy ledger acknowledgement and the cost gate, `--all` included (#6696). #6865: the per-path eligibility (scope, `sync.exclude`, `sync.include_hidden`, strategy, reserved skillpack paths) and the origin a path maps to under the slug mode come from one exported `loadSyncEligibility(engine, context, opts?, company?)`, which the unindexed-file detector shares.- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesQuery` (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows `delete_page` with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain repair file-drift --source <id> --slug <survivor> --prefer file` that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file `file_drift`, and that hold's fix leads with the same command), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). A purge of a shared-origin page refuses and names the soft delete. Tests: `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.- `src/core/persistence/drift-conflicts.ts` — the `source_changed` / `file_database_drift` conflict pile (#6643). `auditDriftConflicts` groups conflict receipts by slug over a bounded window of request sequences (default 100,000, at most 1,000,000), paginated by slug with a `complete` flag; it backs `gbrain sources reconcile <source> --audit --conflicts` (`reconcile-audit.ts`) and MCP `list_write_conflicts` (`ops/persistence.ts`). The window ends at the source's own newest request (current incarnation, the `(source_incarnation, sequence)` index; a cursor never reads past it), and a source the caller may not read returns before anything is computed; the MCP op refuses an out-of-grant `source_id` through `resolveRequestedScope`. Remote callers get database-derived fields only, with source grant, slug fence and visibility filtered in the aggregating SQL; `liveFileDrift` (the `prepareFileTarget` comparison; reason `canonical_file_missing` for a live page whose canonical file is gone, `file_missing` for any other `source_changed`) and `driftClass` (the `reconcile-additive.ts` verdict) run only for a trusted local caller on the canonical owner, and such a row carries the compared file `path`. `submitMaintenance` (`prepared-maintenance.ts`, `maintenanceDriftRefusal`) refuses a drifted page before admission, and `synthesize_concepts` skips a drifted concept before spend, recording it in `dream.concepts.drift_skips` (per-entry atomic updates, released when the sides agree). Tests: `test/maintenance-file-drift-6643.test.ts` (PGLite; Postgres via `test/e2e/maintenance-file-drift-6643-postgres.test.ts`).- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. Repeatable `--only`/`--skip` over the source-relative canonical file path (`src/core/repair/path-glob.ts` `matchesRepairPath`: a value without `*` is an exact path, as every kind's `--only`; with `*` it is a glob, file-drift only: `*` within a segment, `**` across) narrow the selection before the class check, the 1,000-page bound and any preview work (`not_selected` residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. `prepareDriftPage` builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. `--keep` is refused at parse in `src/commands/repair.ts` with the same command rewritten to `--prefer database`. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains and, on the owner host, echoes each declared `storage.keep_db` policy as `keep_db_policy` (prefixes, matched drifted pages among those checked live, `unchecked`, receipt cost from `keepDbReceiptCost`).- `src/core/ghost-pages.ts` — #6696 B5, the one ghost-page classifier: a ghost is a live page for which `liveFileDrift` returns reason `canonical_file_missing` on the source's canonical owner host (`prepareFileTarget` tags that refusal `detail: 'canonical_file_missing'`). `scanGhostSource` reads a source's live pages in id order (at most `GHOST_SCAN_LIMIT`), resolves each recorded canonical path exactly as `prepareFileTarget` does and stats it, skips `publishesDatabaseOnly` and legacy slugs, and runs the full check on at most `candidateLimit` candidates; it returns the ghosts, `inspected`, `file_backed` (the mass-delete valve's population), `truncated` and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is `not_applicable` (`not_owner_host`, or `not_applicable` with no binding); a missing root is `unknown` (`storage_unavailable`), a stat error, invalid gbrain.yml or inconclusive check `unknown` (`ambiguous_storage`). `ghostPageNow` re-checks one page (the repair's recheck); `readGhostPages(engine, { sourceIds?, sampleLimit? })` is the counts-and-samples summary for doctor and the read-scope health op. Tests: `test/ghost-pages-6696.test.ts`.- `src/core/repair/ghost-pages.ts` — `gbrain repair ghost-pages --source <id>` (#6696 B5): explicit-only, preview-bound, destructive consent (`GHOST_CONSENT_TEXT`: the 72 h purge fuse, the per-slug `gbrain restore <slug> --force` undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses `not_owner_host`, `ghost_storage_unknown`, `preview_changed` on an owner change, and `ghost_mass_delete_refused` (`massGhosts`: the sync valve, `MASS_RECONCILE_RATIO` over more than `MASS_RECONCILE_MIN_PAGES` file-backed pages, unless `massReconcileAllowed()`). Each page re-checks with `ghostPageNow`, then a managed brain submits one `managed_maintenance_retire_ghost_page` request (`prepareGhostPageRetirement`, dispatched from `prepared-maintenance.ts`: re-check, `delete_page` with `allowMissingFile`, refusal unless the prepared file target is the approved path with no bytes, so filesystem publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes `soft_deleted`, `file_restored` (asks for a new preview), `changed_since_preview`. Doctor `ghost_pages` (`src/commands/doctor/checks/ghost-pages.ts`, BRAIN, after `fence_integrity`) reports the count, samples and coverage with the preview as its fix, `ok` + info off the owner host, unknown on an unreadable checkout; `gbrain pages ghosts` (`src/commands/pages-ghosts.ts`) lists them read-only.+- `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/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/detached-pages.ts` — #6609 (D5) restore of a page whose recorded canonical file is gone on a brain without managed persistence. `assertRestoreOrigin` (called by `submitPageMutation` for `restore_page`, `publishesFile` = write-through on and a file target) refuses a restore that writes no file of a soft-deleted page whose `source_path` file `inSyncableTree` does not find (exists and is tracked or untracked-not-ignored, the set sync imports) with `source_changed` / detail `canonical_file_absent`, `retryable: false`, docs `storage-tiering.md#restoring-a-page-whose-file-is-gone` and an `ask_user` fix (`gbrain restore <slug> --source-id <id> --detach`, MCP `restore_page` `detach: true`); `detach: true` with nothing to detach refuses `invalid_params`. `detachRestoredPage` runs in the restore publication (from `classifyUnboundPage`) and clears `source_path`, stamping `pages.database_only_reason='detached'`; the page upsert in `engine-sql/pages.ts` clears that stamp when a sync writes a `source_path` again. `scanMissingRecordedFiles` (at most `MISSING_FILES_SCAN_LIMIT` live pages per source, `collectSyncableFiles` + `scannerSlugRootMode` path resolution) feeds doctor `missing_recorded_files`. Test: `test/restore-detach-6609.test.ts`.- `src/core/repair/keep-db-policy.ts` — the opt-in `storage.keep_db` policy (#6696 C7). `readKeepDbPolicy` reads a source's `keep_db` prefixes from the gbrain.yml of its canonical checkout, only when the given host owns the active binding. `runKeepDbPolicy` takes the slugs under the prefixes with a drift conflict receipt in the newest 100,000 request sequences plus the recorded concept drift skips, checks each live, prepares the `--prefer database` resolution (`prepareDriftPage`) and submits it through `runReconcileApply` under this installation's own CLI writer registration (never an inherited caller context), with a request id derived from the page revision and file bytes, so one drift is never submitted twice. A run submits at most `KEEP_DB_BATCH` (10) requests (`stopped: 'rate_limit'`) and asks its `admission` gate before each one (default: the repair core's 90% stop line on lifetime ids and receipt bytes, `stopped: 'capacity'`; the seam for background-producer backpressure). The persistence consumer (`consumer.ts`) runs it while idle at most every 10 minutes when started with `keepDbPolicy` (`service.ts`: serve, jobs and autopilot owners only; never with `requestsOnly`), and `stop()` awaits the pass. Tests: `test/file-drift-bulk-reconcile.test.ts` (PGLite; Postgres via `test/e2e/file-drift-bulk-reconcile-postgres.test.ts`).diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 4cda75dc24..c189cd6ab9 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -35,7 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/sources-lifecycle{,-args}.ts` — strict source mutation parsing before engine connection, with stable UUIDs and source incarnation preconditions. The private CLI administration envelope delegates to a live PGLite owner, retains request IDs after lost responses, and refuses preactivation administration or legacy hardening rather than changing worktrees through an uncoordinated writer. Managed purge names one archived source; the expiry worker separately coordinates each source. `test/persistence-source-cli.test.ts` executes real CLI subprocesses, checks replay after deletion/recreation, and verifies global page/lifecycle request identity.-- `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. Tests: `test/held-files-walkthrough.test.ts`, `test/managed-sync-preparation-stalled-holds.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-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/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 63f63671c7..b2e9b3a2b3 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -56,5 +56,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/fence-repair.ts` — the `fence_repair` maintenance phase: `runFenceRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, registry?, now? })` runs the `fences` repair kind (`src/core/repair/fences.ts`) once through the trusted `repairRunner` (apply; a preview on a dry run) over every active source, with no rule logic of its own: the kind plans from its census, skips sources this host may not write (an owner reason such as `host_mismatch`, `owner_unavailable` as the fallback) and the candidates a running sync still names (`sync_in_progress`; the rest of a syncing source is repaired), reads `fences.repair.llm` and the daily USD ledger, and re-plans on the next run. `fences.repair.enabled` false skips it without calling the kind (the summary names `gbrain config set fences.repair.enabled true`). The run's deadline is min(`FENCE_REPAIR_PHASE_BUDGET_MS` = 300 s, a third of the maintenance job's remaining time), 300 s without a job deadline; past it `runRepair` stops before the next item with `time_budget` (status ok, resumed by the next run). Details read the kind's `FenceRepairVerification`: `candidates`, `repaired`, `repaired_by_tier`, `held_by_reason`, `llm_usd`, `llm_usd_per_repair`, `oldest_hold_at`/`oldest_hold_age_hours`, `llm_enabled`, `scan_partial`, `time_budget_ms`, `stopped_reason`; the summary says when Tier 3 is off and how many fences need a manual edit (`fix`: `gbrain repair fences`). Any other stop reports `warn` with the kind's fix; an internal error reports `warn` with its code only (no message, which could carry fence content) unless the cycle is aborted. Brain-global, after `sync` in `ALL_PHASES`, classified `writes`. Test: `test/cycle-fence-repair.test.ts`.- `src/core/cycle/content-repair.ts` — the `content_repair` maintenance phase (#6377): `runContentRepairPhase(engine, { dryRun, signal?, deadlineAtMs?, kinds?, registry?, now? })` runs the content-repair lane (`src/core/repair/content-lane.ts`) minus `fences`, which `fence_repair` just ran (`contentRepairPhaseKinds()`; with `CONTENT_REPAIR_KINDS` holding only `fences` the phase runs nothing and reports `skipped` / `no_kinds`), through the shared trusted `repairRunner` over every active source: an apply, or a preview on a dry run. Gated on `fences.repair.enabled` (one switch for the whole lane; the summary names `gbrain config set fences.repair.enabled true` and `gbrain repair content`). Deadline min(`CONTENT_REPAIR_PHASE_BUDGET_MS` = 120 s, a third of the maintenance job's remaining time); past it the lane's kind stops `time_budget` (status ok, the next run resumes). Details: `kinds`, `candidates`, `repaired`, `held_by_reason` (each kind's `remaining`, else its per-item outcome reasons), `by_kind` (mode, counts by outcome, spend, oldest hold, stop), `llm_usd`, `oldest_hold_at` / `oldest_hold_age_hours`, `time_budget_ms`, `stopped_reason`; the summary counts holds that wait for a person (`merge_recommended`, `content_repair_needs_human`) and points at `gbrain sync status`. Any stop other than the time budget reports `warn` with the kind's fix; an internal error reports `warn` with its code only unless the cycle is aborted. Brain-global, right after `fence_repair` in `ALL_PHASES`, classified `writes`. Test: `test/cycle-content-repair.test.ts`.+- `src/core/cycle/unindexed-files.ts` — the `unindexed_files` maintenance phase (#6865, global, right after `content_repair` through the `REPAIR_LANE_PHASES` dispatch helper): on a managed brain, `runUnindexedFilesPhase(engine, { dryRun, signal?, deadlineAtMs?, now? })` runs one detector pass (`persistence/unindexed-files.ts`) per managed Git source this host owns, in id order, under one deadline of min(60 s, a third of the maintenance job's remaining time); a source the budget stops continues from its stored cursor next run. A real run stores each result and schedules the found files for a re-screen on the next sync (`requestGitHoldRetry`, at most 5,000 per run); a dry run reports without writing. Company-brain sources and sources this host does not own are skipped with a reason; an error on one source is `warn` and the others still run. Details are counts by source and code, never a path; it never runs on the per-sync path. Classified `no_coordinated_write` (`phase-table.ts`). Tests: `test/unindexed-files.test.ts`, `test/managed-phase-matrix.test.ts`.- `src/core/cycle/phase-table.ts` — `MANAGED_PHASE_TABLE` classifies every `ALL_PHASES` entry for managed brains as `writes` (publishes through the coordinator), `no_coordinated_write` (derived projections, side tables, audit-only) or `managed_skip`, each with its reason; `isManagedBrain` is what `runPhaseLint` uses to report issues without rewriting managed canonical files. The managed phase matrix test fails for an unclassified phase.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex f0a28c200c..7e895c5ab3 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -29,6 +29,7 @@| [Doctor residue (`timeline_history`, `derived_visibility`, `safe_index_pending`)](#doctor-residue) | preview `gbrain doctor --remediation-plan --json` or `gbrain repair`; then `gbrain repair <kind> --apply` | brain host, after the user agrees | `destructive` (rewrites derived rows) | `gbrain doctor --only timeline_history,derived_visibility,safe_index_pending --json` || Low health score | preview `gbrain doctor --remediation-plan --json`; then `gbrain doctor --remediate --yes --target-score 90 --max-usd 5` | agent, after the user agrees | `paid`; `destructive` with `--include-repairs` (approve with `--expect <plan_hash>` from the preview) | `gbrain doctor --json` || [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` |+| [A committed file has no page and no hold (doctor `unindexed_files`)](#unindexed-files) | `gbrain sources retry-held <id> --unindexed`, then the sync it prints | agent | none | `gbrain doctor --only unindexed_files --json` || [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` || A managed catch-up on a live checkout keeps dying (`revision_conflict`, `pinned_git_worktree_conflict`, `page_identity_changed`, `write ECONNABORTED`), or you want an agent to drive the recovery | `gbrain sync status --source <id> --json` (cursor, `committed_last_10m`, each hold and the last error with `class` / `safe_actions` / `needs_human`); when nothing moved and `needs_human` is false, `gbrain sync unblock --source <id> --apply`, then the sync it prints ([runbook](sync-unblock-runbook.md)) | agent; a person only when `needs_human` names a slug | none | `gbrain sync status --source <id> --json` || [Every write on a source stays pending; writer status shows a request `recovering` with `unexpected_file_bytes`](repair.md#stuck-recovery) | preview `gbrain repair stuck-recovery --source <id>` on the owner host, show the user the diff it prints, then run the choice they pick: `--keep prior` or `--keep disk` with `--apply --expect <hash> --yes`; never delete the file to unblock it | agent; the apply after the user picks a version | `destructive` (both versions are backed up first) | `gbrain sources writer status --source <id> --json` shows no recovering request |@@ -577,6 +578,22 @@ three-step check, and the skip codes. `gbrain doctor` reports it as the`auto_chronicle` check. To turn it off, run`gbrain config set auto_chronicle false`.+## Unindexed files++<a id="unindexed-files"></a>++A file an older gbrain refused before refusals became holds has no page and no+hold, and incremental sync never revisits it. The+maintenance phase `unindexed_files` finds such files per managed Git source+(bounded per run; an incomplete scan is never reported clean) and schedules+them for re-screen; doctor `unindexed_files` reads the result. Run+`gbrain sources retry-held <id> --unindexed` (`--dry-run` only lists), then+the sync it prints: each file imports or becomes a [hold](#held-files). `slug_taken` stays until one of the two files is renamed.+`metafile_skipped` (info only, never scheduled) lists titled `index.md`,+`README.md`, `schema.md`, `log.md` or `RESOLVER.md` files that sync skips on+purpose: rename one (`investors/fund-a/index.md` to+`investors/fund-a.md`), commit and sync.+## Sync freshness: no successful sync recorded<a id="sync-freshness-no-successful-sync"></a>diff --git a/llms-full.txt b/llms-full.txtindex 3da3812e41..d01757930f 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -6943,6 +6943,51 @@ and refuses `revision_conflict` if that page changed after the sync admittedit; the Git projection is the sync's own commit. Keep `frontmatter.id` as itis; a changed id is a different page.+Git reports a move that also changed the file as a similarity guess (`R087`),+and two template-shaped files moved in one commit can be paired the wrong way+round (#6729). So sync keeps the page identity across an inexact rename only+when the files confirm it: both carry the same `frontmatter.id` and no other+file or page shares it, or neither carries an id and they share a `slug:` line+or title that no other file in the source uses. The title is the one the page+row gets: the frontmatter `title:`, else the body's first `# Heading` (never+the filename), and the old side counts as the title the brain stores for that+page now. An exact move (`R100`) needs no signal. Any other pair is imported as a delete plus an add: the new file+starts a fresh page, and the old page keeps its facts, links and aliases on+its soft-deleted slug. The sync report prints each such pair, `gbrain sync+status --source <id> --json` lists it under `identity_downgrades`, doctor+`rename_identity_downgrades` names it, and the purge leaves the old page alone+until the pair gets a disposition; there is no time limit, so a pair can still+be repaired later. Restoring the old page settles it: run+`gbrain restore <old-slug> --source-id <id> --force` (it then lives beside the+new page; where the old file cannot be re-created the restore names+`--detach`). An unbound classic source on Postgres refuses page writes outside+its checkout, so the report and doctor do not offer the restore there. To move and rewrite a page so it keeps its identity, give it a+stable id or move, commit and sync first, then edit:++```yaml+---+id: roadmap-2026+title: Roadmap+---+```++Two rules decide by `frontmatter.id`. A pair Git reports as a rename (`R<n>`)+whose two files carry the same id, held by no other file in the range and no+other live page, is a rename. A new file and a deleted file that Git did not+pair are a rename only when they share such an id and also show continuity:+the same file name, the same title, or the same bytes. So a note moved to+another folder and rewritten keeps its page, while a new note that reuses a+deleted note's template id starts a fresh page, even when no live page holds+that id.++With `--working-tree`, the decision reads the files on disk and holds only for+the bytes it read. A renamed file edited before its page moves keeps nothing:+classic sync fails that file and the next sync decides again, and a managed+sync refuses `source_changed` and names+`gbrain sync --no-pull --retry-failed --working-tree --source <id>`. A managed sync refuses `page_identity_changed`+(`rename_identity_conflict`) when a file would take over a page whose+`frontmatter.id` differs from the file's own.+`put_page` at a new slug is not a rename. A content-only write cannot prove theold file is gone, so a create-only `put_page` whose `frontmatter.id` andcontent match an existing page resolves to that page (`duplicate`: the receipt@@ -10588,6 +10633,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| [Doctor residue (`timeline_history`, `derived_visibility`, `safe_index_pending`)](#doctor-residue) | preview `gbrain doctor --remediation-plan --json` or `gbrain repair`; then `gbrain repair <kind> --apply` | brain host, after the user agrees | `destructive` (rewrites derived rows) | `gbrain doctor --only timeline_history,derived_visibility,safe_index_pending --json` || Low health score | preview `gbrain doctor --remediation-plan --json`; then `gbrain doctor --remediate --yes --target-score 90 --max-usd 5` | agent, after the user agrees | `paid`; `destructive` with `--include-repairs` (approve with `--expect <plan_hash>` from the preview) | `gbrain doctor --json` || [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` |+| [A committed file has no page and no hold (doctor `unindexed_files`)](#unindexed-files) | `gbrain sources retry-held <id> --unindexed`, then the sync it prints | agent | none | `gbrain doctor --only unindexed_files --json` || [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` || A managed catch-up on a live checkout keeps dying (`revision_conflict`, `pinned_git_worktree_conflict`, `page_identity_changed`, `write ECONNABORTED`), or you want an agent to drive the recovery | `gbrain sync status --source <id> --json` (cursor, `committed_last_10m`, each hold and the last error with `class` / `safe_actions` / `needs_human`); when nothing moved and `needs_human` is false, `gbrain sync unblock --source <id> --apply`, then the sync it prints ([runbook](sync-unblock-runbook.md)) | agent; a person only when `needs_human` names a slug | none | `gbrain sync status --source <id> --json` || [Every write on a source stays pending; writer status shows a request `recovering` with `unexpected_file_bytes`](repair.md#stuck-recovery) | preview `gbrain repair stuck-recovery --source <id>` on the owner host, show the user the diff it prints, then run the choice they pick: `--keep prior` or `--keep disk` with `--apply --expect <hash> --yes`; never delete the file to unblock it | agent; the apply after the user picks a version | `destructive` (both versions are backed up first) | `gbrain sources writer status --source <id> --json` shows no recovering request |@@ -11136,6 +11182,22 @@ three-step check, and the skip codes. `gbrain doctor` reports it as the`auto_chronicle` check. To turn it off, run`gbrain config set auto_chronicle false`.+## Unindexed files++<a id="unindexed-files"></a>++A file an older gbrain refused before refusals became holds has no page and no+hold, and incremental sync never revisits it. The+maintenance phase `unindexed_files` finds such files per managed Git source+(bounded per run; an incomplete scan is never reported clean) and schedules+them for re-screen; doctor `unindexed_files` reads the result. Run+`gbrain sources retry-held <id> --unindexed` (`--dry-run` only lists), then+the sync it prints: each file imports or becomes a [hold](#held-files). `slug_taken` stays until one of the two files is renamed.+`metafile_skipped` (info only, never scheduled) lists titled `index.md`,+`README.md`, `schema.md`, `log.md` or `RESOLVER.md` files that sync skips on+purpose: rename one (`investors/fund-a/index.md` to+`investors/fund-a.md`), commit and sync.+## Sync freshness: no successful sync recorded<a id="sync-freshness-no-successful-sync"></a>diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 94726c59a5..24bd84cb5b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,7 +13,7 @@ src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/commands/serve-http.ts 932 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts)src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same textsrc/commands/sync.ts 546 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone)-src/core/cycle.ts 3317 ratchet +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence)+src/core/cycle.ts 3322 ratchet +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts)src/core/cycle/synthesize.ts 3224 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.tssrc/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog countsrc/core/engine.ts 2823 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts)diff --git a/src/commands/doctor/checks/unindexed-files.ts b/src/commands/doctor/checks/unindexed-files.tsnew file mode 100644index 0000000000..970d07692b--- /dev/null+++ b/src/commands/doctor/checks/unindexed-files.ts@@ -0,0 +1,125 @@+/**+ * #6865 `unindexed_files`: committed files of a managed Git source with no+ * page and no hold, so they are absent from search and nothing else reports+ * them (typically files an older gbrain refused before refusals became holds).+ * The check never scans: it reads the result the maintenance phase+ * `unindexed_files` or `gbrain sources retry-held <id> --unindexed` stored+ * (`judgeUnindexedFiles`), plus the re-screen schedule and, for scheduled+ * paths a sync already re-screened, whether each now has a page or a hold.+ *+ * ok when every source's result is complete, recent and nothing is missing;+ * warn when files are unindexed (fix: `retry-held --unindexed`, then the+ * follow-up sync) or scheduled and waiting for that sync (fix: the sync); info+ * when a source has no result, a stale one (older than 7 days) or an+ * incomplete one that found nothing so far. Files sync skips on purpose as+ * folder scaffolding (`index.md` and the other metafile names) that carry a+ * frontmatter `type:` or `title:` are named separately (`metafile_skipped`):+ * renaming one is the user's call, so they never make the check warn and are+ * the info finding only when nothing else is.+ */+import type { Check } from '../../doctor.ts';+import type { Action } from '../../../core/agent-output.ts';+import { agentFix, checkError, doctorVerify, infoCheck } from '../check-fix.ts';+import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntry } from '../context.ts';+import { managedPersistenceEnabled } from '../../../core/persistence/ownership.ts';+import { judgeUnindexedFiles, type UnindexedState } from '../../../core/persistence/unindexed-files.ts';+import { gitFollowUpSync } from '../../sources-retry-held.ts';++const DOCS = 'docs/guides/troubleshooting.md#unindexed-files';++const hours = (ms: number | null) => ms === null ? null : Math.round(ms / 3_600_000);++/** Scheduling the source's unindexed files, then the sync that re-screens them, then this check. */+async function scheduleFix(ctx: DoctorContext, sourceId: string, why: string): Promise<Action> {+ const sync = await gitFollowUpSync(connectedEngine(ctx), sourceId, []);+ return agentFix(['gbrain', 'sources', 'retry-held', sourceId, '--unindexed'], why, 'unindexed_files', { docs: DOCS,+ then: { argv: sync, consent: [], actor: 'agent', requires_exclusive: false, verify: doctorVerify('unindexed_files'), docs: DOCS,+ why: `The sync re-screens the scheduled files of ${sourceId}: each one that passes imports, each one that refuses is recorded as a hold that gbrain sources status ${sourceId} lists.` } });+}++/** One source's finding as a line: how many are missing or waiting, what the stored pass found, and the first paths. */+function sourceLine(state: UnindexedState): string {+ const record = state.record!;+ const codes = Object.entries(record.by_code).map(([code, n]) => `${code} ${n}`).join(', ');+ const found = `found ${record.unindexed} in ${record.scanned} file(s)${codes ? `: ${codes}` : ''}${record.slug_taken ? `; ${record.slug_taken} share a slug with another page` : ''}`;+ const samples = record.samples.slice(0, 5).map(sample => `${sample.path} [${sample.code}]`).join(', ');+ return `${state.source_id}: ${state.unscheduled + state.still_unindexed} unindexed, ${state.waiting} scheduled and waiting for a sync (${found}${record.complete ? '' : '; the scan is incomplete'}, `+ + `${hours(state.age_ms)} h ago${samples ? `; e.g. ${samples}` : ''})`;+}++/** The read-only note on scaffolding-named files sync skips on purpose, or '' when there are none. */+function metafileNote(states: UnindexedState[]): string {+ const found = states.filter(state => state.state !== 'missing' && state.record?.metafile_skipped);+ if (!found.length) return '';+ const count = found.reduce((n, state) => n + state.record!.metafile_skipped, 0);+ const samples = found.flatMap(state => state.record!.metafile_samples.slice(0, 3).map(path => `${state.source_id}:${path}`)).slice(0, 5).join(', ');+ return `${count} file(s) with a frontmatter type: or title: are named like folder scaffolding (index.md, README.md, schema.md, log.md, RESOLVER.md), which sync skips on purpose (e.g. ${samples}). `+ + 'To index one, rename it (for example investors/fund-a/index.md -> investors/fund-a.md), commit, then sync.';+}++async function runUnindexedFiles(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const engine = connectedEngine(ctx);+ if (!(await managedPersistenceEnabled(engine))) {+ checks.push(infoCheck('unindexed_files', 'Not applicable: managed persistence is off, so no managed Git source is checked for unindexed files.', 'not_applicable', undefined, { docs: DOCS }));+ return checks;+ }+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(`SELECT s.id, s.incarnation::text AS incarnation FROM sources s+ WHERE s.archived IS NOT TRUE AND (s.config->>'kind') IS NULL AND s.config->'company_brain' IS NULL+ 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]);+ if (!sources.length) {+ checks.push(infoCheck('unindexed_files', 'Not applicable: no managed Git source is bound to a checkout.', 'not_applicable', undefined, { docs: DOCS }));+ return checks;+ }+ const states = await judgeUnindexedFiles(engine, sources);+ const details = { docs: DOCS, sources: states.map(({ source_id, state, record, ...rest }) => !record || state === 'missing' ? { source_id, state }+ : { source_id, state, unscheduled: rest.unscheduled, waiting: rest.waiting, still_unindexed: rest.still_unindexed, age_hours: hours(rest.age_ms), complete: record.complete,+ scanned: record.scanned, unindexed: record.unindexed, slug_taken: record.slug_taken, by_code: record.by_code, samples: record.samples, target: record.target, computed_at: record.computed_at,+ metafile_skipped: record.metafile_skipped ?? 0, metafile_samples: record.metafile_samples ?? [] }) };+ const scaffolding = metafileNote(states);+ const unindexed = states.filter(state => state.state === 'unindexed');+ const waiting = states.filter(state => state.state === 'scheduled');+ if (unindexed.length || waiting.length) {+ const first = unindexed[0] ?? waiting[0]!;+ const fix = unindexed.length+ ? await scheduleFix(ctx, first.source_id, `Schedules the unindexed files of ${first.source_id} for a re-screen on its next sync and refreshes this check's stored result; nothing is imported or edited now.`)+ : agentFix(await gitFollowUpSync(engine, first.source_id, []), `The sync re-screens the ${first.waiting} scheduled file(s) of ${first.source_id}: each one that passes imports and each one that refuses is recorded as a hold.`,+ 'unindexed_files', { docs: DOCS });+ checks.push({ name: 'unindexed_files', status: 'warn', details, fix,+ message: `Committed files in managed Git sources have no page and no hold, so they are missing from search: ${[...unindexed, ...waiting].map(sourceLine).join('; ')}. `+ + 'Usually an older gbrain refused them before refusals became holds. Schedule them with gbrain sources retry-held <id> --unindexed, then run the sync it prints: '+ + 'each file then imports or is held with its reason (a file sharing a slug with another page stays out until one of them is renamed).'+ + (scaffolding ? ` ${scaffolding}` : '') });+ return checks;+ }+ const unknown = states.filter(state => state.state !== 'ok');+ if (unknown.length) {+ const first = unknown[0]!;+ const why = (state: UnindexedState) => state.state === 'missing' ? 'not computed yet' : state.state === 'stale' ? `computed ${hours(state.age_ms)} h ago, older than 7 days`+ : `incomplete: ${state.record!.scanned} file(s) checked so far, none missing`;+ checks.push(infoCheck('unindexed_files', `Unindexed files are not known for ${unknown.map(state => `${state.source_id} (${why(state)})`).join(', ')}. `+ + 'The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.'+ + (scaffolding ? ` ${scaffolding}` : ''),+ 'unknown', await scheduleFix(ctx, first.source_id, `Finds the committed files of ${first.source_id} with no page and no hold (bounded; it continues an incomplete scan), schedules them for a re-screen and stores the result this check reads.`), details));+ return checks;+ }+ if (scaffolding) {+ const first = states.find(state => state.record?.metafile_skipped)!;+ checks.push(infoCheck('unindexed_files', `Every other committed file of ${states.length} managed Git source(s) is indexed, held or excluded. ${scaffolding}`, 'degraded', {+ argv: await gitFollowUpSync(engine, first.source_id, []), consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify('unindexed_files'), docs: DOCS,+ why: 'Sync skips index.md and the other scaffolding names on purpose; a file renamed to an ordinary name is imported by the next sync.',+ user_message: `Sync skips files named index.md (and README.md, schema.md, log.md, RESOLVER.md) on purpose, as folder scaffolding, so ${first.record!.metafile_samples[0]} is not in search. `+ + 'To index such a file, rename it, for example investors/fund-a/index.md -> investors/fund-a.md, commit, then run this sync.' }, details));+ return checks;+ }+ checks.push({ name: 'unindexed_files', status: 'ok', details,+ message: `Every committed file of ${states.length} managed Git source(s) is indexed, held or excluded (${states.reduce((n, state) => n + (state.record?.scanned ?? 0), 0)} file(s) checked).` });+ } catch (error) {+ checks.push(checkError('unindexed_files', 'read the stored unindexed-file results', error, { details: { docs: DOCS } }));+ }+ return checks;+}++export const unindexedFilesEntry: DoctorEntry = { name: 'unindexed_files', emits: ['unindexed_files'], run: runUnindexedFiles };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex ce4153a688..0fa753c91a 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -118,6 +118,7 @@ import { fenceIntegrityEntry } from './checks/fence-integrity.ts';import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';import { ghostPagesEntry } from './checks/ghost-pages.ts';import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgrades.ts';+import { unindexedFilesEntry } from './checks/unindexed-files.ts';import { purgeParkedPagesEntry } from './checks/purge-parks.ts';import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';@@ -239,6 +240,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [renameIdentityDowngradesEntry,purgeParkedPagesEntry,missingRecordedFilesEntry,+ unindexedFilesEntry,syncConfigKeysEntry,fenceIntegrityEntry,searchModeEntry,diff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.tsindex 3a30f4f851..906ab07a49 100644--- a/src/commands/sources-retry-held.ts+++ b/src/commands/sources-retry-held.ts@@ -14,6 +14,12 @@* held. Most holds re-screen by themselves (changed or deleted file, newer* gbrain); the request covers causes outside the file (#6188: a prepare-time* fence hold whose stored-row conflict was fixed in the database).+ *+ * #6865: `--unindexed` runs the bounded unindexed-file detector for a Git+ * source (committed files with no page, no hold and no scheduled re-screen;+ * persistence/unindexed-files.ts), schedules those paths the same way, stores+ * the result doctor `unindexed_files` reads, and prints the follow-up sync.+ * `--dry-run` lists them and writes nothing.*/import type { BrainEngine } from '../core/engine.ts';import type { Action } from '../core/agent-output.ts';@@ -23,6 +29,8 @@ import { isConnectorSourceKind } from '../core/persistence/connector-identity.tsimport { fenceAutoRepairFor, holdRepairSteps, readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry, type GitHoldRecord } from '../core/persistence/sync-holds.ts';import { readManagedSyncBacklog } from '../core/persistence/sync-drain.ts';import type { FenceAutoRepair } from '../core/fence-repair/hold-fix.ts';+import { companyBrainProfile } from '../core/company-brain/policy.ts';+import { findUnindexedFiles, refreshUnindexedFiles, UNINDEXED_SCAN_BUDGET_MS, type UnindexedScan } from '../core/persistence/unindexed-files.ts';export interface RetryHeldReceipt {source_id: string;@@ -34,6 +42,8 @@ export interface RetryHeldReceipt {next_action: string;/** Git sources with held files: the one next step (the sync that re-screens them, or the scheduling command after a dry run). */fix?: Action;+ /** `--unindexed`: what the detector pass covered and found (counts only). */+ unindexed?: { complete: boolean; target: string | null; scanned: number; unindexed: number; slug_taken: number; already_scheduled: number; by_code: Record<string, number>; metafile_skipped: number };}interface Scheduled { items: Array<{ key: string; code: string; reason?: string; already: boolean }>; sync: string[]; fenceAuto?: FenceAutoRepair }@@ -57,7 +67,7 @@ async function scheduleConnectorItems(engine: BrainEngine, sourceId: string, inc* cursor's options when one exists, else the arguments a `preparation_stalled`* hold recorded, else the plain command.*/-async function gitFollowUpSync(engine: BrainEngine, sourceId: string, held: ReadonlyArray<Pick<GitHoldRecord, 'code' | 'meta'>>): Promise<string[]> {+export async function gitFollowUpSync(engine: BrainEngine, sourceId: string, held: ReadonlyArray<Pick<GitHoldRecord, 'code' | 'meta'>>): Promise<string[]> {if (!await managedBrain(engine)) return ['gbrain', 'sync', '--source', sourceId];const [backlog] = await readManagedSyncBacklog(engine, [sourceId]).catch(() => []);if (backlog) return ['gbrain', 'sync', ...backlog.resume_args];@@ -112,28 +122,76 @@ export async function retryHeld(engine: BrainEngine, sourceId: string, opts: { d: dryRun ? `${count} held item(s) would be scheduled; run: gbrain sources retry-held ${sourceId}`: `${count} held item(s) scheduled; none has run yet. Run them now with: ${sync}, then verify with: gbrain sources status ${sourceId}`;const items = scheduled.items.map(item => ({ key: item.key, code: item.code, ...(item.reason ? { reason: item.reason } : {}),- action: dryRun && !item.already ? 'would_retry' as const : 'retry_scheduled' as const,- next_action: dryRun ? 'Run the same command without --dry-run to schedule it.' : `${kind === 'git' ? 'Re-screened' : 'Re-attempted'} on the next ${sync}.` }));- return { source_id: sourceId, kind, dry_run: dryRun, scheduled: dryRun ? 0 : count, items, next_action: next, ...(step ? { fix: step.fix } : {}) };+ action: dryRun && !item.already ? 'would_retry' as const : 'retry_scheduled' as const }));+ return receiptOf({ source_id: sourceId, kind, dry_run: dryRun, scheduled: dryRun ? 0 : count, ...(step ? { fix: step.fix } : {}) }, items, next,+ dryRun ? 'Run the same command without --dry-run to schedule it.' : `${kind === 'git' ? 'Re-screened' : 'Re-attempted'} on the next ${sync}.`);+}++/** The receipt both modes print; every item shares one next step (schedule it after a dry run, else the run that re-attempts it). */+function receiptOf(base: Omit<RetryHeldReceipt, 'items' | 'next_action'>, items: Array<Omit<RetryHeldReceipt['items'][number], 'next_action'>>, next: string, itemNext: string): RetryHeldReceipt {+ return { ...base, items: items.map(item => ({ ...item, next_action: itemNext })), next_action: next };+}++const UNINDEXED_VERIFY = { argv: ['gbrain', 'doctor', '--only', 'unindexed_files', '--json'] };++/**+ * #6865 `--unindexed`: one bounded detector pass for a Git source. A real run schedules the found files for a re-screen+ * on the next sync and stores the result (continuing an incomplete stored scan); a dry run lists them and writes nothing.+ */+export async function retryUnindexed(engine: BrainEngine, sourceId: string, opts: { dryRun?: boolean; budgetMs?: number } = {}): Promise<RetryHeldReceipt> {+ const [source] = await engine.executeRaw<{ config: Record<string, unknown> }>('SELECT config FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);+ if (!source) throw new OperationError('not_found', `Source "${sourceId}" was not found.`, 'List sources with: gbrain sources list');+ if (source.config?.kind != null || companyBrainProfile(source.config ?? {})) throw new OperationError('invalid_params',+ `Source ${sourceId} is a ${source.config?.kind != null ? 'connector' : 'company-brain'} source; --unindexed applies to managed Git sources only.`,+ `Run gbrain sources retry-held ${sourceId} without --unindexed to re-attempt its held items.`);+ const dryRun = opts.dryRun === true;+ const deadlineAt = Date.now() + (opts.budgetMs ?? UNINDEXED_SCAN_BUDGET_MS);+ let scan: UnindexedScan, scheduled: string[] = [];+ if (dryRun) scan = await findUnindexedFiles(engine, sourceId, { deadlineAt });+ else ({ scan, scheduled } = await refreshUnindexedFiles(engine, sourceId, { deadlineAt }));+ const sync = await gitFollowUpSync(engine, sourceId, []);+ const again = ['gbrain', 'sources', 'retry-held', sourceId, '--unindexed'];+ const count = scan.files.length;+ const partial = scan.complete ? '' : ` The scan stopped at its time budget after ${scan.scanned} file(s); run ${again.join(' ')} again to continue.`;+ const waiting = count + scan.scheduled;+ const next = !count ? (scan.complete ? `No unindexed files for ${sourceId}.` : `No unindexed files found so far in ${sourceId}.`)+ + (scan.scheduled ? ` ${scan.scheduled} file(s) already wait for a re-screen; run: ${sync.join(' ')}.` : '') + partial+ : dryRun ? `${count} unindexed file(s) would be scheduled for a re-screen; run: ${again.join(' ')}.${partial}`+ : `${count} unindexed file(s) scheduled for a re-screen; none has run yet. Run it now with: ${sync.join(' ')}, then verify with: ${UNINDEXED_VERIFY.argv.join(' ')}. `+ + `Each file that passes imports; each one that refuses is held and listed by gbrain sources status ${sourceId}.${partial}`;+ const fix: Action | undefined = dryRun && count+ ? { argv: again, consent: [], actor: 'agent', requires_exclusive: false, verify: UNINDEXED_VERIFY, why: `Schedules ${count} unindexed file(s) of ${sourceId} for a re-screen on its next sync; nothing runs now.` }+ : !dryRun && waiting+ ? { argv: sync, consent: [], actor: 'agent', requires_exclusive: false, verify: UNINDEXED_VERIFY,+ why: `The sync re-screens the ${waiting} scheduled file(s): each one that passes imports and each one that refuses is recorded as a hold.` }+ : !scan.complete ? { argv: again, consent: [], actor: 'agent', requires_exclusive: false, verify: UNINDEXED_VERIFY, why: `Continues the scan of ${sourceId} where this pass stopped.` }+ : undefined;+ return receiptOf({ source_id: sourceId, kind: 'git', dry_run: dryRun, scheduled: scheduled.length, ...(fix ? { fix } : {}),+ unindexed: { complete: scan.complete, target: scan.target, scanned: scan.scanned, unindexed: scan.unindexed, slug_taken: scan.slug_taken, already_scheduled: scan.scheduled, by_code: scan.by_code, metafile_skipped: scan.metafile_skipped } },+ scan.files.map(file => ({ key: file.path, code: file.code, reason: 'unindexed', action: dryRun ? 'would_retry' as const : 'retry_scheduled' as const })), next,+ dryRun ? 'Run the same command without --dry-run to schedule it.' : `Re-screened on the next ${sync.join(' ')}.`);}export async function runRetryHeld(engine: BrainEngine, args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) {- console.log('Usage: gbrain sources retry-held <id> [--dry-run] [--json]\n\n'+ console.log('Usage: gbrain sources retry-held <id> [--unindexed] [--dry-run] [--json]\n\n'+ 'Re-attempt every held connector item of a Google or GitHub source on its next sync, or re-screen every\n'+ 'held file of a Git source on its next sync (most held files re-screen by themselves when they change).\n'+ 'Nothing runs now. A file that still refuses stays held: preview frontmatter holds with\n'+ "'gbrain repair frontmatter --source <id>' and fence holds (invalid_fence) with 'gbrain repair fences --source <id>';\n"+ "a preparation_stalled hold needs no file repair: inspect 'gbrain sources writer status --source <id> --json', then rerun the sync it prints.\n"+ + " --unindexed find committed files of a managed Git source with no page and no hold (files an older gbrain\n"+ + " refused before refusals became holds), schedule them for a re-screen on the next sync and refresh\n"+ + " doctor unindexed_files; the scan is bounded and the next run continues an incomplete one\n"+ ' --dry-run show what would be scheduled; change nothing\n --json print the receipt as JSON');return;}const json = args.includes('--json');const positional = args.filter(arg => !arg.startsWith('--'));- const unknown = args.find(arg => arg.startsWith('--') && arg !== '--dry-run' && arg !== '--json');- if (unknown) throw new OperationError('invalid_params', `Unknown option: ${unknown}.`, 'Usage: gbrain sources retry-held <id> [--dry-run] [--json]');- if (positional.length !== 1) throw new OperationError('invalid_params', 'Name one source.', 'Usage: gbrain sources retry-held <id> [--dry-run] [--json]');- const receipt = await retryHeld(engine, positional[0], { dryRun: args.includes('--dry-run') });+ const unknown = args.find(arg => arg.startsWith('--') && arg !== '--dry-run' && arg !== '--json' && arg !== '--unindexed');+ if (unknown) throw new OperationError('invalid_params', `Unknown option: ${unknown}.`, 'Usage: gbrain sources retry-held <id> [--unindexed] [--dry-run] [--json]');+ if (positional.length !== 1) throw new OperationError('invalid_params', 'Name one source.', 'Usage: gbrain sources retry-held <id> [--unindexed] [--dry-run] [--json]');+ const receipt = await (args.includes('--unindexed') ? retryUnindexed : retryHeld)(engine, positional[0], { dryRun: args.includes('--dry-run') });// #6712 PR 2: a soak intervention (soak-counters.ts).if (!args.includes('--dry-run')) await (await import('../core/persistence/soak-counters.ts')).recordSoakEvent(engine, 'retry_held');if (json) { console.log(JSON.stringify(receipt, null, 2)); return; }diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 14031dbdfe..eb65900146 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -2005,10 +2005,11 @@ Subcommands:Rejects a missing source or a path thatdoesn't exist. See gbrain doctor'sdefault_source_local_path check.- retry-held <id> [--dry-run] [--json]+ retry-held <id> [--unindexed] [--dry-run] [--json]Re-attempt a connector source's held items, or re-screen a Git source's held files, on its next sync.Runs nothing now. Most Git holds re-screen by themselves (file changed or deleted, newer gbrain); fixfrontmatter 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).shared-skills <id> on|off|status [--json]Opt a source out of (or back into) shared-skills adoption; status explains its effective policy.set-path <id> --clear Clear a connector source's (google, github)diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex ccf3a4c5e2..18e5dfa71c 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -48,7 +48,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -81,7 +81,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--is-inside-work-tree', '--json', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--full', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -111,7 +111,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--acknowledge-managed', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--diff', '--expect', '--force', '--force-break-lock', '--full', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -125,11 +125,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--prefer', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--timeout', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 7e129300bd..7cf3811601 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -71,6 +71,7 @@ export type CyclePhase =| 'lint' | 'backlinks' | 'sync' | 'synthesize' | 'extract' | 'extract_facts'| 'fence_repair' // #6188: repairs held and stored malformed facts/takes fences (global maintenance lane)| 'content_repair' // #6377: the rest of the content-repair lane (slug conflicts and later kinds), right after fence_repair+ | 'unindexed_files' // #6865: committed files with no page and no hold, scheduled for a re-screen on the next sync| 'resolve_symbol_edges'| 'patterns' | 'recompute_emotional_weight' | 'consolidate'// v0.36.1.0 Hindsight calibration wave:@@ -131,6 +132,8 @@ export const ALL_PHASES: CyclePhase[] = ['fence_repair',// #6377: the other content-repair kinds (src/core/repair/content-lane.ts) right after it, same reason.'content_repair',+ // #6865: after the repair lane, so its holds are settled; schedules unindexed files for the next sync.+ 'unindexed_files','synthesize','extract',// v0.32.2 — reconcile DB facts index from the `## Facts` fence on@@ -332,6 +335,7 @@ const NEEDS_LOCK_PHASES: ReadonlySet<CyclePhase> = new Set(['sync','fence_repair', // #6188: writes repaired fences through coordinated writes'content_repair', // #6377: writes content repairs through the same coordinated file-repair path+ 'unindexed_files', // #6865: writes the re-screen schedule and its stored result'synthesize','extract',// v0.32.2 — wipes + re-inserts facts per affected page.@@ -1880,13 +1884,14 @@ async function runPhaseOrphans(engine: BrainEngine, sourceId?: string): Promise</**- * #6188 / #6377: the two repair-lane phases that run right after `sync`, in this order. `runCycle` dispatches them- * through one loop; each phase module owns its gate, budget and report.+ * #6188 / #6377 / #6865: the bounded phases that run right after `sync`, in this order: the two repair-lane phases, then+ * the unindexed-file detector. `runCycle` dispatches them through one loop; each phase module owns its gate, budget and report.*/-const REPAIR_LANE_PHASES = ['fence_repair', 'content_repair'] as const;+const REPAIR_LANE_PHASES = ['fence_repair', 'content_repair', 'unindexed_files'] as const;async function runRepairLanePhase(phase: typeof REPAIR_LANE_PHASES[number], engine: BrainEngine | null,opts: { dryRun: boolean; signal?: AbortSignal; deadlineAtMs: number | null }): Promise<PhaseResult> {+ if (phase === 'unindexed_files') return (await import('./cycle/unindexed-files.ts')).runUnindexedFilesPhase(engine, opts);return phase === 'fence_repair' ? (await import('./cycle/fence-repair.ts')).runFenceRepairPhase(engine, opts) : (await import('./cycle/content-repair.ts')).runContentRepairPhase(engine, opts);}diff --git a/src/core/cycle/phase-scope.ts b/src/core/cycle/phase-scope.tsindex 79bc3bb60b..a42a77c6e9 100644--- a/src/core/cycle/phase-scope.ts+++ b/src/core/cycle/phase-scope.ts@@ -18,6 +18,7 @@ export const PHASE_SCOPE: Record<CyclePhase, PhaseScope> = {sync: 'source',fence_repair: 'global',content_repair: 'global',+ unindexed_files: 'global',synthesize: 'mixed',extract: 'source',extract_facts: 'source',diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.tsindex efffe705fc..4bc5823b1b 100644--- a/src/core/cycle/phase-table.ts+++ b/src/core/cycle/phase-table.ts@@ -25,6 +25,7 @@ export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>sync: { class: 'writes', reason: 'Managed sync admits each changed file through the coordinator.' },fence_repair: { class: 'writes', reason: 'Fence repairs publish through managed_file_repair (managed sources), a revision-bound put_page (database-only pages) or the legacy confined write, one coordinated write per repaired file or page.' },content_repair: { class: 'writes', reason: 'The other content-repair lane kinds publish through the same coordinated file-repair path as fence_repair, one write per repaired file; with no kind beyond fences registered the phase writes nothing.' },+ unindexed_files: { class: 'no_coordinated_write', reason: 'Finds committed files with no page and no hold and schedules each for a re-screen on the next sync (an op_checkpoints row); the sync, not this phase, imports or holds them.' },synthesize: { class: 'writes', reason: 'Dream synthesis publishes pages through the maintenance coordinator.' },extract: { class: 'writes', reason: 'Derived links and unrecorded timeline rows commit inside revision-bound coordinated transactions.' },extract_facts: { class: 'writes', reason: 'Fence facts are re-projected through coordinated maintenance writes.' },diff --git a/src/core/cycle/unindexed-files.ts b/src/core/cycle/unindexed-files.tsnew file mode 100644index 0000000000..e7fa26c59a--- /dev/null+++ b/src/core/cycle/unindexed-files.ts@@ -0,0 +1,107 @@+/**+ * `unindexed_files` cycle phase (#6865): one bounded pass of the unindexed-file+ * detector (src/core/persistence/unindexed-files.ts) over every managed Git+ * source this host owns, in the global maintenance lane right after+ * `content_repair`. It finds committed files with no page, no hold and no+ * scheduled re-screen (typically files an older gbrain refused before+ * refusals became holds), stores the result where doctor `unindexed_files`+ * reads it, and schedules the found paths for a re-screen on the next sync+ * (at most `UNINDEXED_SCHEDULE_CAP` per run), so each is imported or recorded+ * as a hold. Scheduling is the only write: no file or page changes here, and+ * the per-sync path never runs it.+ *+ * Deadline: min(60 s, a third of the maintenance job's remaining time),+ * shared by the sources in id order; a source the budget stops is continued+ * by the next run from its stored cursor. A dry run scans and reports without+ * scheduling or storing. The report is counts only, never a path. It never+ * fails the cycle: an error on a source reports `warn` and the others still run.+ */+import type { BrainEngine } from '../engine.ts';+import type { PhaseResult } from '../cycle.ts';+import type { SyncOpts } from '../../commands/sync.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { resolveManagedSyncContext } from '../persistence/sync-discovery.ts';+import { companyBrainProfile } from '../company-brain/policy.ts';+import { findUnindexedFiles, refreshUnindexedFiles, UNINDEXED_SCAN_BUDGET_MS, UNINDEXED_SCHEDULE_CAP, type UnindexedScan } from '../persistence/unindexed-files.ts';+import { isUncontainedPhaseError } from './phase-containment.ts';++export interface UnindexedFilesPhaseOpts {+ dryRun: boolean;+ signal?: AbortSignal;+ /** The enclosing maintenance job's absolute deadline (epoch ms); null or unset for a direct `gbrain dream`. */+ deadlineAtMs?: number | null;+ now?: () => number;+}++const errorCode = (error: unknown) => { const code = (error as { code?: unknown } | null)?.code; return typeof code === 'string' ? code : 'internal'; };++export async function runUnindexedFilesPhase(engine: BrainEngine | null, opts: UnindexedFilesPhaseOpts): Promise<PhaseResult> {+ const base = { phase: 'unindexed_files' as const, duration_ms: 0 };+ if (!engine) return { ...base, status: 'skipped', summary: 'no database connected', details: { reason: 'no_database' } };+ if (!(await managedPersistenceEnabled(engine))) {+ return { ...base, status: 'skipped', summary: 'managed persistence is off, so there is no managed Git source to check for unindexed files', details: { reason: 'not_managed' } };+ }+ const now = opts.now ?? Date.now;+ const start = now();+ const timeBudgetMs = opts.deadlineAtMs == null ? UNINDEXED_SCAN_BUDGET_MS : Math.min(UNINDEXED_SCAN_BUDGET_MS, Math.floor((opts.deadlineAtMs - start) / 3));+ if (timeBudgetMs <= 0) return { ...base, status: 'skipped', summary: 'no maintenance-job time left to look for unindexed files; the next run continues', details: { reason: 'deadline' } };+ const deadlineAt = start + timeBudgetMs;+ const rows = await engine.executeRaw<{ id: string; config: Record<string, unknown> | null }>(+ "SELECT id, config FROM sources WHERE archived IS NOT TRUE AND local_path IS NOT NULL AND (config->>'kind') IS NULL ORDER BY id");+ const sources: Array<{ source_id: string; complete: boolean; scanned: number; unindexed: number; slug_taken: number; scheduled_now: number; already_scheduled: number;+ metafile_skipped: number; by_code: Record<string, number> }> = [];+ const skipped: Array<{ source_id: string; reason: string }> = [];+ const errors: Array<{ source_id: string; code: string }> = [];+ let room = UNINDEXED_SCHEDULE_CAP;+ for (const row of rows) {+ if (now() >= deadlineAt) { skipped.push({ source_id: row.id, reason: 'deadline' }); continue; }+ try {+ if (companyBrainProfile(row.config ?? {})) { skipped.push({ source_id: row.id, reason: 'company_source' }); continue; }+ const context = await resolveManagedSyncContext(engine, { sourceId: row.id, noPull: true } as SyncOpts).catch((error: unknown) => {+ if (['owner_unavailable', 'source_changed', 'writer_coordinator_required'].includes(errorCode(error))) return errorCode(error);+ throw error;+ });+ if (typeof context === 'string') { skipped.push({ source_id: row.id, reason: context }); continue; }+ let scan: UnindexedScan, scheduledNow = 0;+ if (opts.dryRun) scan = await findUnindexedFiles(engine, row.id, { context, deadlineAt, now });+ else {+ const refresh = await refreshUnindexedFiles(engine, row.id, { context, deadlineAt, now, keep: room });+ scan = refresh.scan; scheduledNow = refresh.scheduled.length; room -= scheduledNow;+ }+ sources.push({ source_id: row.id, complete: scan.complete, scanned: scan.scanned, unindexed: scan.unindexed, slug_taken: scan.slug_taken,+ scheduled_now: scheduledNow, already_scheduled: scan.scheduled, metafile_skipped: scan.metafile_skipped, by_code: scan.by_code });+ } catch (error) {+ if (isUncontainedPhaseError(error, opts.signal)) throw error;+ errors.push({ source_id: row.id, code: errorCode(error) });+ }+ }+ const total = (key: 'scanned' | 'unindexed' | 'slug_taken' | 'scheduled_now' | 'already_scheduled' | 'metafile_skipped') => sources.reduce((n, source) => n + source[key], 0);+ const byCode: Record<string, number> = {};+ for (const source of sources) for (const [code, n] of Object.entries(source.by_code)) byCode[code] = (byCode[code] ?? 0) + n;+ const incomplete = sources.filter(source => !source.complete).length;+ const codes = Object.entries(byCode).map(([code, n]) => `${code} ${n}`).join(', ');+ const parts = [+ `${opts.dryRun ? 'dry run: ' : ''}checked ${total('scanned')} committed file(s) in ${sources.length} managed Git source(s)`,+ total('unindexed') ? `${total('unindexed')} had no page and no hold (${codes}${total('slug_taken') ? `; ${total('slug_taken')} share a slug with another page` : ''})` : 'none was missing from the index',+ opts.dryRun ? (total('unindexed') ? 'nothing was scheduled' : '') : total('scheduled_now') ? `${total('scheduled_now')} scheduled for a re-screen on the next sync` : '',+ total('already_scheduled') ? `${total('already_scheduled')} already wait for a re-screen` : '',+ total('metafile_skipped') ? `${total('metafile_skipped')} titled file(s) are named like folder scaffolding (index.md and the like), which sync skips on purpose; renaming one is the user's call` : '',+ ].filter(Boolean);+ const notes = [+ incomplete ? `${incomplete} source(s) stopped at the phase time budget (${Math.round(timeBudgetMs / 1000)} s); the next maintenance run continues where they stopped.` : '',+ skipped.length ? `${skipped.length} source(s) skipped (${[...new Set(skipped.map(s => s.reason))].join(', ')}).` : '',+ errors.length ? `${errors.length} source(s) could not be checked (${[...new Set(errors.map(e => e.code))].join(', ')}); gbrain doctor --only unindexed_files --json shows each source's state.` : '',+ ].filter(Boolean);+ return {+ ...base,+ status: errors.length ? 'warn' : 'ok',+ summary: [`${parts.join('; ')}.`, ...notes].join(' '),+ details: {+ mode: opts.dryRun ? 'dry_run' : 'apply', sources: sources.map(({ by_code: _codes, ...source }) => source), scanned: total('scanned'), unindexed: total('unindexed'),+ slug_taken: total('slug_taken'), scheduled_now: total('scheduled_now'), already_scheduled: total('already_scheduled'), metafile_skipped: total('metafile_skipped'), by_code: byCode,+ complete: incomplete === 0, time_budget_ms: timeBudgetMs, skipped, errors,+ ...(errors.length ? { fix: { argv: ['gbrain', 'doctor', '--only', 'unindexed_files', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows each managed Git source\'s unindexed-file state and the next step; read-only.' } } : {}),+ },+ };+}diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex b76e6c7801..e54a5f9c0e 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -202,6 +202,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['rename_identity_downgrades',// #6609: live pages of a classic checkout whose recorded file a full sync would not find (doctor/checks/missing-recorded-files.ts).'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','unified_multimodal_coverage','unverified_extractions','voice_gate_health',diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex e3a26505f6..36a8be0bce 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -214,6 +214,32 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncOwhy: 'The sync command routes a connector source to its own coordinator.' } });return { binding, root, gitRoot, sourceId, incarnation: source.incarnation, source };}+/** #6865: which Git paths of one managed source sync admits, and the page origin each maps to under the source's slug mode. */+export interface SyncEligibility { scope: string; slugMode: 'git-root' | 'source-root'; nativeRoot: string; nativeGitRoot: string;+ eligible: (gitPath: string) => boolean; sourcePath: (gitPath: string) => string; }+/**+ * #6865: the eligibility rules managed discovery applies to a Git path (the source's scope, `sync.exclude`, `sync.include_hidden`,+ * the strategy and reserved skillpack paths) and the origin a path maps to under the slug mode. Discovery and the unindexed-file+ * detector share this one definition, so a file the detector reports is a file a sync would screen.+ */+export async function loadSyncEligibility(engine: BrainEngine, context: Pick<ManagedSyncContext, 'root' | 'gitRoot' | 'sourceId' | 'source'>,+ opts: Pick<SyncOpts, 'strategy' | 'exclude' | 'includeHidden' | 'srcSubpath'> = {}, company = !!currentCompanyBrainSync(context.sourceId)): Promise<SyncEligibility> {+ const strategy = opts.strategy ?? context.source.config?.strategy ?? 'markdown';+ const nativeRoot = realpathSync.native(context.root), nativeGitRoot = realpathSync.native(context.gitRoot);+ const scope = relative(nativeGitRoot, nativeRoot).split(sep).join('/');+ const probe = resolveSlugForPath(join(scope, 'x.md'));+ const slugMode = company ? 'source-root' : scope ? await resolveSlugRootMode(engine, { sourceId: context.sourceId, explicitGitRoot: opts.srcSubpath !== undefined,+ slugPrefix: probe.slice(0, -2), dryRun: true }) : 'git-root';+ const sourcePath = (path: string) => slugMode === 'source-root' && scope ? path.slice(scope.length + 1) : path;+ const exclude = await syncExcludePatterns(engine, opts.exclude);+ const includeHidden = [...new Set([...(opts.includeHidden ?? []), ...(await engine.getConfig('sync.include_hidden') ?? '')+ .split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))];+ // Reserved skillpack paths belong to the shared skill publisher; the managed importer always refuses them.+ const eligible = (path: string) => (!scope || path.startsWith(`${scope}/`)) &&+ !matchesAnyGlob(scope ? path.slice(scope.length + 1) : path, exclude) && !isReservedSkillBundlePath(sourcePath(path)) &&+ isSyncable(path, { strategy: strategy as 'markdown', includeHidden });+ return { scope, slugMode, nativeRoot, nativeGitRoot, eligible, sourcePath };+}/** The cursor bound: entries and serialized bytes one frozen manifest may hold. */let cursorBound = { entries: 100_000, bytes: 16 * 1024 ** 2 };/** Test seam: a smaller cursor bound (call with no argument to restore the default). */@@ -281,21 +307,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst resume = await resumableSliceStage(engine, opts, gitRoot, sourceId, incarnation);if (resume) return discoverManagedSync(engine, opts, context ?? { binding, root, gitRoot, sourceId, incarnation, source }, resume, walk);}- const strategy = opts.strategy ?? source.config?.strategy ?? 'markdown';- const nativeRoot = realpathSync.native(root), nativeGitRoot = realpathSync.native(gitRoot);- const scope = relative(nativeGitRoot, nativeRoot).split(sep).join('/');- const probe = resolveSlugForPath(join(scope, 'x.md'));- const slugMode = company ? 'source-root' : scope ? await resolveSlugRootMode(engine, { sourceId, explicitGitRoot: opts.srcSubpath !== undefined,- slugPrefix: probe.slice(0, -2), dryRun: true }) : 'git-root';- const sourcePath = (path: string) => slugMode === 'source-root' && scope ? path.slice(scope.length + 1) : path;+ const { scope, slugMode, nativeRoot, nativeGitRoot, eligible, sourcePath } = await loadSyncEligibility(engine, { root, gitRoot, sourceId, source }, opts, !!company);const originScope: SyncOriginScope = { sourceId, root, scope, slugMode };- const exclude = await syncExcludePatterns(engine, opts.exclude);- const includeHidden = [...new Set([...(opts.includeHidden ?? []), ...(await engine.getConfig('sync.include_hidden') ?? '')- .split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))];- // Reserved skillpack paths belong to the shared skill publisher; the managed importer always refuses them.- const eligible = (path: string) => (!scope || path.startsWith(`${scope}/`)) &&- !matchesAnyGlob(scope ? path.slice(scope.length + 1) : path, exclude) && !isReservedSkillBundlePath(sourcePath(path)) &&- isSyncable(path, { strategy: strategy as 'markdown', includeHidden });const target = stage?.target ?? company?.plan.revision?.commit ?? syncGit(gitRoot, ['rev-parse', 'HEAD']).trim();const head = stage?.head ?? target;const slicing = stage?.slice ?? null;diff --git a/src/core/persistence/unindexed-files.ts b/src/core/persistence/unindexed-files.tsnew file mode 100644index 0000000000..6cd69316ce--- /dev/null+++ b/src/core/persistence/unindexed-files.ts@@ -0,0 +1,323 @@+/**+ * #6865: files of a managed Git source that are committed, eligible for sync,+ * and neither indexed nor held. An older gbrain refused some files before+ * refusals became holds (a stray frontmatter `slug:` line, unreadable YAML);+ * incremental discovery never visits an unchanged file with no page and no+ * hold, so those files stay absent from search and nothing reports them.+ *+ * `findUnindexedFiles` streams the tree of the source's last synced commit+ * (`git ls-tree -r`, the committed set discovery walks), filters it through+ * discovery's own eligibility (`loadSyncEligibility`) and compares in+ * source-path space: a file counts as indexed when a live page records its+ * origin, held when it has a sync hold, and `scheduled` when a re-screen is+ * already requested for it. A file whose path slug belongs to a live page with+ * another or no origin is not indexed either; it is counted as `slug_taken`.+ * Lookups run in batches on the existing indexes, never over every page at+ * once. A file sync skips on purpose as folder scaffolding (`index.md`,+ * `README.md` and the other `isSyncMetafile` names) that would otherwise be eligible+ * and whose frontmatter has a `type:` or `title:` is counted separately as+ * `metafile_skipped`: read-only, never scheduled, because sync skips it again.+ * Each found file is screened read-only (the import screen's codes, or+ * `clean`) up to a cap. A time or count budget stops the scan with+ * `complete: false` and a cursor (the last Git path examined, in tree order),+ * so the next pass resumes there and every path is eventually covered; an+ * incomplete scan is never reported clean.+ *+ * `refreshUnindexedFiles` runs one bounded pass, schedules the found paths+ * for a re-screen on the next sync (`requestGitHoldRetry`, at most+ * `UNINDEXED_SCHEDULE_CAP` per pass; a scheduling write, never a content+ * write) and stores the result per source in `op_checkpoints` (op+ * `unindexed-files`), where doctor `unindexed_files` reads it through+ * `judgeUnindexedFiles`. An incomplete stored result is continued and+ * accumulated by the next pass.+ */+import type { BrainEngine } from '../engine.ts';+import type { SyncOpts } from '../../commands/sync.ts';+import { spawn } from '../spawn.ts';+import { gitChildEnv } from '../git-env.ts';+import { isSyncMetafile, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';+import { screenImportContent } from '../import-screen.ts';+import { parseMarkdownHead } from '../markdown.ts';+import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';+import { loadSyncEligibility, resolveManagedSyncContext, syncExcludePatterns, type ManagedSyncContext } from './sync-discovery.ts';+import { heldGitPaths, readGitHoldRetryPaths, requestGitHoldRetry } from './sync-holds.ts';+import { readBlobContents, type TreeBlob } from './sync-blobs.ts';+import { isWindowsColonTarget } from './native-file-target.ts';++export const UNINDEXED_FILES_OP = 'unindexed-files';+/** Paths one pass schedules for a re-screen, and the most scheduled paths a stored result names. */+export const UNINDEXED_SCHEDULE_CAP = 5_000;+/** Found files one pass screens; the rest count as `unscreened`. */+export const UNINDEXED_SCREEN_LIMIT = 2_000;+export const UNINDEXED_SAMPLE_LIMIT = 20;+/** The time one live pass (the maintenance phase, `sources retry-held --unindexed`) spends at most. */+export const UNINDEXED_SCAN_BUDGET_MS = 60_000;+/** A stored result older than this is stale. */+export const UNINDEXED_STALE_MS = 7 * 24 * 3_600_000;+const BATCH = 1_000;++export interface UnindexedFile { path: string; source_path: string; code: string; slug_taken: boolean }+export interface UnindexedSample { path: string; code: string; slug_taken?: true }++export interface UnindexedScan {+ source_id: string;+ incarnation: string;+ /** The commit whose tree was scanned (the source's last synced commit); null when the source never synced. */+ target: string | null;+ complete: boolean;+ /** The last Git path examined when the budget stopped the scan; null when complete. */+ cursor: string | null;+ /** Eligible files examined. */+ scanned: number;+ /** Files with no page, no hold and no scheduled re-screen. */+ unindexed: number;+ /** Of `unindexed`: the path slug belongs to a live page with another or no recorded origin. */+ slug_taken: number;+ /** Files with no page and no hold whose re-screen is already scheduled. */+ scheduled: number;+ by_code: Record<string, number>;+ samples: UnindexedSample[];+ /** Folder scaffolding names sync skips on purpose (`isSyncMetafile`) that are otherwise eligible and carry a frontmatter `type:` or `title:`; never scheduled. */+ metafile_skipped: number;+ metafile_samples: string[];+ /** The first unindexed files (at most `keep`), root-relative. */+ files: UnindexedFile[];+ /** The first already scheduled paths seen (at most `keep`), root-relative. */+ scheduled_paths: string[];+}++export interface UnindexedScanOpts {+ context?: ManagedSyncContext;+ /** Resume after this Git path (a previous incomplete scan's cursor). */+ cursor?: string | null;+ /** Absolute epoch ms; checked after each batch, so every pass examines at least one batch. */+ deadlineAt?: number;+ /** Stop after examining this many eligible files. */+ maxScanned?: number;+ screenLimit?: number;+ keep?: number;+ /** Tree entries per lookup batch (default 1,000). */+ batch?: number;+ now?: () => number;+}++/** The stored result of the latest pass(es) for one source (`op_checkpoints` op `unindexed-files`, fingerprint the source id). */+export interface UnindexedRecord extends Omit<UnindexedScan, 'files' | 'scheduled_paths'> {+ version: 1;+ started_at: string;+ computed_at: string;+ /** Root-relative paths whose re-screen the stored passes scheduled or found scheduled, at most `UNINDEXED_SCHEDULE_CAP`. */+ pending: string[];+ /** Some scheduled paths did not fit in `pending`, so the result cannot confirm them. */+ pending_truncated: boolean;+ /** Of `unindexed`: how many the stored passes scheduled; the rest wait for a pass with room. */+ scheduled_now: number;+ /** Prepended to a root-relative path to get its page origin (`<scope>/` for a subdirectory source in git-root mode). */+ source_prefix: string;+}++interface TreeEntry { path: string; oid: string; size: number }++/** The blobs of `target` under `scope` in tree order, after `after`, in batches; the child stops when the consumer does. */+async function* treeBatches(gitRoot: string, target: string, scope: string, after: string | null, size: number): AsyncGenerator<TreeEntry[]> {+ const child = spawn('git', ['-c', 'core.quotepath=false', '--literal-pathspecs', '-C', gitRoot, 'ls-tree', '-r', '-l', '-z', target, ...(scope ? ['--', scope] : [])],+ { env: gitChildEnv(), stdio: ['ignore', 'pipe', 'pipe'] });+ let stderr = '';+ child.stderr!.on('data', (chunk: Buffer) => { stderr = (stderr + chunk.toString('utf8')).slice(0, 2000); });+ const exit = new Promise<number | null>((resolve, reject) => { child.on('error', reject); child.on('close', resolve); });+ const floor = after === null ? null : Buffer.from(after, 'utf8');+ let pending: Buffer = Buffer.alloc(0), batch: TreeEntry[] = [];+ try {+ for await (const chunk of child.stdout! as AsyncIterable<Buffer>) {+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;+ for (let nul = pending.indexOf(0); nul >= 0; nul = pending.indexOf(0)) {+ const row = pending.subarray(0, nul).toString('utf8');+ pending = pending.subarray(nul + 1);+ const tab = row.indexOf('\t');+ const [, kind, oid, bytes] = row.slice(0, tab).split(/\s+/);+ const path = row.slice(tab + 1);+ if (kind !== 'blob' || floor && Buffer.compare(Buffer.from(path, 'utf8'), floor) <= 0) continue;+ batch.push({ path, oid: oid!, size: Number(bytes) });+ if (batch.length >= size) { yield batch; batch = []; }+ }+ }+ if (batch.length) yield batch;+ const code = await exit;+ if (code !== 0) throw new Error(`git ls-tree failed in ${gitRoot} (exit ${code}): ${stderr.trim().slice(0, 300)}`);+ } finally {+ if (child.exitCode === null) child.kill();+ }+}++/** Files of one managed Git source with no live page, no hold and no scheduled re-screen; bounded by `opts`. */+export async function findUnindexedFiles(engine: BrainEngine, sourceId: string, opts: UnindexedScanOpts = {}): Promise<UnindexedScan> {+ const context = opts.context ?? await resolveManagedSyncContext(engine, { sourceId, noPull: true } as SyncOpts);+ const { gitRoot, incarnation } = context;+ const now = opts.now ?? Date.now;+ const keep = opts.keep ?? UNINDEXED_SCHEDULE_CAP;+ const screenLimit = opts.screenLimit ?? UNINDEXED_SCREEN_LIMIT;+ const scan: UnindexedScan = { source_id: sourceId, incarnation, target: context.source.last_commit, complete: true, cursor: null, scanned: 0, unindexed: 0,+ slug_taken: 0, scheduled: 0, by_code: {}, samples: [], metafile_skipped: 0, metafile_samples: [], files: [], scheduled_paths: [] };+ if (!scan.target) return scan;+ const { scope, slugMode, eligible, sourcePath } = await loadSyncEligibility(engine, context);+ const exclude = await syncExcludePatterns(engine);+ const scaffolding = (path: string) => isSyncMetafile(path) && !matchesAnyGlob(scope ? path.slice(scope.length + 1) : path, exclude)+ && !isReservedSkillBundlePath(sourcePath(path)) && eligible(`${path.slice(0, path.lastIndexOf('/') + 1)}gbrain-metafile-probe${path.slice(path.lastIndexOf('.'))}`);+ const retry = new Set(await readGitHoldRetryPaths(engine, sourceId, incarnation));+ let screened = 0;+ for await (const batch of treeBatches(gitRoot, scan.target, scope, opts.cursor ?? null, opts.batch ?? BATCH)) {+ const rows = batch.filter(entry => eligible(entry.path) && !isWindowsColonTarget(entry.path)).map(entry => {+ const root = scope ? entry.path.slice(scope.length + 1) : entry.path;+ return { ...entry, root, origin: sourcePath(entry.path), legacy: slugMode === 'source-root' && scope ? entry.path : null };+ });+ scan.scanned += rows.length;+ const metafiles = batch.filter(entry => !eligible(entry.path) && scaffolding(entry.path));+ if (metafiles.length) {+ const indexed = new Set((await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path = ANY($2::text[])',+ [sourceId, metafiles.map(entry => sourcePath(entry.path))])).map(page => page.source_path));+ const unread = metafiles.filter(entry => !indexed.has(sourcePath(entry.path))).slice(0, Math.max(0, screenLimit - screened));+ screened += unread.length;+ const contents = readBlobContents(gitRoot, unread.map((entry): TreeBlob => ({ oid: entry.oid, size: entry.size })));+ for (const entry of unread) {+ const frontmatter = parseMarkdownHead(contents.get(entry.oid) ?? '').frontmatter;+ if (frontmatter.type == null && frontmatter.title == null) continue;+ scan.metafile_skipped++;+ if (scan.metafile_samples.length < UNINDEXED_SAMPLE_LIMIT) scan.metafile_samples.push(scope ? entry.path.slice(scope.length + 1) : entry.path);+ }+ }+ if (rows.length) {+ const origins = rows.flatMap(row => row.legacy ? [row.origin, row.legacy] : [row.origin]);+ const pages = await engine.executeRaw<{ source_path: string; slug: string }>(+ 'SELECT source_path, slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path = ANY($2::text[])', [sourceId, origins]);+ const byOrigin = new Map(pages.map(page => [page.source_path, page.slug]));+ const held = await heldGitPaths(engine, sourceId, incarnation, rows.map(row => row.root));+ const missing = rows.filter(row => !byOrigin.has(row.origin) && !(row.legacy && byOrigin.get(row.legacy) === resolveSlugForPath(row.root)) && !held.has(row.root));+ const fresh = missing.filter(row => {+ if (!retry.has(row.root)) return true;+ scan.scheduled++;+ if (scan.scheduled_paths.length < keep) scan.scheduled_paths.push(row.root);+ return false;+ });+ const slugs = fresh.map(row => resolveSlugForPath(row.origin)).filter(Boolean);+ const taken = new Set(slugs.length ? (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(page => page.slug) : []);+ const toScreen = fresh.slice(0, Math.max(0, screenLimit - screened));+ screened += toScreen.length;+ const contents = readBlobContents(gitRoot, toScreen.map((row): TreeBlob => ({ oid: row.oid, size: row.size })));+ const codes = new Map(toScreen.map(row => {+ const content = contents.get(row.oid);+ if (content === undefined) return [row.root, 'file_too_large'];+ const result = screenImportContent({ content, path: row.origin, byteLength: row.size, expectedSlug: resolveSlugForPath(row.origin) || null });+ return [row.root, result.status === 'refused' ? result.refusal.code : 'clean'];+ }));+ for (const row of fresh) {+ const code = codes.get(row.root) ?? 'unscreened', slugTaken = taken.has(resolveSlugForPath(row.origin));+ scan.unindexed++;+ if (slugTaken) scan.slug_taken++;+ scan.by_code[code] = (scan.by_code[code] ?? 0) + 1;+ if (scan.samples.length < UNINDEXED_SAMPLE_LIMIT) scan.samples.push({ path: row.root, code, ...(slugTaken ? { slug_taken: true as const } : {}) });+ if (scan.files.length < keep) scan.files.push({ path: row.root, source_path: row.origin, code, slug_taken: slugTaken });+ }+ }+ if ((opts.deadlineAt !== undefined && now() >= opts.deadlineAt) || (opts.maxScanned !== undefined && scan.scanned >= opts.maxScanned)) {+ scan.complete = false;+ scan.cursor = batch[batch.length - 1]!.path;+ break;+ }+ }+ return scan;+}++/** The stored results of these sources (sources with none are absent). */+export async function readUnindexedFiles(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds: string[]): Promise<Map<string, UnindexedRecord>> {+ if (!sourceIds.length) return new Map();+ const rows = await engine.executeRaw<{ record: UnindexedRecord }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=ANY($2::text[])',+ [UNINDEXED_FILES_OP, sourceIds]);+ return new Map(rows.map(row => [row.record.source_id, row.record]));+}++const addCounts = (a: Record<string, number>, b: Record<string, number>) => {+ const out = { ...a };+ for (const [code, n] of Object.entries(b)) out[code] = (out[code] ?? 0) + n;+ return out;+};++export interface UnindexedRefresh { scan: UnindexedScan; record: UnindexedRecord; scheduled: string[] }++/**+ * One bounded pass for one source: continues an incomplete stored result of the same incarnation (accumulating its counts),+ * schedules the found paths for a re-screen unless `schedule` is false, and stores the merged result.+ */+export async function refreshUnindexedFiles(engine: BrainEngine, sourceId: string, opts: Omit<UnindexedScanOpts, 'cursor'> & { schedule?: boolean } = {}): Promise<UnindexedRefresh> {+ const context = opts.context ?? await resolveManagedSyncContext(engine, { sourceId, noPull: true } as SyncOpts);+ const now = opts.now ?? Date.now;+ const stored = (await readUnindexedFiles(engine, [sourceId])).get(sourceId);+ const previous = stored && !stored.complete && stored.incarnation === context.incarnation && stored.cursor ? stored : null;+ const scan = await findUnindexedFiles(engine, sourceId, { ...opts, context, cursor: previous?.cursor ?? null });+ const scheduled = opts.schedule === false ? [] : scan.files.map(file => file.path);+ if (scheduled.length) await requestGitHoldRetry(engine, sourceId, context.incarnation, scheduled);+ const pending = [...new Set([...(previous?.pending ?? []), ...scan.scheduled_paths, ...scheduled])];+ const { scope, slugMode } = await loadSyncEligibility(engine, context);+ const at = new Date(now()).toISOString();+ const record: UnindexedRecord = {+ version: 1, source_id: sourceId, incarnation: context.incarnation, target: scan.target, complete: scan.complete, cursor: scan.cursor,+ started_at: previous?.started_at ?? at, computed_at: at,+ scanned: (previous?.scanned ?? 0) + scan.scanned, unindexed: (previous?.unindexed ?? 0) + scan.unindexed, slug_taken: (previous?.slug_taken ?? 0) + scan.slug_taken,+ scheduled: (previous?.scheduled ?? 0) + scan.scheduled, by_code: addCounts(previous?.by_code ?? {}, scan.by_code),+ samples: [...(previous?.samples ?? []), ...scan.samples].slice(0, UNINDEXED_SAMPLE_LIMIT),+ metafile_skipped: (previous?.metafile_skipped ?? 0) + scan.metafile_skipped,+ metafile_samples: [...(previous?.metafile_samples ?? []), ...scan.metafile_samples].slice(0, UNINDEXED_SAMPLE_LIMIT),+ pending: pending.slice(0, UNINDEXED_SCHEDULE_CAP),+ pending_truncated: (previous?.pending_truncated ?? false) || pending.length > UNINDEXED_SCHEDULE_CAP || scan.scheduled_paths.length < scan.scheduled,+ scheduled_now: (previous?.scheduled_now ?? 0) + scheduled.length,+ source_prefix: slugMode === 'git-root' && scope ? `${scope}/` : '',+ };+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,jsonb_build_array($3::text::jsonb))+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`, [UNINDEXED_FILES_OP, sourceId, JSON.stringify(record)]);+ return { scan, record, scheduled };+}++/** A stored result as doctor judges it now. */+export interface UnindexedState {+ source_id: string;+ record: UnindexedRecord | null;+ /** `missing`: no result for the current incarnation; `partial`: nothing found so far but the scan is incomplete. */+ state: 'ok' | 'unindexed' | 'scheduled' | 'partial' | 'stale' | 'missing';+ /** Found files no pass scheduled. */+ unscheduled: number;+ /** Scheduled paths the next sync has not re-screened yet. */+ waiting: number;+ /** Scheduled paths a sync re-screened that still have no page and no hold. */+ still_unindexed: number;+ age_ms: number | null;+}++/**+ * Judges each source's stored result without scanning: its retry row says which scheduled paths still wait for a sync, and+ * one page read plus one hold read over the consumed paths says whether each was imported or held.+ */+export async function judgeUnindexedFiles(engine: Pick<BrainEngine, 'executeRaw'>, sources: Array<{ id: string; incarnation: string }>, now = Date.now()): Promise<UnindexedState[]> {+ const records = await readUnindexedFiles(engine, sources.map(source => source.id));+ const out: UnindexedState[] = [];+ for (const source of sources) {+ const record = records.get(source.id) ?? null;+ const base = { source_id: source.id, record, unscheduled: 0, waiting: 0, still_unindexed: 0, age_ms: record ? Math.max(0, now - Date.parse(record.computed_at)) : null };+ if (!record || record.incarnation !== source.incarnation) { out.push({ ...base, state: 'missing' }); continue; }+ if (base.age_ms! > UNINDEXED_STALE_MS) { out.push({ ...base, state: 'stale' }); continue; }+ const unscheduled = Math.max(0, record.unindexed - record.scheduled_now);+ const retry = new Set(await readGitHoldRetryPaths(engine, source.id, source.incarnation));+ const waiting = record.pending.filter(path => retry.has(path)).length;+ const consumed = record.pending.filter(path => !retry.has(path));+ let stillUnindexed = 0;+ if (consumed.length) {+ const indexed = new Set((await engine.executeRaw<{ source_path: string }>(+ 'SELECT source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path = ANY($2::text[])',+ [source.id, consumed.map(path => `${record.source_prefix}${path}`)])).map(page => page.source_path));+ const held = await heldGitPaths(engine, source.id, source.incarnation, consumed);+ stillUnindexed = consumed.filter(path => !indexed.has(`${record.source_prefix}${path}`) && !held.has(path)).length;+ }+ const state = unscheduled || stillUnindexed ? 'unindexed' : waiting ? 'scheduled' : record.complete && !record.pending_truncated ? 'ok' : 'partial';+ out.push({ ...base, state, unscheduled, waiting, still_unindexed: stillUnindexed });+ }+ return out;+}diff --git a/test/core/cycle.serial.test.ts b/test/core/cycle.serial.test.tsindex 6b9c317f37..aadcc87a5d 100644--- a/test/core/cycle.serial.test.ts+++ b/test/core/cycle.serial.test.ts@@ -488,7 +488,8 @@ describe('runCycle — yieldBetweenPhases hook', () => {// Temporal typed edges: 26 (added `edge_contradictions` after calibration_profile).// C4 pinned questions: 27 (added `standing_questions` after drift).// #6188: 28 (added `fence_repair` after sync). #6377: 29 (added `content_repair` after fence_repair).- expect(hookCalls).toBe(29);+ // #6865: 30 (added `unindexed_files` after content_repair).+ expect(hookCalls).toBe(30);});test('hook exceptions do not abort the cycle', async () => {@@ -504,8 +505,8 @@ describe('runCycle — yieldBetweenPhases hook', () => {// v0.41.11.0: 20 phases (+extract_atoms, +synthesize_concepts, +conversation_facts_backfill).// v0.41.39 (#1700) + v0.42.0.0: 22 phases (+enrich_thin, +skillopt).// #2653: 23 phases (+drift). #5876: 24 (+chronicle). GBRA-40 Lane D: 25 (+facts_drain). Temporal typed edges: 26 (+edge_contradictions). C4: 27 (+standing_questions).- // #6188: 28 (+fence_repair). #6377: 29 (+content_repair).- expect(report.phases.length).toBe(29);+ // #6188: 28 (+fence_repair). #6377: 29 (+content_repair). #6865: 30 (+unindexed_files).+ expect(report.phases.length).toBe(30);});});diff --git a/test/e2e/dream-cycle-phase-order-pglite.test.ts b/test/e2e/dream-cycle-phase-order-pglite.test.tsindex a9e49e1013..0226dc242d 100644--- a/test/e2e/dream-cycle-phase-order-pglite.test.ts+++ b/test/e2e/dream-cycle-phase-order-pglite.test.ts@@ -132,6 +132,7 @@ const EXPECTED_PHASES: CyclePhase[] = ['sync','fence_repair', // #6188 — fence repair (global maintenance lane)'content_repair', // #6377 — the rest of the content-repair lane (slug conflicts)+ 'unindexed_files', // #6865 — committed files with no page and no hold, scheduled for a re-screen'synthesize','extract','extract_facts', // v0.32.2 — reconcile fence → DB facts indexdiff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 8715775f4d..c12d1ac976 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -201,6 +201,7 @@" [OK] rename_identity_downgrades: No rename that lost its page identity is waiting for a disposition."," [OK] purge_parked_pages: No soft-deleted page is parked by the managed purge."," [INFO] missing_recorded_files: Not applicable: no source is a classic checkout on this host (managed sources are checked by ghost_pages).",+ " [INFO] unindexed_files: Unindexed files are not known for default (not computed yet), notes (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed."," [OK] sync_config_keys: No retired sync config key is stored on this brain."," [OK] fence_integrity: No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned)."," [OK] search_mode: Mode: conservative (no per-key overrides — mode bundle is canonical).",@@ -223,7 +224,7 @@" [OK] oauth_client_scope_health: Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources, no privileged self-registered clients)"," [OK] autopilot_lock_scope: Lock path: <home>/.gbrain/autopilot.lock"," [OK] stale_locks: No stale locks (no rows with ttl_expires_at < NOW())",- " [OK] cycle_phase_scope: Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ " [OK] cycle_phase_scope: Phase taxonomy: 12 source-scoped, 16 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns]."," [INFO] embed_staleness: Not applicable: embeddings are disabled on this brain by choice, so chunks have no vectors by design (keyword search keeps working)."," [OK] entity_link_coverage: Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale"," [OK] timeline_coverage: Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 4568f3fdce..bd076512d8 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -2917,6 +2917,86 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/troubleshooting.md#unindexed-files",+ "sources": [+ {+ "source_id": "default",+ "state": "missing"+ },+ {+ "source_id": "notes",+ "state": "missing"+ }+ ]+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sources",+ "retry-held",+ "default",+ "--unindexed",+ "--brain",+ "host"+ ],+ "command": "gbrain sources retry-held default --unindexed --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "then": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull",+ "--brain",+ "host"+ ],+ "command": "gbrain sync --source default --no-pull --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "The sync re-screens the scheduled files of default: each one that passes imports, each one that refuses is recorded as a hold that gbrain sources status default lists."+ },+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Finds the committed files of default with no page and no hold (bounded; it continues an incomplete scan), schedules them for a re-screen and stores the result this check reads."+ },+ "message": "Unindexed files are not known for default (not computed yet), notes (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.",+ "name": "unindexed_files",+ "readiness_state": "unknown",+ "severity": "info",+ "status": "ok"+ },{"category": "meta","details": {@@ -3210,7 +3290,7 @@"category": "meta","details": {"counts": {- "global": 15,+ "global": 16,"mixed": 2,"source": 12},@@ -3243,11 +3323,12 @@"standing_questions": "global","sync": "source","synthesize": "mixed",- "synthesize_concepts": "global"+ "synthesize_concepts": "global",+ "unindexed_files": "global"}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 16 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex cfbfe4e618..e1d28332ad 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -3048,6 +3048,90 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/troubleshooting.md#unindexed-files",+ "sources": [+ {+ "source_id": "default",+ "state": "missing"+ },+ {+ "source_id": "notes",+ "state": "missing"+ },+ {+ "source_id": "plain",+ "state": "missing"+ }+ ]+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sources",+ "retry-held",+ "default",+ "--unindexed",+ "--brain",+ "host"+ ],+ "command": "gbrain sources retry-held default --unindexed --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "then": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull",+ "--brain",+ "host"+ ],+ "command": "gbrain sync --source default --no-pull --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "The sync re-screens the scheduled files of default: each one that passes imports, each one that refuses is recorded as a hold that gbrain sources status default lists."+ },+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Finds the committed files of default with no page and no hold (bounded; it continues an incomplete scan), schedules them for a re-screen and stores the result this check reads."+ },+ "message": "Unindexed files are not known for default (not computed yet), notes (not computed yet), plain (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.",+ "name": "unindexed_files",+ "readiness_state": "unknown",+ "severity": "info",+ "status": "ok"+ },{"category": "meta","details": {@@ -3508,7 +3592,7 @@"category": "meta","details": {"counts": {- "global": 15,+ "global": 16,"mixed": 2,"source": 12},@@ -3541,11 +3625,12 @@"standing_questions": "global","sync": "source","synthesize": "mixed",- "synthesize_concepts": "global"+ "synthesize_concepts": "global",+ "unindexed_files": "global"}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 16 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},@@ -6992,6 +7077,90 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/troubleshooting.md#unindexed-files",+ "sources": [+ {+ "source_id": "default",+ "state": "missing"+ },+ {+ "source_id": "notes",+ "state": "missing"+ },+ {+ "source_id": "plain",+ "state": "missing"+ }+ ]+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sources",+ "retry-held",+ "default",+ "--unindexed",+ "--brain",+ "host"+ ],+ "command": "gbrain sources retry-held default --unindexed --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "then": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull",+ "--brain",+ "host"+ ],+ "command": "gbrain sync --source default --no-pull --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "The sync re-screens the scheduled files of default: each one that passes imports, each one that refuses is recorded as a hold that gbrain sources status default lists."+ },+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Finds the committed files of default with no page and no hold (bounded; it continues an incomplete scan), schedules them for a re-screen and stores the result this check reads."+ },+ "message": "Unindexed files are not known for default (not computed yet), notes (not computed yet), plain (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.",+ "name": "unindexed_files",+ "readiness_state": "unknown",+ "severity": "info",+ "status": "ok"+ },{"category": "meta","details": {@@ -7452,7 +7621,7 @@"category": "meta","details": {"counts": {- "global": 15,+ "global": 16,"mixed": 2,"source": 12},@@ -7485,11 +7654,12 @@"standing_questions": "global","sync": "source","synthesize": "mixed",- "synthesize_concepts": "global"+ "synthesize_concepts": "global",+ "unindexed_files": "global"}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 16 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 3d41841ed3..0dbf579b92 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -3051,6 +3051,90 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/troubleshooting.md#unindexed-files",+ "sources": [+ {+ "source_id": "default",+ "state": "missing"+ },+ {+ "source_id": "notes",+ "state": "missing"+ },+ {+ "source_id": "plain",+ "state": "missing"+ }+ ]+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sources",+ "retry-held",+ "default",+ "--unindexed",+ "--brain",+ "host"+ ],+ "command": "gbrain sources retry-held default --unindexed --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "then": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull",+ "--brain",+ "host"+ ],+ "command": "gbrain sync --source default --no-pull --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "The sync re-screens the scheduled files of default: each one that passes imports, each one that refuses is recorded as a hold that gbrain sources status default lists."+ },+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Finds the committed files of default with no page and no hold (bounded; it continues an incomplete scan), schedules them for a re-screen and stores the result this check reads."+ },+ "message": "Unindexed files are not known for default (not computed yet), notes (not computed yet), plain (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.",+ "name": "unindexed_files",+ "readiness_state": "unknown",+ "severity": "info",+ "status": "ok"+ },{"category": "meta","details": {@@ -3511,7 +3595,7 @@"category": "meta","details": {"counts": {- "global": 15,+ "global": 16,"mixed": 2,"source": 12},@@ -3544,11 +3628,12 @@"standing_questions": "global","sync": "source","synthesize": "mixed",- "synthesize_concepts": "global"+ "synthesize_concepts": "global",+ "unindexed_files": "global"}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 16 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},@@ -6996,6 +7081,90 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/troubleshooting.md#unindexed-files",+ "sources": [+ {+ "source_id": "default",+ "state": "missing"+ },+ {+ "source_id": "notes",+ "state": "missing"+ },+ {+ "source_id": "plain",+ "state": "missing"+ }+ ]+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sources",+ "retry-held",+ "default",+ "--unindexed",+ "--brain",+ "host"+ ],+ "command": "gbrain sources retry-held default --unindexed --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "then": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull",+ "--brain",+ "host"+ ],+ "command": "gbrain sync --source default --no-pull --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "The sync re-screens the scheduled files of default: each one that passes imports, each one that refuses is recorded as a hold that gbrain sources status default lists."+ },+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Finds the committed files of default with no page and no hold (bounded; it continues an incomplete scan), schedules them for a re-screen and stores the result this check reads."+ },+ "message": "Unindexed files are not known for default (not computed yet), notes (not computed yet), plain (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.",+ "name": "unindexed_files",+ "readiness_state": "unknown",+ "severity": "info",+ "status": "ok"+ },{"category": "meta","details": {@@ -7456,7 +7625,7 @@"category": "meta","details": {"counts": {- "global": 15,+ "global": 16,"mixed": 2,"source": 12},@@ -7489,11 +7658,12 @@"standing_questions": "global","sync": "source","synthesize": "mixed",- "synthesize_concepts": "global"+ "synthesize_concepts": "global",+ "unindexed_files": "global"}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 16 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 3aff3a8917..fc2da82117 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2674,6 +2674,82 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/troubleshooting.md#unindexed-files",+ "sources": [+ {+ "source_id": "default",+ "state": "missing"+ }+ ]+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sources",+ "retry-held",+ "default",+ "--unindexed",+ "--brain",+ "host"+ ],+ "command": "gbrain sources retry-held default --unindexed --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "then": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull",+ "--brain",+ "host"+ ],+ "command": "gbrain sync --source default --no-pull --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "The sync re-screens the scheduled files of default: each one that passes imports, each one that refuses is recorded as a hold that gbrain sources status default lists."+ },+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Finds the committed files of default with no page and no hold (bounded; it continues an incomplete scan), schedules them for a re-screen and stores the result this check reads."+ },+ "message": "Unindexed files are not known for default (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.",+ "name": "unindexed_files",+ "readiness_state": "unknown",+ "severity": "info",+ "status": "ok"+ },{"category": "meta","details": {@@ -2920,7 +2996,7 @@"category": "meta","details": {"counts": {- "global": 15,+ "global": 16,"mixed": 2,"source": 12},@@ -2953,11 +3029,12 @@"standing_questions": "global","sync": "source","synthesize": "mixed",- "synthesize_concepts": "global"+ "synthesize_concepts": "global",+ "unindexed_files": "global"}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 16 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 0a2b3847d9..0481fce68e 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -2719,6 +2719,82 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/troubleshooting.md#unindexed-files",+ "sources": [+ {+ "source_id": "default",+ "state": "missing"+ }+ ]+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sources",+ "retry-held",+ "default",+ "--unindexed",+ "--brain",+ "host"+ ],+ "command": "gbrain sources retry-held default --unindexed --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "then": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull",+ "--brain",+ "host"+ ],+ "command": "gbrain sync --source default --no-pull --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "The sync re-screens the scheduled files of default: each one that passes imports, each one that refuses is recorded as a hold that gbrain sources status default lists."+ },+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Finds the committed files of default with no page and no hold (bounded; it continues an incomplete scan), schedules them for a re-screen and stores the result this check reads."+ },+ "message": "Unindexed files are not known for default (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.",+ "name": "unindexed_files",+ "readiness_state": "unknown",+ "severity": "info",+ "status": "ok"+ },{"category": "meta","details": {@@ -2964,7 +3040,7 @@"category": "meta","details": {"counts": {- "global": 15,+ "global": 16,"mixed": 2,"source": 12},@@ -2997,11 +3073,12 @@"standing_questions": "global","sync": "source","synthesize": "mixed",- "synthesize_concepts": "global"+ "synthesize_concepts": "global",+ "unindexed_files": "global"}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 16 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 9143acae36..b0d8556c1c 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -2722,6 +2722,82 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/troubleshooting.md#unindexed-files",+ "sources": [+ {+ "source_id": "default",+ "state": "missing"+ }+ ]+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sources",+ "retry-held",+ "default",+ "--unindexed",+ "--brain",+ "host"+ ],+ "command": "gbrain sources retry-held default --unindexed --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "then": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "sync",+ "--source",+ "default",+ "--no-pull",+ "--brain",+ "host"+ ],+ "command": "gbrain sync --source default --no-pull --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#unindexed-files",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "The sync re-screens the scheduled files of default: each one that passes imports, each one that refuses is recorded as a hold that gbrain sources status default lists."+ },+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "unindexed_files",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Finds the committed files of default with no page and no hold (bounded; it continues an incomplete scan), schedules them for a re-screen and stores the result this check reads."+ },+ "message": "Unindexed files are not known for default (not computed yet). The maintenance phase unindexed_files computes them on each run and continues an incomplete scan; to compute them now, run gbrain sources retry-held <id> --unindexed.",+ "name": "unindexed_files",+ "readiness_state": "unknown",+ "severity": "info",+ "status": "ok"+ },{"category": "meta","details": {@@ -2967,7 +3043,7 @@"category": "meta","details": {"counts": {- "global": 15,+ "global": 16,"mixed": 2,"source": 12},@@ -3000,11 +3076,12 @@"standing_questions": "global","sync": "source","synthesize": "mixed",- "synthesize_concepts": "global"+ "synthesize_concepts": "global",+ "unindexed_files": "global"}},"elapsed_ms": "<volatile>",- "message": "Phase taxonomy: 12 source-scoped, 15 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 16 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [fence_repair, content_repair, unindexed_files, resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, standing_questions, chronicle, facts_drain, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 6ffeaf7106..9af0c7117e 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -853,6 +853,10 @@"category": "brain","name": "missing_recorded_files"},+ {+ "category": "brain",+ "name": "unindexed_files"+ },{"category": "meta","name": "sync_config_keys"diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.tsindex d1068c04ad..e086c3c45c 100644--- a/test/managed-phase-matrix.test.ts+++ b/test/managed-phase-matrix.test.ts@@ -159,6 +159,23 @@ const MATRIX: Record<CyclePhase, Entry> = {expect(result.details).toMatchObject({ mode: 'apply', kinds: ['slug-conflicts'] });},},+ unindexed_files: {+ // #6865: a file the source's last synced commit holds with no page and no hold (an older gbrain's unrecorded refusal) is+ // found and scheduled for a re-screen on the next sync; the phase writes no page.+ seed: async ({ engine, sourceId, root }) => {+ git(root, 'init', '-q');+ mkdirSync(join(root, 'notes'));+ writeFileSync(join(root, 'notes/unindexed-example.md'), page('note', 'Unindexed example', 'Never imported.\n'));+ git(root, 'add', '.');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');+ await engine.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [sourceId, git(root, 'rev-parse', 'HEAD').trim()]);+ },+ assert: async ({ engine, result }) => {+ expect(result.status).toBe('ok');+ expect(result.details).toMatchObject({ mode: 'apply', scanned: 1, unindexed: 1, scheduled_now: 1, complete: true });+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE slug='notes/unindexed-example'")).toEqual([]);+ },+ },synthesize: {seed: async ({ engine, sourceId, root }) => {await put(engine, sourceId, 'people/example', page('note', 'Example', 'Example evidence.'));diff --git a/test/phase-scope-coverage.test.ts b/test/phase-scope-coverage.test.tsindex 925048e32c..1683c43e98 100644--- a/test/phase-scope-coverage.test.ts+++ b/test/phase-scope-coverage.test.ts@@ -41,7 +41,7 @@ describe('PHASE_SCOPE coverage', () => {expect(invalid).toEqual([]);});- test('all 29 phases covered (regression on accidental omission)', () => {+ test('all 30 phases covered (regression on accidental omission)', () => {// Pin the count so a future PR that adds a phase to ALL_PHASES// without updating PHASE_SCOPE notices here too. The v0.39.1.0// master merge brought in the 17th phase (`schema-suggest`); v0.41@@ -52,9 +52,9 @@ describe('PHASE_SCOPE coverage', () => {// adds 'facts_drain' for 25.// Temporal typed edges adds 'edge_contradictions' for 26; C4 pinned// questions adds 'standing_questions' for 27.- // #6188 adds 'fence_repair' for 28; #6377 adds 'content_repair' for 29.- expect(ALL_PHASES.length).toBe(29);- expect(Object.keys(PHASE_SCOPE).length).toBe(29);+ // #6188 adds 'fence_repair' for 28; #6377 adds 'content_repair' for 29; #6865 adds 'unindexed_files' for 30.+ expect(ALL_PHASES.length).toBe(30);+ expect(Object.keys(PHASE_SCOPE).length).toBe(30);});test('embed remains global (the headline brain-wide phase)', () => {diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 875c453765..9f8efb2709 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -220,6 +220,7 @@ test/trust-guarded-supersession.test.tstest/trust-held-removals.test.tstest/trust-owner-actions.test.tstest/unbound-source-6536.test.ts+test/unindexed-files.test.tstest/withdrawal-overlay-concurrency.test.tstest/withdrawal-publication-file.test.tstest/writer-status-owner-backends.test.tsdiff --git a/test/unindexed-files.test.ts b/test/unindexed-files.test.tsnew file mode 100644index 0000000000..bbadc7d9e3--- /dev/null+++ b/test/unindexed-files.test.ts@@ -0,0 +1,252 @@+/**+ * #6865: files an older gbrain refused before refusals became holds are on disk, committed and unchanged, with no page and+ * no hold, so incremental discovery never visits them. The detector finds them (in source-path space, both slug modes),+ * `sources retry-held --unindexed` schedules them, the next plain sync imports or holds each one, and doctor+ * `unindexed_files` walks argv -> then -> verify to ok. A bounded scan that stops early is never reported clean.+ */+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 type { SyncOpts } from '../src/commands/sync.ts';+import type { Check } from '../src/commands/doctor.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Action } from '../src/core/agent-output.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 { discoverManagedSync, loadSyncEligibility, resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';+import { readGitHoldRetryPaths, readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { findUnindexedFiles, readUnindexedFiles, refreshUnindexedFiles } from '../src/core/persistence/unindexed-files.ts';+import { gitFollowUpSync, retryUnindexed, runRetryHeld } from '../src/commands/sources-retry-held.ts';+import { unindexedFilesEntry } from '../src/commands/doctor/checks/unindexed-files.ts';+import { runUnindexedFilesPhase } from '../src/core/cycle/unindexed-files.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-unindexed-'));+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.\n`;+const STRAY_SLUG = '---\ntitle: Fund A\nslug: fund-a\n---\nA synthetic fund page.\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 });+});++/** Fixture writes the managed writer guard would refuse (the state an older gbrain left), made with persistence briefly off. */+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>, opts: { subdir?: string; mode?: 'git-root' | 'source-root' } = {}) {+ const id = `unidx-${randomUUID().replace(/-/g, '').slice(0, 20)}`, repo = join(home, id), root = opts.subdir ? join(repo, opts.subdir) : repo;+ const write = (path: string, content: string) => { mkdirSync(join(repo, path, '..'), { recursive: true }); writeFileSync(join(repo, path), content); };+ mkdirSync(root, { 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, root, JSON.stringify(opts.mode ? { slug_root_mode: opts.mode } : {})]);+ await claimWorktree(engine, id, root);+ 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 });+ /** An older gbrain refused these files without recording a hold: committed, and the source's cursor moved past them. */+ const 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)]));+ };+ const doctor = async (): Promise<Check> => (await unindexedFilesEntry.run({ engine, sourceIds: [id] } as unknown as DoctorContext) as Check[])[0]!;+ const holds = async () => (await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? [];+ return { id, repo, root, sync, legacy, doctor, holds };+}++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); }+ }+ });+}++/** Runs a fix's sync step the way an agent would: the argv must be the plain follow-up sync of the source. */+async function runSyncStep(engine: BrainEngine, sourceId: string, step: Action, sync: () => Promise<unknown>) {+ expect(step.argv).toEqual(await gitFollowUpSync(engine, sourceId, []));+ expect(step.argv).toEqual(['gbrain', 'sync', '--source', sourceId, '--no-pull']);+ await sync();+}++test('a legacy refused file is found, scheduled by retry-held --unindexed, then imported or held by a plain sync; doctor argv -> then -> verify ends ok', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A') });+ await s.sync();+ await s.legacy({ 'notes/clean.md': note('Clean'), 'investors/fund-a.md': STRAY_SLUG });+ expect(await engine.getPage('notes/clean', { sourceId: s.id })).toBeNull();+ expect(await s.holds()).toEqual([]);++ const scan = await findUnindexedFiles(engine, s.id);+ expect(scan).toMatchObject({ complete: true, cursor: null, scanned: 3, unindexed: 2, slug_taken: 0, scheduled: 0, target: git(s.repo, 'rev-parse', 'HEAD'),+ by_code: { clean: 1, frontmatter_slug_conflict: 1 } });+ expect(scan.files.map(file => [file.path, file.code]).sort()).toEqual([['investors/fund-a.md', 'frontmatter_slug_conflict'], ['notes/clean.md', 'clean']]);++ const dry = await retryUnindexed(engine, s.id, { dryRun: true });+ expect(dry).toMatchObject({ kind: 'git', dry_run: true, scheduled: 0, fix: { argv: ['gbrain', 'sources', 'retry-held', s.id, '--unindexed'] } });+ expect(dry.items.map(item => [item.key, item.reason, item.action]).sort()).toEqual([['investors/fund-a.md', 'unindexed', 'would_retry'], ['notes/clean.md', 'unindexed', 'would_retry']]);+ expect(await readGitHoldRetryPaths(engine, s.id, (await incarnationOf(engine, s.id)))).toEqual([]);+ expect((await readUnindexedFiles(engine, [s.id])).size).toBe(0);++ const before = await s.doctor();+ expect(before).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'unknown' });+ const fix = before.fix as Action;+ expect(fix.argv).toEqual(['gbrain', 'sources', 'retry-held', s.id, '--unindexed']);+ expect(fix.verify).toEqual({ argv: ['gbrain', 'doctor', '--only', 'unindexed_files', '--json'] });+ expect(fix.then!.verify).toEqual({ argv: ['gbrain', 'doctor', '--only', 'unindexed_files', '--json'] });++ const receipt = await retryUnindexed(engine, s.id);+ expect(receipt).toMatchObject({ scheduled: 2, unindexed: { complete: true, unindexed: 2 } });+ expect(receipt.fix!.argv).toEqual(fix.then!.argv);+ expect(receipt.items.map(item => [item.key, item.code, item.reason])).toEqual(expect.arrayContaining([['notes/clean.md', 'clean', 'unindexed'],+ ['investors/fund-a.md', 'frontmatter_slug_conflict', 'unindexed']]));+ const waiting = await s.doctor();+ expect(waiting).toMatchObject({ status: 'warn', details: { sources: [{ source_id: s.id, state: 'scheduled', waiting: 2, unscheduled: 0 }] } });+ expect((waiting.fix as Action).argv).toEqual(fix.then!.argv);++ await runSyncStep(engine, s.id, fix.then!, () => s.sync());+ expect((await engine.getPage('notes/clean', { sourceId: s.id }))?.title).toBe('Clean');+ expect((await s.holds()).map(hold => [hold.path, hold.code])).toEqual([['investors/fund-a.md', 'frontmatter_slug_conflict']]);++ const verified = await s.doctor();+ expect(verified).toMatchObject({ status: 'ok', details: { sources: [{ source_id: s.id, state: 'ok', still_unindexed: 0, waiting: 0 }] } });+ expect(verified.severity).toBeUndefined();+ expect((await findUnindexedFiles(engine, s.id))).toMatchObject({ complete: true, unindexed: 0, scheduled: 0 });+ const empty = await retryUnindexed(engine, s.id);+ expect(empty).toMatchObject({ scheduled: 0, items: [], next_action: `No unindexed files for ${s.id}.` });+}), 240_000);++async function incarnationOf(engine: BrainEngine, id: string): Promise<string> {+ return (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]))[0]!.incarnation;+}++test('files a pass could not schedule warn with retry-held --unindexed; argv -> then -> verify ends ok', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A') });+ await s.sync();+ await s.legacy({ 'notes/b.md': note('B'), 'notes/c.md': note('C') });+ const first = await refreshUnindexedFiles(engine, s.id, { keep: 1 });+ expect(first.scheduled).toEqual(['notes/b.md']);+ const check = await s.doctor();+ expect(check).toMatchObject({ status: 'warn', details: { sources: [{ state: 'unindexed', unscheduled: 1, waiting: 1 }] } });+ expect(check.message).toContain('notes/b.md [clean]');+ const fix = check.fix as Action;+ expect(fix.argv).toEqual(['gbrain', 'sources', 'retry-held', s.id, '--unindexed']);+ const receipt = await retryUnindexed(engine, s.id);+ expect(receipt.items.map(item => item.key)).toEqual(['notes/c.md']);+ expect(receipt.unindexed).toMatchObject({ already_scheduled: 1, unindexed: 1 });+ await runSyncStep(engine, s.id, fix.then!, () => s.sync());+ expect((await engine.getPage('notes/c', { sourceId: s.id }))?.title).toBe('C');+ expect(await s.doctor()).toMatchObject({ status: 'ok', details: { sources: [{ state: 'ok' }] } });+}), 240_000);++test('a file whose path slug belongs to a database-only page is not indexed: it is reported as slug_taken', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A') });+ await s.sync();+ await s.legacy({ 'notes/db-only.md': note('Db only') });+ await unmanaged(engine, () => engine.putPage('notes/db-only', { type: 'note', title: 'Db only', compiled_truth: 'Written database-only.' }, { sourceId: s.id }));+ const [page] = await engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM pages WHERE source_id=$1 AND slug=$2', [s.id, 'notes/db-only']);+ expect(page!.source_path).toBeNull();+ const scan = await findUnindexedFiles(engine, s.id);+ expect(scan).toMatchObject({ unindexed: 1, slug_taken: 1, samples: [{ path: 'notes/db-only.md', code: 'clean', slug_taken: true }] });+}), 240_000);++test('a titled file named like folder scaffolding is reported as metafile_skipped, never scheduled, and only an info finding with a user fix', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A') });+ await s.sync();+ await s.legacy({ 'investors/fund-a/index.md': '---\ntitle: Fund A\ntype: company\n---\nA synthetic fund overview.\n', 'notes/README.md': 'Plain scaffolding, no frontmatter.\n' });+ const scan = await findUnindexedFiles(engine, s.id);+ expect(scan).toMatchObject({ complete: true, scanned: 1, unindexed: 0, metafile_skipped: 1, metafile_samples: ['investors/fund-a/index.md'] });+ const receipt = await retryUnindexed(engine, s.id);+ expect(receipt).toMatchObject({ scheduled: 0, items: [], unindexed: { metafile_skipped: 1 }, next_action: `No unindexed files for ${s.id}.` });+ expect(await readGitHoldRetryPaths(engine, s.id, await incarnationOf(engine, s.id))).toEqual([]);+ const check = await s.doctor();+ expect(check).toMatchObject({ status: 'ok', severity: 'info', details: { sources: [{ state: 'ok', metafile_skipped: 1, metafile_samples: ['investors/fund-a/index.md'] }] } });+ const fix = check.fix as Action;+ expect(fix).toMatchObject({ actor: 'user', argv: ['gbrain', 'sync', '--source', s.id, '--no-pull'] });+ expect(fix.user_message).toContain('investors/fund-a/index.md -> investors/fund-a.md');+ expect(fix.user_message).toContain('on purpose');+}), 240_000);++test('a bounded scan that stops early is incomplete and never clean; later passes resume and cover the late paths', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/b.md': note('B'), 'notes/c.md': note('C') });+ await s.sync();+ await s.legacy({ 'notes/z.md': note('Z') });+ const head = await findUnindexedFiles(engine, s.id, { batch: 1, maxScanned: 1 });+ expect(head).toMatchObject({ complete: false, cursor: 'notes/a.md', scanned: 1, unindexed: 0 });+ const first = await refreshUnindexedFiles(engine, s.id, { batch: 1, maxScanned: 1 });+ expect(first.record).toMatchObject({ complete: false, cursor: 'notes/a.md', unindexed: 0 });+ const partial = await s.doctor();+ expect(partial).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'unknown', details: { sources: [{ state: 'partial' }] } });+ expect(partial.message).toContain('incomplete');+ let passes = 1, record = first.record;+ while (!record.complete && passes < 10) { record = (await refreshUnindexedFiles(engine, s.id, { batch: 1, maxScanned: 1 })).record; passes++; }+ expect(passes).toBe(5);+ expect(record).toMatchObject({ complete: true, cursor: null, scanned: 4, unindexed: 1, scheduled_now: 1, pending: ['notes/z.md'] });+ expect((await s.doctor()).details).toMatchObject({ sources: [{ state: 'scheduled', waiting: 1 }] });+}), 240_000);++for (const mode of ['git-root', 'source-root'] as const) {+ test(`a subdirectory source in ${mode} mode: discovery and the detector share one eligibility, compared in source-path space`, () => each(async engine => {+ const s = await source(engine, { 'brain/notes/a.md': note('A'), 'brain/notes/b.md': note('B'), 'brain/.hidden/h.md': note('H'), 'other/x.md': note('X') },+ { subdir: 'brain', mode });+ const opts = { sourceId: s.id, noPull: true, dryRun: true } as SyncOpts;+ const context = await resolveManagedSyncContext(engine, opts);+ const eligibility = await loadSyncEligibility(engine, context, opts);+ expect(eligibility).toMatchObject({ scope: 'brain', slugMode: mode });+ const listed = git(s.repo, 'ls-tree', '-r', '--name-only', 'HEAD').split('\n').filter(eligibility.eligible).map(eligibility.sourcePath).sort();+ const discovered = (await discoverManagedSync(engine, opts)).entries.filter(entry => entry.action === 'import').map(entry => entry.sourcePath).sort();+ expect(discovered).toEqual(listed);+ expect(listed).toEqual(mode === 'git-root' ? ['brain/notes/a.md', 'brain/notes/b.md'] : ['notes/a.md', 'notes/b.md']);+ await s.sync();+ await s.legacy({ 'brain/notes/c.md': note('C'), 'other/y.md': note('Y') });+ const scan = await findUnindexedFiles(engine, s.id);+ expect(scan).toMatchObject({ complete: true, scanned: 3, unindexed: 1 });+ expect(scan.files).toEqual([{ path: 'notes/c.md', source_path: mode === 'git-root' ? 'brain/notes/c.md' : 'notes/c.md', code: 'clean', slug_taken: false }]);+ }), 240_000);+}++test('the maintenance phase stores the result and schedules the paths; a dry run reports without writing', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A') });+ await s.sync();+ await s.legacy({ 'notes/b.md': note('B') });+ const dry = await runUnindexedFilesPhase(engine, { dryRun: true });+ expect(dry.details).toMatchObject({ mode: 'dry_run', scheduled_now: 0 });+ expect((dry.details.sources as Array<{ source_id: string; unindexed: number }>).find(entry => entry.source_id === s.id)).toMatchObject({ unindexed: 1 });+ expect((await readUnindexedFiles(engine, [s.id])).size).toBe(0);+ const live = await runUnindexedFilesPhase(engine, { dryRun: false });+ expect(live.status).toBe('ok');+ expect(live.summary).not.toContain('notes/b.md');+ expect((live.details.sources as Array<{ source_id: string; scheduled_now: number }>).find(entry => entry.source_id === s.id)).toMatchObject({ scheduled_now: 1 });+ expect((await readUnindexedFiles(engine, [s.id])).get(s.id)).toMatchObject({ complete: true, unindexed: 1, pending: ['notes/b.md'] });+ await s.sync();+ expect((await engine.getPage('notes/b', { sourceId: s.id }))?.title).toBe('B');+}), 240_000);++test('retry-held --unindexed refuses a connector source with invalid_params', () => each(async engine => {+ const id = `unidx-conn-${randomUUID().slice(0, 8)}`;+ await unmanaged(engine, () => engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES($1,$1,'{"kind":"github"}'::jsonb)`, [id]));+ await expect(retryUnindexed(engine, id)).rejects.toMatchObject({ code: 'invalid_params' });+ await unmanaged(engine, () => engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]));+ await expect(runRetryHeld(engine, [id, '--unindexed', '--all'])).rejects.toMatchObject({ code: 'invalid_params', message: 'Unknown option: --all.' });+}), 60_000);