Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): unindexed scan converges on busy sources, re-screens drain in the level pass, dry runs never wait on the writer (#7149, #7150, #7167)
garrytan94d51fcb045c
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 64744c0580..97497563a5 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -21,7 +21,7 @@- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept`, `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and the cross product against a reference model built from the state space).- `src/core/persistence/sync-pass.ts` — the read-only shadow of the level-triggered pass (#6712 PR 4a): `readShadowLevel` reads one managed source's level (`T` via `readTreeLevel`, `X`, working-mode untracked files, `Dp` for committed candidates only or every path in working mode, pages keyset on `pages.id` with the import record by a LATERAL primary-key probe and the revision's attestation in the same statement, holds and retry rows, open requests and pending Git effects, deletion markers) and classifies every path with `sync-classify.ts`; it writes and admits nothing. Postgres reads share one `REPEATABLE READ, READ ONLY` transaction; PGLite runs bounded 2,000-row statements. A company-brain source returns null (it keeps its frozen manifest). `shadowConvergence` wraps it in the receipt, `dryRunConvergence` backs `gbrain sync --dry-run --json`'s `convergence` (with the read-only screen), `statusConvergence` backs `sync status --detail` and doctor, and `idleTickProbe` times the idle tick's reads for the bench (`scripts/bench/sync-convergence.ts`). Tests: `test/sync-pass-shadow-6712.test.ts`.- `src/core/persistence/sync-convergence.ts` — the convergence receipt (#6712 PR 4a, schema `convergence/1`, always `dry_run: true`): per-class `counts` and `classes` with action tags (`in_flight`, `keep_db_pending` beyond 200 per pass, and `deletes_withheld` when #2828's valve trips are classes too), predicted `decisions` by side after `readOnlySameContentScreen` (the dry run's `sameContentAtOrigin`: a screening request through `prepareManagedSyncMutation(..., { unsaved: true })`, at most 200 paths; one call's preparations share group-publish.ts's `preparationReads` memo plus the binding, trust-config and purge-tombstone reads, read their pages through `importGroupReads`' batch (`reread`), and answer each page's origin, timeline, take-collision and safe-chunk-fence reads from one read per kind per call (`sliceReads`), so a call costs a constant, not a statement per page (GBRA-108); equal content is `same_content_noops`, unscreened is `screen_unknown`), `would_hold`, `db_ahead` by prefix, `legacy_unverified`, `legacy_pageless`, `deletes` with the valve verdict and set hash, up to 20 samples per non-matched class, timings and statement count. `--redact-paths` replaces paths with sha256 prefixes and drops slugs.-- `src/core/persistence/sync-pass-run.ts` — the live level-triggered pass of a managed, non-company source (#6712 PR 4b, design v3.2 §2.2, §3.1–§3.5, §8, §9), run under the source's drain lease. `runSyncPass` retires an unfinished legacy cursor first (its options seed the episode), pins the pass row (`sync.admission`, `HEAD`, the mode; the row is written with the lease token), decides the kind (`idle` stamps only `last_sync_at` as `up_to_date`; `hold_only`; `full`), then runs at most `PASS_MAX_ROUNDS` (4) rounds: read and classify the level (`sync-pass.ts`), admit `C_k = unsettled − S` in batches of at most `PASS_BATCH_MAX` (10,000; deletes, then imports) through sync-run.ts's cursor machinery on an in-memory batch, and add each settled `(path, level)` to `S` (never admitted twice in one pass). With nothing unsettled and nothing in flight it stamps through `applyPassCheckpoint`; four rounds without converging stop `resumable` / `not_converged`. Every stop records its outcome, stop reason, `settled` and `remaining` on the pass row (a stop mid-batch counts the entries its batch passed); a blocked page refusal is replayed with no new request while nothing that decided it changed. Tests: `test/sync-pass-live-6712.test.ts`, `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-outcomes-6712.test.ts`.+- `src/core/persistence/sync-pass-run.ts` — the live level-triggered pass of a managed, non-company source (#6712 PR 4b, design v3.2 §2.2, §3.1–§3.5, §8, §9), run under the source's drain lease. `runSyncPass` retires an unfinished legacy cursor first (its options seed the episode), pins the pass row (`sync.admission`, `HEAD`, the mode; the row is written with the lease token), decides the kind (`idle` stamps only `last_sync_at` as `up_to_date`; `hold_only`; `full`), then runs at most `PASS_MAX_ROUNDS` (4) rounds: read and classify the level (`sync-pass.ts`), admit `C_k = unsettled − S` in batches of at most `PASS_BATCH_MAX` (10,000; deletes, then imports) through sync-run.ts's cursor machinery on an in-memory batch, and add each settled `(path, level)` to `S` (never admitted twice in one pass). With nothing unsettled and nothing in flight it stamps through `applyPassCheckpoint`; four rounds without converging stop `resumable` / `not_converged`. Every stop records its outcome, stop reason, `settled` and `remaining` on the pass row (a stop mid-batch counts the entries its batch passed); a blocked page refusal is replayed with no new request while nothing that decided it changed. #7149: a requested re-screen (the `sync-hold-retry` row) is consumed as soon as the pass settles its path (the batch carrying it drained, or the round classified it settled), not only by the stamp, so a pass that stops before its stamp leaves no imported file reported as waiting. Tests: `test/sync-pass-live-6712.test.ts`, `test/unindexed-files-convergence-7149.test.ts`, `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-outcomes-6712.test.ts`.- `src/core/persistence/sync-pass-row.ts` — the pass row and the rows beside it (#6712 PR 4b, design §3.4), free of heavy imports so doctor, status, the lease, compaction and GC read it without loading the pass. `managed-sync-pass` (fingerprint `<source>:<incarnation>`) holds `obligations` (baseline, episode, cost, the converged state, mismatch and not-converged streaks, page faults, a blocked request to replay) and `telemetry` (the newest pass's kind, round, outcome, stop reason, candidates, settled, remaining, counts, timings). `writePassRow` writes it at pin under `assertDrainLease` and afterwards only `WHERE lease_token = $token`. Beside it: `sync-origin-deleted` (deletion markers), `sync-deletes-withheld` (the mass-delete trip) and `sync-pass-cost` (one reservation per group); `SYNC_PASS_ROW_OPS` lists the ops the checkpoint GC keeps for a live incarnation. `passHealth` is the one health rule (`blocked`, `not_converged`, `settle_mismatch`, `open_stalled`, `nothing_pending`); `SETTLE_MISMATCH_STREAK` and `NOT_CONVERGED_REPORT_STREAK` are 3.- `src/core/persistence/sync-pass-readers.ts` — the pass row as the former cursor readers see it (#6712 PR 4b, design §3.7): doctor's movement, git-holds and terminal-failure checks, the drain backlog (`readManagedSyncBacklog`), the blocked-run reader and `sources status` read a non-company source's pass row through `readPassReadings` (`passHealth` plus the checkout HEAD from a hardened `rev-parse` on this host; no checkout means `head: null` and the recorded converged target is trusted). `passResumeArgs` is the plain sync that continues the pass, with the open episode's inherited options; `passStopCode` and `passStuckSince` name a stuck pass. Company sources and unretired legacy cursors keep their cursor arm in each reader. Tests: `test/sync-pass-readers-6712.test.ts`, `test/sync-pass-reader-gaps-6712.test.ts`.- `src/core/persistence/sync-pass-apply.ts` — what a live pass round does besides admitting one-sided imports and deletes (#6712 PR 4b, design v3.2 §2.5–§2.7, §3.1, §5): holds with side and state for the two-sided and deleted rows (`file_drift` with `side`, `tombstone_edited`, `purged_differs`, `file_gone`), the `settle_mismatch` hold after three passes at one level, arm-1 adoption of a record without a revision on `fileSame`, the bounded legacy sweep (500 per round) that records equal legacy pages on the first full round (GBRA-108: in slices of `LEGACY_SWEEP_SLICE` (100) whose records commit before the next slice, each followed by a pass-row save and a `managed_sync.legacy_swept` progress event the drain's in-pass governor counts, so a pass stopped mid-sweep keeps its slices and the next pass sweeps only the rest; seam `sync:legacy_slice`; tests `test/sync-legacy-sweep-gbra108.test.ts` and its Postgres twin), the mass-delete valve (one `sync-deletes-withheld` record; imports and the stamp proceed), `keep_db` admission (200 per pass), deletion-marker retirement in full rounds, and the remote ending (`reconcile_host_required`: one-sided work commits, drift stays unsettled with no hold). Entry points: `applyPassRound`, `finishPassApply`, `summarizeRound`. Tests: `test/sync-pass-completion-6712.test.ts`.@@ -35,7 +35,7 @@- `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/repair/legacy-twins.ts` — `gbrain repair legacy-twins --source <id>` (#6885): explicit-only, preview-bound, destructive consent (`LEGACY_TWINS_CONSENT_TEXT`). `scanLegacyTwins` reads a source's live pages with no recorded origin and no `database_only_reason` in id batches (at most `LEGACY_TWINS_SCAN_LIMIT`), keeps those whose slug `slugifyPath` folds differently, and pairs each with the live page at the folded slug that records a file (at most `LEGACY_TWINS_LIMIT` pairs and decisions). `pairVerdict` lists a pair as a decision (never merged) for differing `content_hash`, several legacy candidates, a twin file `liveFileDrift` does not call `agrees`, a file at the twin's own slug path, twin withdrawals, a legacy `file:` URI or a twin slug outside the op grammar. The preview binds pairs to the owner (host, worktree, owner epoch, incarnation) and both pages' ids, slugs and revisions; the apply refuses `not_owner_host`, `legacy_twins_storage_unknown`, `preview_changed` and `legacy_twin_mass_merge_refused` (`massTwins`, the sync valve). Each pair re-checks with `pairNow`, then a managed brain submits one `managed_maintenance_merge_legacy_twin` request on the twin (`prepareLegacyTwinMerge`, dispatched from `prepared-maintenance.ts`: no file target, `databaseOnlyReason: 'shared_origin'`, the legacy key in `additionalPageKeys`, `pairLocked` under the publication locks); an unmanaged brain merges in `maintenanceTransaction` under both page locks. `applyTwinMerge` records the twin's `source_path` on the legacy page, clears the twin's origin (so its tombstone's retention purge is database-only, never a `shared_origin` refusal), moves links (deduplicated; pair links stay), timeline rows, raw data, attachments, page aliases and facts about the twin, records the twin slug as a `slug_aliases` row, versions and soft-deletes the twin, and moves the twin's `sync-import-provenance` record to the legacy page at its post-write revision. Outcomes `merged`, `changed_since_preview`. Tests: `test/repair-legacy-twins-6885.test.ts` (Postgres: `test/e2e/repair-legacy-twins-6885-postgres.test.ts`).-- `src/core/persistence/unindexed-files.ts` — #6865 the unindexed-file detector: `findUnindexedFiles(engine, sourceId, opts)` streams `git ls-tree -r -l -z` of the source's last synced commit, filters it through discovery's own `loadSyncEligibility`, and in batches (one `pages.source_path = ANY` read on `pages_source_path_idx`, one hold read by fingerprint) keeps files with no live page recording their origin (source-path space, with the legacy Git-root spelling in source-root mode), no hold and no scheduled re-screen (`readGitHoldRetryPaths`; those count as `scheduled`); a file whose path slug belongs to a live page with another or no origin is still unindexed and counted `slug_taken`. Found files are screened read-only with `screenImportContent` (at most 2,000 per pass, the rest `unscreened`). Folder-scaffolding names sync skips on purpose (`isSyncMetafile`) that would otherwise be eligible (checked against a probe name in the same directory plus `sync.exclude` and the reserved skill paths) and carry a frontmatter `type:` or `title:` are counted apart as `metafile_skipped` with samples, and never scheduled. A time or count budget stops it with `complete: false` and a cursor (the last Git path, compared in byte order, which is Git's recursive tree order). `refreshUnindexedFiles` continues an incomplete stored result, schedules the found paths (`requestGitHoldRetry`, a scheduling write only) and stores one `op_checkpoints` row per source (op `unindexed-files`, fingerprint the source id; the 7-day checkpoint purge applies). `judgeUnindexedFiles` is doctor's read: unscheduled finds, scheduled paths still in the retry row (waiting for a sync), and consumed paths that still have no page and no hold, without scanning. Test: `test/unindexed-files.test.ts`.+- `src/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 of the same incarnation and eligibility also after the source's commit moved (#7149): it first re-examines the paths before the cursor that changed between the two commits (`git diff-tree`; more than `UNINDEXED_REVISIT_CAP`, or an unreadable old commit, starts over), then resumes after the cursor. It 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). `unindexedScanBudgetMs` sizes one pass's budget: 60 s per started 100k live pages, at most 5 min. `judgeUnindexedFiles` is doctor's read without scanning: a scheduled path with a page or a hold is settled even while the retry row still names it (#7149); of the rest, those in the retry row wait for a sync and the others are still unindexed. Tests: `test/unindexed-files.test.ts`, `test/unindexed-files-convergence-7149.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/overwritten-edits.ts` — #6712 follow-up: `scanOverwrittenEdits` finds live pages whose database-only revision a managed-sync import replaced with different content and no hold, from durable rows only (it survives receipt compaction): `page_versions.write_request_id` / `archived_write_request_id`, the writer's committed receipt (`outcome.persistence.mode = 'database'`, not an import, no `git` effect for that revision, not a read-only mirror write), the archiving request recognised as a managed-sync import by intent kind or, once compacted, by operation `submit_job` + `outcome.imported_file` without `connector_database`, and `reconcileCanonical` digests (the import's own revision differs; no later revision holds the edit again). `high` or `unknown` (`no_persistence_outcome`, `import_content_unreadable`, `segmented`); the newest open overwrite per page; at most `OVERWRITE_SCAN_LIMIT` candidate versions per source. Revisions with no recorded writer are not reported.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 986e328d42..323325fd74 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -57,6 +57,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/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, least recently scanned first (#7149: no stored result first, then the oldest, so one large source cannot starve the others), under one deadline of min(5 min, a third of the maintenance job's remaining time), each source also stopping at its own budget (`unindexedScanBudgetMs`: 60 s per started 100k live pages); 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/unindexed-files-convergence-7149.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/repair.md b/docs/guides/repair.mdindex 5cb0784f88..e51e635746 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2705,7 +2705,9 @@ the next maintenance run, so pause first if you want to keep the original.A file an older gbrain refused before refusals became holds has no page and nohold; incremental sync never revisits it. Themaintenance phase `unindexed_files` finds such files (bounded, never-clean while incomplete) and schedules a re-screen; doctor+clean while incomplete; each run continues the stored scan, also after new+commits, and serves the least recently scanned source first) and schedules a+re-screen, which the next sync consumes once it imports or holds the file; doctor`unindexed_files` reports them. Run `gbrain sources retry-held <id> --unindexed`, then the sync it prints: each file imports or becomes a[hold](#held-files). `slug_taken` (the path slug belongs to another page) and `deleted_page`(the page was deleted while the file stayed committed) are never scheduled:diff --git a/src/commands/doctor/checks/unindexed-files.ts b/src/commands/doctor/checks/unindexed-files.tsindex ab59b4a2ee..0add59889f 100644--- a/src/commands/doctor/checks/unindexed-files.ts+++ b/src/commands/doctor/checks/unindexed-files.ts@@ -86,7 +86,8 @@ async function runUnindexedFiles(ctx: DoctorContext): Promise<Check[]> {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, deleted_page: record.deleted_page ?? 0, by_code: record.by_code, samples: record.samples, target: record.target, computed_at: record.computed_at,+ scanned: record.scanned, unindexed: record.unindexed, slug_taken: record.slug_taken, deleted_page: record.deleted_page ?? 0, by_code: record.by_code, samples: record.samples, target: record.target, started_at: record.started_at, computed_at: record.computed_at,+ scheduled_now: record.scheduled_now, pending_truncated: record.pending_truncated,metafile_skipped: record.metafile_skipped ?? 0, metafile_samples: record.metafile_samples ?? [] }) };const scaffolding = [blockedNote(states), metafileNote(states)].filter(Boolean).join(' ');const unindexed = states.filter(state => state.state === 'unindexed');diff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.tsindex 5dbd5b6c5c..141941da82 100644--- a/src/commands/sources-retry-held.ts+++ b/src/commands/sources-retry-held.ts@@ -30,7 +30,7 @@ import { outOfAttemptsHold, fenceAutoRepairFor, holdRepairSteps, readGitHoldRetrimport { 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';+import { findUnindexedFiles, refreshUnindexedFiles, unindexedScanBudgetMs, type UnindexedScan } from '../core/persistence/unindexed-files.ts';export interface RetryHeldReceipt {source_id: string;@@ -145,7 +145,7 @@ export async function retryUnindexed(engine: BrainEngine, sourceId: string, opts`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);+ const deadlineAt = Date.now() + (opts.budgetMs ?? await unindexedScanBudgetMs(engine, sourceId));let scan: UnindexedScan, scheduled: string[] = [];if (dryRun) scan = await findUnindexedFiles(engine, sourceId, { deadlineAt });else ({ scan, scheduled } = await refreshUnindexedFiles(engine, sourceId, { deadlineAt }));diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.tsindex 1a389ea12f..b980f234bd 100644--- a/src/commands/sync-delegate.ts+++ b/src/commands/sync-delegate.ts@@ -511,7 +511,7 @@ export type ManagedDelegationOutcome =* #6543: only a forced rung (the serve cannot take the run) really runs a consumer beside the serve; on the others this* process admits its writes and, with persistence.single_consumer on, the serve's consumer publishes them.*/-const fallbackLine = (pid: number, cause: string, forced: boolean, fix = 'Restart that serve on this gbrain version to run the catch-up inside it.'): string => forced+const ownConsumerLine = (pid: number, cause: string, forced: boolean, fix = 'Restart that serve on this gbrain version to run the catch-up inside it.'): string => forced? `[sync] ${cause}; this run uses its own consumer beside the serve (PID ${pid}). ${fix}`: `[sync] ${cause}; this run does not delegate to the serve (PID ${pid}): it admits its own writes, and with persistence.single_consumer on the serve's consumer publishes them. ${fix}`;@@ -530,9 +530,13 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:// waiter-only behind the serve it bypassed. A healthy serve beside a kill switch or an unsupported flag keeps consuming.const own = async (reason: Extract<ManagedDelegationOutcome, { kind: 'own_consumer' }>['reason'], line: string | null = null, force = false): Promise<ManagedDelegationOutcome> => {if (line) serr(line);- if (force) (await import('../core/persistence/consumer-election.ts')).forceOwnConsumer(reason);+ // #7167: a dry run writes nothing, so it starts no consumer of its own.+ if (force && !opts.dryRun) (await import('../core/persistence/consumer-election.ts')).forceOwnConsumer(reason);return { kind: 'own_consumer', reason, line };};+ // #7167: a dry run that is not delegated previews in this process and writes nothing; it neither admits writes nor runs a consumer.+ const fallbackLine = (pid: number, cause: string, forced: boolean, fix?: string): string => opts.dryRun+ ? `[sync] ${cause}; this dry run previews in this process instead of the serve (PID ${pid}) and writes nothing.` : ownConsumerLine(pid, cause, forced, fix);// 0. Opt-outs bypass the ladder before anything is probed or classified.if (args.includes('--no-delegate') || env.GBRAIN_SYNC_NO_DELEGATE === '1') return own('opted_out', null, true);const { resolveBrainId } = await import('../core/brain-resolver.ts');diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 42de5f3ab6..713587ea38 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -21,6 +21,8 @@ export interface SyncResult {managedWrite?: import('../core/persistence/sync-run.ts').ManagedSyncWriteDiagnostic;/** #6643: the request a rediscovery that retries a recorded failure waits for (its producer and slug), instead of a silent no-op. */retryWait?: import('../core/persistence/sync-run.ts').RetryWait;+ /** #7167: a managed dry run's read of the source's writer: open write requests (queued, running or recovering) and the oldest one's age. */+ writer?: import('../core/persistence/sync-run.ts').DryRunWriterState;/** #6712 PR 1: another drainer holds (or took) the source's drain lease; `resumable`, nothing admitted by this run. */leaseHeld?: import('../core/persistence/sync-lease.ts').DrainLeaseHeld;/**diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex 27c9542d29..3dd6a25fe4 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -113,7 +113,9 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promiconst lockKey = syncLockId(sourceId);const work = async (leaseSignal: AbortSignal | undefined): Promise<SyncResult> => {const opts: SyncOpts = leaseSignal ? { ...outer, signal: outer.signal ? AbortSignal.any([outer.signal, leaseSignal]) : leaseSignal } : outer;- let result = opts.drain+ // #7167: a dry run reads and previews once; the drain's stall governor (no commit in 5 min) would abandon a long read+ // of a large source as a writer stall, and nothing it does is a write the drain needs to watch.+ let result = opts.drain && !opts.dryRun? await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true): await (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);// #6349: a delta past the cursor bound syncs in stages; a drain takes the next stage from where the last one landeddiff --git a/src/core/cycle/unindexed-files.ts b/src/core/cycle/unindexed-files.tsindex e7fa26c59a..de0e55f3f6 100644--- a/src/core/cycle/unindexed-files.ts+++ b/src/core/cycle/unindexed-files.ts@@ -10,9 +10,12 @@* 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+ * Deadline: min(5 min, a third of the maintenance job's remaining time),+ * shared by the sources, each of which also stops at its own budget (60 s per+ * started 100k live pages, `unindexedScanBudgetMs`). #7149: the sources run+ * least recently scanned first (no stored result first, then the oldest), so+ * one large source cannot keep the others from ever being scanned; 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.*/@@ -22,7 +25,7 @@ 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 { findUnindexedFiles, readUnindexedFiles, refreshUnindexedFiles, unindexedScanBudgetMs, UNINDEXED_SCAN_MAX_BUDGET_MS, UNINDEXED_SCHEDULE_CAP, type UnindexedScan } from '../persistence/unindexed-files.ts';import { isUncontainedPhaseError } from './phase-containment.ts';export interface UnindexedFilesPhaseOpts {@@ -43,12 +46,15 @@ export async function runUnindexedFilesPhase(engine: BrainEngine | null, opts: U}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));+ const timeBudgetMs = opts.deadlineAtMs == null ? UNINDEXED_SCAN_MAX_BUDGET_MS : Math.min(UNINDEXED_SCAN_MAX_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;+ const rows = await engine.executeRaw<{ id: string; config: Record<string, unknown> | null; incarnation: string }>(+ "SELECT id, config, incarnation::text AS incarnation FROM sources WHERE archived IS NOT TRUE AND local_path IS NOT NULL AND (config->>'kind') IS NULL ORDER BY id");+ const stored = await readUnindexedFiles(engine, rows.map(row => row.id));+ const scannedAt = (row: { id: string; incarnation: string }) => { const record = stored.get(row.id); return record?.incarnation === row.incarnation ? record.computed_at : ''; };+ rows.sort((a, b) => scannedAt(a).localeCompare(scannedAt(b)));+ const sources: Array<{ source_id: string; budget_ms: number; 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 }> = [];@@ -63,12 +69,14 @@ export async function runUnindexedFilesPhase(engine: BrainEngine | null, opts: U});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 });+ const budgetMs = await unindexedScanBudgetMs(engine, row.id);+ const sourceDeadlineAt = Math.min(deadlineAt, now() + budgetMs);+ if (opts.dryRun) scan = await findUnindexedFiles(engine, row.id, { context, deadlineAt: sourceDeadlineAt, now });else {- const refresh = await refreshUnindexedFiles(engine, row.id, { context, deadlineAt, now, keep: room });+ const refresh = await refreshUnindexedFiles(engine, row.id, { context, deadlineAt: sourceDeadlineAt, 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,+ sources.push({ source_id: row.id, budget_ms: budgetMs, 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;@@ -88,7 +96,7 @@ export async function runUnindexedFilesPhase(engine: BrainEngine | null, opts: Utotal('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.` : '',+ incomplete ? `${incomplete} source(s) stopped at their time budget; 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);diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 84c40ab0c7..5f4ee3e358 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -41,7 +41,7 @@ import { PASS_BATCH_KEY_PREFIX, readConvergedWatermark, SyncAdmissionPaused, typimport { assertDrainLease, currentDrainLease } from './sync-lease.ts';import { digest } from './digest.ts';import { readSyncTail } from './sync-tail-record.ts';-import { clearGitHold, holdRescreenDue, readGitHoldRetryPaths, readSyncHoldPolicy, readGitSourceHolds, readSyncImportProvenances, syncImportParserFor } from './sync-holds.ts';+import { clearGitHold, clearGitHoldRetryPaths, holdRescreenDue, readGitHoldRetryPaths, readSyncHoldPolicy, readGitSourceHolds, readSyncImportProvenances, syncImportParserFor } from './sync-holds.ts';import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { loadConfig } from '../config.ts';import { startPersistenceConsumer } from './service.ts';@@ -453,8 +453,9 @@ async function stampIdlePass(engine: BrainEngine, input: SyncPassInput, lease: N* settle mismatches, and owed paths it cannot settle. A path settled earlier in this pass is admitted at most once more.*/async function triageRound(level: ShadowLevel, input: { S: Map<string, string>; legacyWaived: Set<string>; readmitted: Set<string>; admission: string; remote: boolean;- counts: { pausedDeletes: number } }) {+ counts: { pausedDeletes: number }; consumeRetry: (paths: Iterable<string>) => Promise<void> }) {const { S, legacyWaived, readmitted, admission, remote, counts } = input;+ const settledPaths: string[] = [];const settledKey = (path: string, levelOid: string | null) => `${path}\0${levelOid ?? ''}`;const deletes: ShadowPath[] = [], imports: ShadowPath[] = [], inFlight: ShadowPath[] = [], mismatch: ShadowPath[] = [], owed: ShadowPath[] = [];const heldRenameOrigins = new Set(level.heldRenames.map(held => syncOriginPath(held.rename.sourcePath)));@@ -462,7 +463,7 @@ async function triageRound(level: ShadowLevel, input: { S: Map<string, string>;for (const entry of level.paths) {if (step.due()) await step.pause();const r = entry.result;- if (r.settled) continue;+ if (r.settled) { settledPaths.push(entryPaths(level, entry.path).path); continue; }if (r.inFlight) { inFlight.push(entry); continue; }if (S.has(settledKey(entry.path, entry.state.level))) {// A hold this pass wrote or re-screened at L, a slug collision it skipped, or the origin deletion an identity hold keeps@@ -481,6 +482,7 @@ async function triageRound(level: ShadowLevel, input: { S: Map<string, string>;} else if (r.action === 'import' || r.action === 'reparse' || (!remote && (r.cls === 'drift' || r.cls === 'dirty'))) imports.push(entry);else owed.push(entry);}+ await input.consumeRetry(settledPaths);return { deletes, imports, inFlight, mismatch, owed };}@@ -541,6 +543,22 @@ function addCounts(counts: Record<string, number>, add: Record<string, number |for (const [key, value] of Object.entries(add)) counts[key] = (counts[key] ?? 0) + (value ?? 0);}+/**+ * #7149: a requested re-screen is consumed once the pass settled its path (imported, held, or settled at its level), not+ * only by the stamp: a pass that stopped before its stamp (timeout, writer_pending, not_converged) left the whole row+ * behind, so doctor kept reporting imported files as waiting and every later pass was forced to a full round.+ */+function retryConsumer(engine: BrainEngine, sourceId: string, incarnation: string, retry: readonly string[]): (paths: Iterable<string>) => Promise<void> {+ const open = new Set(retry);+ return async paths => {+ if (!open.size) return;+ const taken = [...new Set(paths)].filter(path => open.has(path));+ if (!taken.length) return;+ await clearGitHoldRetryPaths(engine, sourceId, incarnation, taken);+ for (const path of taken) open.delete(path);+ };+}+/** The pass stamp (design v3.2 §3.3): what its converged checkpoint publishes; closing the open episode counts what it released. */async function passStampFor(engine: BrainEngine, input: { context: ManagedSyncContext; head: string; slugMode: Cursor['slugMode']; episode: PassEpisode | undefined; selection: SyncSelection;configured: boolean; mode: SyncSelection['mode']; leaseToken: string; retry: string[]; level: ShadowLevel; selectionFp: string; parserFp: string; pack: string | null; full: boolean;@@ -646,7 +664,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr// The entries this round's batches settled before the round folds its candidates into S: a slice that stops mid-round// reports them (yieldSettled); a blocked stop reports S as it replays.let roundSettled = 0, yieldSettled = 0;- const retryConsumed = new Set<string>(retry);+ const retryConsumed = new Set<string>(retry), consumeRetry = retryConsumer(engine, sourceId, incarnation, remote ? [] : retry);const sliceBase = { started: performance.now(), pages: 0 };let batchNo = 0, waits = 0, candidatesFirst = 0;let lastMismatch: ShadowPath[] = [];@@ -792,7 +810,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrassertActive();if (applied.sweptAll && !value.obligations.legacy_sweep) value.obligations.legacy_sweep = { first_full_at: new Date().toISOString() };if (!remote) value.obligations.deletes_withheld = applied.withheld?.set_hash ?? null;- const { deletes, imports, inFlight, mismatch, owed } = await triageRound(level, { S, legacyWaived, readmitted, admission, remote, counts });+ const { deletes, imports, inFlight, mismatch, owed } = await triageRound(level, { S, legacyWaived, readmitted, admission, remote, counts, consumeRetry });// Earlier passes' requests that committed since they stopped are this pass's imports (sync-pass-carried.ts).if (value.obligations.pending_requests?.length) {const carried = await settleCarried(engine, value.obligations.pending_requests);@@ -872,6 +890,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr// A folded stamp writes the pass row with the obligations as they stand when its import is frozen.const stopped = await drain(chunk, last ? { ...await stampFor(level), fold: { ...fold, obligations: structuredClone(value.obligations), batch: chunk.length } } : undefined);if (stopped) return stop(stopped);+ await consumeRetry(chunk.map(entry => entry.path));value.telemetry.remaining = Math.max(0, built.entries.length - i - chunk.length) + inFlight.length + owed.length + mismatch.length;if (await envelopeCrossed(engine, value, costScope, processingOptions)) counts.costDeferred = 1;if (last && batchFolded) { await adoptStampedObligations(engine, value); folded = { head, done: doneKey() }; continue; } // the stamp wrote the pass rowdiff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 62b826484d..0ae062d5f3 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -545,10 +545,17 @@ async function adoptCursor(engine: BrainEngine, key: string, cursor: Cursor, inpreturn saved;}/** #5988: a managed dry run lists the holds the pending (or newly discovered) imports would earn, read-only. */+export interface DryRunWriterState { open_requests: number; oldest_open_age_seconds: number | null; next: string[] }+async function managedDryRun(engine: BrainEngine, value: Cursor, base: Cursor, run: { company: boolean; processingOptions: SyncProcessingOptions;syncOptions: SyncCursorOptions; repoPath?: string; remote: boolean }): Promise<SyncResult> {const screen = run.company ? null : await loadSyncScreenRun(engine, value.sourceId, value.processingOptions ?? run.processingOptions, run.remote);- return { ...result(base, 'dry_run'), ...await dryRunScreen(engine, value, screen,+ // #7167: the writer's state is reported, never waited on.+ const [open] = await engine.executeRaw<{ n: number | string; age: number | string | null }>(`SELECT count(*) AS n, EXTRACT(EPOCH FROM now() - min(created_at)) AS age+ FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')`, [value.sourceId]);+ const writer: DryRunWriterState = { open_requests: Number(open?.n ?? 0), oldest_open_age_seconds: open?.age == null ? null : Math.round(Number(open.age)),+ next: ['gbrain', 'sources', 'writer', 'status', '--source', value.sourceId, '--json'] };+ return { ...result(base, 'dry_run'), writer, ...await dryRunScreen(engine, value, screen,checkpointRetryCommand({ sourceId: value.sourceId, processingOptions: value.processingOptions, syncOptions: value.syncOptions ?? run.syncOptions, repoPath: run.repoPath })) };}diff --git a/src/core/persistence/unindexed-files.ts b/src/core/persistence/unindexed-files.tsindex 0655a4c0ca..e55e56651f 100644--- a/src/core/persistence/unindexed-files.ts+++ b/src/core/persistence/unindexed-files.ts@@ -33,8 +33,15 @@* 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 while its target commit and eligibility- * fingerprint are unchanged; otherwise the pass starts over. Blobs are read+ * accumulated by the next pass while its incarnation and eligibility+ * fingerprint are unchanged, also when the source's commit moved meanwhile+ * (#7149: a busy source commits between every two maintenance runs, and a scan+ * that started over each time never finished): the continuation first+ * re-examines the paths before its cursor that changed between the two+ * commits, then resumes after the cursor. When those changes cannot be listed+ * (the old commit is gone) or number more than `UNINDEXED_REVISIT_CAP`, the+ * pass starts over. Each source's time budget grows with its size+ * (`unindexedScanBudgetMs`). Blobs are read* and screened in slices bounded by bytes, with the deadline checked between* slices (a file left unread counts as `unscreened`).*/@@ -46,7 +53,7 @@ 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 { loadSyncEligibility, resolveManagedSyncContext, syncExcludePatterns, syncGit, 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';@@ -58,8 +65,13 @@ 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. */+/** The time one live pass (the maintenance phase, `sources retry-held --unindexed`) spends per `UNINDEXED_BUDGET_PAGES` live pages of its source. */export const UNINDEXED_SCAN_BUDGET_MS = 60_000;+export const UNINDEXED_BUDGET_PAGES = 100_000;+/** The most one pass of one source spends, and the most the maintenance phase spends over all sources. */+export const UNINDEXED_SCAN_MAX_BUDGET_MS = 300_000;+/** Changed paths before a stored cursor a continuation re-examines; with more, the pass starts over. */+export const UNINDEXED_REVISIT_CAP = 5_000;/** A stored result older than this is stale. */export const UNINDEXED_STALE_MS = 7 * 24 * 3_600_000;const BATCH = 1_000;@@ -104,6 +116,8 @@ export interface UnindexedScanOpts {context?: ManagedSyncContext;/** Resume after this Git path (a previous incomplete scan's cursor). */cursor?: string | null;+ /** Git paths at or before `cursor` examined again first (paths that changed since the scan passed them). */+ revisit?: ReadonlySet<string>;/** Absolute epoch ms; checked after each batch, so every pass examines at least one batch. */deadlineAt?: number;/** Stop after examining this many eligible files. */@@ -143,7 +157,7 @@ function visitBlobSlices<T extends TreeBlob>(gitRoot: string, entries: T[], visi}/** 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[]> {+async function* treeBatches(gitRoot: string, target: string, scope: string, after: string | null, size: number, revisit?: ReadonlySet<string>): 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 = '';@@ -160,7 +174,7 @@ async function* treeBatches(gitRoot: string, target: string, scope: string, afteconst 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;+ if (kind !== 'blob' || floor && Buffer.compare(Buffer.from(path, 'utf8'), floor) <= 0 && !revisit?.has(path)) continue;batch.push({ path, oid: oid!, size: Number(bytes) });if (batch.length >= size) { yield batch; batch = []; }}@@ -192,7 +206,8 @@ export async function findUnindexedFiles(engine: BrainEngine, sourceId: string,const retry = new Set(await readGitHoldRetryPaths(engine, sourceId, incarnation));const pastDeadline = () => opts.deadlineAt !== undefined && now() >= opts.deadlineAt;let screened = 0;- for await (const batch of treeBatches(gitRoot, scan.target, scope, opts.cursor ?? null, opts.batch ?? BATCH)) {+ const floor = opts.cursor ? Buffer.from(opts.cursor, 'utf8') : null;+ for await (const batch of treeBatches(gitRoot, scan.target, scope, opts.cursor ?? null, opts.batch ?? BATCH, opts.revisit)) {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 };@@ -249,13 +264,33 @@ export async function findUnindexedFiles(engine: BrainEngine, sourceId: string,}if (pastDeadline() || (opts.maxScanned !== undefined && scan.scanned >= opts.maxScanned)) {scan.complete = false;- scan.cursor = batch[batch.length - 1]!.path;+ const last = batch[batch.length - 1]!.path;+ scan.cursor = floor && Buffer.compare(Buffer.from(last, 'utf8'), floor) <= 0 ? opts.cursor! : last;break;}}return scan;}+/** One pass's time budget for a source: `UNINDEXED_SCAN_BUDGET_MS` per started `UNINDEXED_BUDGET_PAGES` live pages, at most `UNINDEXED_SCAN_MAX_BUDGET_MS`. */+export async function unindexedScanBudgetMs(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<number> {+ const [row] = await engine.executeRaw<{ n: number | string }>('SELECT count(*) AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [sourceId]);+ return unindexedBudgetForPages(Number(row?.n ?? 0));+}++export function unindexedBudgetForPages(pages: number): number {+ return Math.min(UNINDEXED_SCAN_MAX_BUDGET_MS, UNINDEXED_SCAN_BUDGET_MS * Math.max(1, Math.ceil(pages / UNINDEXED_BUDGET_PAGES)));+}++/** Git paths at or before `cursor` that differ between `from` and `to`; null when Git cannot list them or they number more than `UNINDEXED_REVISIT_CAP`. */+function changedBefore(gitRoot: string, from: string, to: string, scope: string, cursor: string): Set<string> | null {+ let listed: string;+ try { listed = syncGit(gitRoot, ['--literal-pathspecs', 'diff-tree', '-r', '-z', '--no-renames', '--name-only', from, to, ...(scope ? ['--', scope] : [])]); } catch { return null; }+ const floor = Buffer.from(cursor, 'utf8');+ const paths = new Set(listed.split('\0').filter(path => path && Buffer.compare(Buffer.from(path, 'utf8'), floor) <= 0));+ return paths.size > UNINDEXED_REVISIT_CAP ? null : paths;+}+/** 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();@@ -282,9 +317,12 @@ export async function refreshUnindexedFiles(engine: BrainEngine, sourceId: strinconst stored = (await readUnindexedFiles(engine, [sourceId])).get(sourceId);const eligibility = await loadSyncEligibility(engine, context);const key = eligibilityKey(eligibility.scope, eligibility.slugMode, await syncExcludePatterns(engine));- const previous = stored && !stored.complete && stored.incarnation === context.incarnation && stored.cursor- && stored.target === context.source.last_commit && stored.eligibility === key ? stored : null;- const scan = await findUnindexedFiles(engine, sourceId, { ...opts, context, cursor: previous?.cursor ?? null });+ const resumable = stored && !stored.complete && stored.incarnation === context.incarnation && stored.cursor && stored.target && context.source.last_commit+ && stored.eligibility === key ? stored : null;+ const revisit = resumable && resumable.target !== context.source.last_commit+ ? changedBefore(context.gitRoot, resumable.target!, context.source.last_commit!, eligibility.scope, resumable.cursor!) : new Set<string>();+ const previous = revisit ? resumable : null;+ const scan = await findUnindexedFiles(engine, sourceId, { ...opts, context, cursor: previous?.cursor ?? null, ...(previous && revisit?.size ? { revisit } : {}) });const scheduled = opts.schedule === false ? [] : scan.files.filter(file => !file.slug_taken && !file.deleted_page).map(file => file.path);if (scheduled.length) await requestGitHoldRetry(engine, sourceId, context.incarnation, scheduled);const pending = [...new Set([...(previous?.pending ?? []), ...scan.scheduled_paths, ...scheduled])];@@ -319,7 +357,7 @@ export interface UnindexedState {unscheduled: number;/** Found files a re-screen cannot import (`slug_taken` + `deleted_page`): a person renames, deletes or restores; never scheduled. */blocked: number;- /** Scheduled paths the next sync has not re-screened yet. */+ /** Scheduled paths the next sync has not re-screened yet and that still have no page and no hold. */waiting: number;/** Scheduled paths a sync re-screened that still have no page and no hold. */still_unindexed: number;@@ -327,8 +365,10 @@ export interface UnindexedState {}/**- * 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.+ * Judges each source's stored result without scanning: one page read plus one hold read over the scheduled paths says+ * whether each was imported or held, and of the rest its retry row says which still wait for a sync. A scheduled path+ * with a page or a hold is settled even while the retry row still names it (#7149: a sync pass that stops before its+ * stamp leaves the row behind after importing the path).*/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));@@ -341,16 +381,16 @@ export async function judgeUnindexedFiles(engine: Pick<BrainEngine, 'executeRaw'const blocked = (record.slug_taken ?? 0) + (record.deleted_page ?? 0);const unscheduled = Math.max(0, record.unindexed - blocked - 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) {+ let open = record.pending;+ if (open.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;+ [source.id, open.map(path => `${record.source_prefix}${path}`)])).map(page => page.source_path));+ const held = await heldGitPaths(engine, source.id, source.incarnation, open);+ open = open.filter(path => !indexed.has(`${record.source_prefix}${path}`) && !held.has(path));}+ const waiting = open.filter(path => retry.has(path)).length;+ const stillUnindexed = open.length - waiting;const state = unscheduled || stillUnindexed ? 'unindexed' : waiting ? 'scheduled' : record.complete && !record.pending_truncated ? 'ok' : 'partial';out.push({ ...base, state, unscheduled, blocked, waiting, still_unindexed: stillUnindexed });}diff --git a/test/origin-twin-sequence-7150.test.ts b/test/origin-twin-sequence-7150.test.tsnew file mode 100644index 0000000000..978383b7e4--- /dev/null+++ b/test/origin-twin-sequence-7150.test.ts@@ -0,0 +1,144 @@+/**+ * #7150: the production sequence behind #6948, replayed end to end on a managed source against current master. A legacy+ * page with no recorded origin sits beside the page that records a file, with the same body; the source is trust-claimed+ * (the `trust_claim` channel the second page's history showed), a writer then tries to give the legacy page the held+ * origin, file repair targets the file, and finally the twin state an older gbrain left behind meets a sync. Before #6948+ * the twin stopped every managed sync of the source with `page_identity_changed` naming one slug. Now:+ *+ * - the trust claim re-tiers rows and assigns no origin;+ * - every origin-assigning writer refuses a second live claimant and names the page that records the file;+ * - file repair resolves the file to the page its path names and refuses the twin;+ * - a sync holds only the twin-claimed file, names every claimant, syncs the rest, and the sync-time heal merges a+ * same-body twin into the canonical page with an `origin_twin_resolved` receipt; a twin whose body differs stays a per-file+ * hold for a person and never stops the source.+ *+ * PGLite and, with DATABASE_URL, Postgres. Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performSync } from '../src/commands/sync/perform.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { canonicalOriginPage } from '../src/core/persistence/origin-guard.ts';+import { prepareDriftPage } from '../src/core/repair/file-drift.ts';+import { liftClaimedSources, recordSourceClaims } from '../src/core/trust/claim.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { dropOriginIndex } from './helpers/origin-index.ts';+import { withEnv } from './helpers/with-env.ts';++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', 'synthetic content'); };+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;+const FILE = 'projects/note-example.md', CANONICAL = 'projects/note-example', TWIN = 'ideas/note-example';++async function refusal(run: () => Promise<unknown>): Promise<Error & { code?: string; detail?: string }> {+ try { await run(); } catch (error) { return error as Error & { code?: string; detail?: string }; }+ throw new Error('expected the write to be refused, but it succeeded');+}++for (const backend of testBackends()) describe(`[${backend}] #7150 the origin-twin sequence cannot stop a managed source`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ const home = mkdtempSync(join(tmpdir(), `gbrain-7150-${backend}-`));+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, GBRAIN_INTERACTIVE: '0', CI: '1' };+ const sync = (opts: Record<string, unknown>) => withEnv(env, () => performSync(engine, opts as Parameters<typeof performSync>[1]));+ const page = async (sourceId: string, slug: string) => (await engine.executeRaw<{ deleted_at: string | null; compiled_truth: string; source_path: string | null }>(+ 'SELECT deleted_at, compiled_truth, source_path FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0] ?? null;+ const write = (sourceId: string, fn: (tx: BrainEngine) => Promise<unknown>) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => fn(tx), TEST_WRITE_ATTRIBUTION));++ /** The canonical page synced from FILE, plus a legacy page with no origin carrying the same body. */+ async function shape(twinBody?: string) {+ const id = `ot7150-${randomUUID().replace(/-/g, '').slice(0, 12)}`, root = join(home, id);+ mkdirSync(join(root, 'projects'), { recursive: true }); mkdirSync(join(root, 'notes'));+ git(root, 'init', '-q');+ writeFileSync(join(root, FILE), note('A synthetic project note.'));+ writeFileSync(join(root, 'notes/other.md'), note('Another note, version one.'));+ commit(root);+ await withEnv(env, async () => {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ });+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };+ expect((await sync(opts)).status).toBe('first_sync');+ const canonical = (await engine.executeRaw<{ compiled_truth: string; timeline: string; trust_tier: string }>(+ 'SELECT compiled_truth, timeline, trust_tier FROM pages WHERE source_id=$1 AND slug=$2', [id, CANONICAL]))[0]!;+ await write(id, async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.write_trust_tier', $1, true)", [canonical.trust_tier]);+ await tx.putPage(TWIN, { type: 'note', title: 'Example', compiled_truth: twinBody ?? canonical.compiled_truth, timeline: canonical.timeline ?? '', frontmatter: {},+ content_hash: randomUUID() }, { sourceId: id });+ });+ expect((await page(id, TWIN))!.source_path).toBeNull();+ return { id, root, opts };+ }++ /** What an older gbrain left: the legacy page records the held file too (no current writer can, so it is set directly). */+ async function legacyTwin(sourceId: string) {+ await dropOriginIndex(engine);+ await write(sourceId, tx => tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [sourceId, TWIN, FILE]));+ }++ beforeAll(async () => {+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => {+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); });+ await engine.disconnect(); await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+ }, 60_000);++ test('trust claim, then an origin assignment, then file repair, then sync: no step creates a twin, and a legacy twin heals with a receipt while the rest syncs', async () => {+ const f = await shape();+ // 1. The trust claim re-tiers the source's legacy rows and assigns no origin.+ await withEnv(env, async () => { await recordSourceClaims(engine, [f.id]); await liftClaimedSources(engine); });+ expect((await page(f.id, TWIN))!.source_path).toBeNull();+ // 2. A writer giving the legacy page the held origin is refused and names the page that records the file.+ const assigned = await refusal(() => write(f.id, tx => tx.putPage(TWIN, { type: 'note', title: 'Example', compiled_truth: 'Moved.', source_path: FILE }, { sourceId: f.id })));+ expect(assigned).toMatchObject({ code: 'page_identity_changed', detail: 'origin_already_claimed' });+ expect(assigned.message + String((assigned as { hint?: string }).hint ?? '')).toContain(FILE);+ expect((await page(f.id, TWIN))!.source_path).toBeNull();+ // 3. The state an older gbrain left. File repair resolves the file to the page its path names and refuses the twin.+ await legacyTwin(f.id);+ expect(await canonicalOriginPage(engine, f.id, FILE)).toMatchObject({ slug: CANONICAL });+ expect(await refusal(() => prepareDriftPage(engine, f.id, TWIN, 'file', new Date().toISOString()))).toMatchObject({ code: 'page_identity_changed', detail: 'origin_conflict' });+ // 4. A sync with an unrelated edit: the source syncs, and the heal merges the same-body twin with a receipt.+ writeFileSync(join(f.root, 'notes/other.md'), note('Another note, version two.'));+ commit(f.root);+ const result = await sync(f.opts);+ expect(result.status).toBe('synced');+ expect((await page(f.id, 'notes/other'))!.compiled_truth).toContain('version two');+ expect(result.origin_twins_resolved).toMatchObject({ resolved: 1, failed: 0, resolved_paths: [FILE] });+ expect(result.origin_twins_resolved!.receipts[0]).toMatchObject({ status: 'origin_twin_resolved', survivor_slug: CANONICAL, twin_slug: TWIN,+ restore_argv: ['gbrain', 'restore', TWIN, '--source-id', f.id] });+ expect((await page(f.id, TWIN))!.deleted_at).not.toBeNull();+ expect((await page(f.id, CANONICAL))!.deleted_at).toBeNull();+ }, 180_000);++ test('a legacy twin whose body differs is held for that file alone, naming every claimant, and never stops the source', async () => {+ const f = await shape('A different body the file does not carry.');+ await legacyTwin(f.id);+ writeFileSync(join(f.root, 'notes/other.md'), note('Another note, version two.'));+ commit(f.root);+ const result = await withEnv(env, () => performManagedSync(engine, f.opts));+ expect(result.status).toBe('synced');+ expect((await page(f.id, 'notes/other'))!.compiled_truth).toContain('version two');+ const held = ((await readGitSourceHolds(engine, { sourceIds: [f.id] }))[0]?.holds ?? []).filter(hold => hold.code === 'origin_conflict');+ expect(held.map(hold => [hold.path, hold.meta.reason, hold.meta.canonical_slug, (hold.meta.origin_claimants ?? []).map(claimant => claimant.slug).sort()]))+ .toEqual([[FILE, 'content_differs', CANONICAL, [TWIN, CANONICAL].sort()]]);+ expect((await page(f.id, TWIN))!.deleted_at).toBeNull();+ }, 180_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 15d79af331..18de0a6ce0 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -223,6 +223,7 @@ test/migration-persistence-request-id-index.test.tstest/migration-persistence-request-slug-index.test.tstest/on-commit-embedding.serial.test.tstest/origin-guard-6948.test.ts+test/origin-twin-sequence-7150.test.tstest/origin-twins-6948.test.tstest/overwritten-edits-6712.test.tstest/owner-refusal.test.ts@@ -398,6 +399,7 @@ test/sync-drain-effect-recovery-blocked.test.tstest/sync-drain-head-blocked-6543.test.tstest/sync-drain-inpass-stall.test.tstest/sync-drain-write-capacity.test.ts+test/sync-dry-run-drain-7167.test.tstest/sync-exits-l4-6712.test.tstest/sync-freshness-6858.test.tstest/sync-frontmatter-recovery.test.ts@@ -433,6 +435,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-convergence-7149.test.tstest/unindexed-files.test.tstest/vector-manifest-probe-bound.test.tstest/withdrawal-overlay-concurrency.test.tsdiff --git a/test/serve-sync-handoff.serial.test.ts b/test/serve-sync-handoff.serial.test.tsindex de566aad5a..5b031de86e 100644--- a/test/serve-sync-handoff.serial.test.ts+++ b/test/serve-sync-handoff.serial.test.ts@@ -289,6 +289,26 @@ describe('maybeDelegateManagedSyncToServe (the Postgres ladder, client half)', (expect(ownConsumerForcedReason()).toBeNull();}), 120_000);+ test('#7167: a dry run that is not delegated says it previews in this process and writes nothing, and never forces a consumer of its own', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const f = await fixture(1);+ const dead = join(home, `dead-${randomUUID().slice(0, 8)}.sock`);+ writeFileSync(dead, '');+ resetOwnConsumerForTest();+ captureStderr();+ const dry = { ...baseOpts(f.id), dryRun: true };+ const noSock = await maybeDelegateManagedSyncToServe(engine, ['--dry-run'], dry, deps({ sock: null }));+ const silent = await maybeDelegateManagedSyncToServe(engine, ['--dry-run'], dry, deps({ sock: dead }));+ releaseStderr();+ for (const outcome of [noSock, silent]) {+ expect(outcome).toMatchObject({ kind: 'own_consumer', reason: 'no_socket' });+ const line = outcome.kind === 'own_consumer' ? outcome.line ?? '' : '';+ expect(line).toMatch(/; this dry run previews in this process instead of the serve \(PID 4242\) and writes nothing\.$/);+ expect(line).not.toMatch(/admits|own consumer/);+ }+ expect(captured).toHaveLength(2);+ expect(ownConsumerForcedReason()).toBeNull();+ }), 120_000);+test('#6543: a serve whose IPC socket does not answer cannot take the run, so this process consumes itself (forced past single_consumer)', async () => withEnv({ GBRAIN_HOME: home }, async () => {const f = await fixture(1);const dead = join(home, `dead-${randomUUID().slice(0, 8)}.sock`);diff --git a/test/sync-dry-run-drain-7167.test.ts b/test/sync-dry-run-drain-7167.test.tsnew file mode 100644index 0000000000..1a151b7cdc--- /dev/null+++ b/test/sync-dry-run-drain-7167.test.ts@@ -0,0 +1,48 @@+/**+ * #7167: `gbrain sync --dry-run` on a large managed source sat for five minutes and then failed `partial` / `writer_pending`+ * with `drain_stalled` (`no_progress`). The CLI runs a sync as a drain, and the drain's governor stops a pass that commits+ * nothing for five minutes; a dry run commits nothing by design, so a long read of a big source was abandoned as a writer+ * stall. A dry run now previews once, outside the drain, and reports the writer's open requests as a field instead of+ * waiting on them.+ *+ * The governor's five minutes are reached here by a clock that runs 20,000 times faster than real time while the dry run+ * reads (the drain reads `Date.now`); the dry run itself never reads the clock for a decision. On Postgres, master+ * reproduced the report exactly (`partial`, `writer_pending`, `drain_stalled`, `no_progress`); on PGLite the governor's+ * head read queues behind the dry run's own statements, so there master returned the preview with a drain report.+ */+import { afterEach, expect, spyOn, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { performSync } from '../src/commands/sync/perform.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { testBackends } from './helpers/test-backends.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content'); };+const note = (title: string) => `---\ntype: concept\ntitle: ${title}\n---\nA synthetic observation about ${title}.\n`;+const setup = ({ root }: { root: string }) => {+ git(root, 'init', '-q');+ for (let d = 0; d < 4; d++) {+ mkdirSync(join(root, `notes-${d}`), { recursive: true });+ for (let i = 0; i < 60; i++) writeFileSync(join(root, `notes-${d}/n${i}.md`), note(`notes-${d}/n${i}`));+ }+ commit(root);+};++let clock: { mockRestore(): void } | null = null;+afterEach(() => { clock?.mockRestore(); clock = null; });++for (const backend of testBackends()) test(`[${backend}] a dry run on the drain path is never abandoned as a writer stall: it previews, reports the writer state, and returns`, () => managedBrain(async ({ engine }) => {+ const real = Date.now.bind(Date), start = real();+ clock = spyOn(Date, 'now').mockImplementation(() => start + (real() - start) * 20_000);+ let result;+ try {+ result = await performSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, dryRun: true, drain: true, governMs: 10 });+ } finally { clock.mockRestore(); clock = null; }+ expect(result.status).toBe('dry_run');+ expect(result.reason).toBeUndefined();+ expect(result.drain).toBeUndefined();+ expect(result.writer).toEqual({ open_requests: 0, oldest_open_age_seconds: null, next: ['gbrain', 'sources', 'writer', 'status', '--source', 'default', '--json'] });+ expect(Number((await engine.executeRaw<{ n: number | string }>("SELECT count(*) AS n FROM pages WHERE source_id='default'"))[0]!.n)).toBe(0);+}, { setup, ...(backend === 'postgres' ? { databaseUrl: process.env.DATABASE_URL } : {}) }), 240_000);diff --git a/test/unindexed-files-convergence-7149.test.ts b/test/unindexed-files-convergence-7149.test.tsnew file mode 100644index 0000000000..67e9d3b887--- /dev/null+++ b/test/unindexed-files-convergence-7149.test.ts@@ -0,0 +1,171 @@+/**+ * #7149: on a large, busy managed Git source the #6865 unindexed-file scan never finished and the files it scheduled+ * never left the "waiting" state, so committed files stayed out of search with nothing reporting them.+ *+ * - A stored incomplete scan used to start over whenever the source's commit moved, which on a busy source is every+ * maintenance run; it now continues its cursor and first re-examines the paths before the cursor that changed.+ * - The maintenance phase scanned sources in id order under one shared deadline, so the first large source used it up+ * on every run; sources now run least recently scanned first, each within a budget sized to its pages.+ * - A sync pass consumed the re-screen requests only when it stamped, so one that stopped first (timeout,+ * writer_pending, not_converged) imported the files and left them reported as waiting; it now consumes each request+ * once it settles the path, and doctor counts a scheduled path with a page or a hold as settled.+ */+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 { 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 { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { readGitHoldRetryPaths, requestGitHoldRetry } from '../src/core/persistence/sync-holds.ts';+import { readUnindexedFiles, refreshUnindexedFiles, unindexedBudgetForPages } from '../src/core/persistence/unindexed-files.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-7149-'));+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`;++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, prefix: string, files: Record<string, string>) {+ const id = `${prefix}-${randomUUID().replace(/-/g, '').slice(0, 12)}`, root = join(home, id);+ const write = (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ for (const [path, content] of Object.entries(files)) write(path, content);+ commit(root);+ await unmanaged(engine, () => engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}'::jsonb)", [id, root]));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ 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 });+ /** Committed files an older gbrain refused without a hold: the source's commit moves past them and no sync imports them. */+ const legacy = async (added: Record<string, string>) => {+ for (const [path, content] of Object.entries(added)) write(path, content);+ const head = commit(root);+ await unmanaged(engine, () => engine.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [id, head]));+ return head;+ };+ const incarnation = async () => (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]))[0]!.incarnation;+ const doctor = async (): Promise<Check> => (await unindexedFilesEntry.run({ engine, sourceIds: [id] } as unknown as DoctorContext) as Check[])[0]!;+ return { id, root, sync, legacy, incarnation, doctor };+}++async function each(run: (engine: BrainEngine) => Promise<void>) {+ await withEnv(env, async () => {+ for (const engine of engines) {+ try { await run(engine); } finally { await disposePersistenceConsumer(engine); }+ }+ });+}++const files = (prefix: string, n: number) => Object.fromEntries(Array.from({ length: n }, (_, i) => [`${prefix}/f${String(i).padStart(2, '0')}.md`, note(`${prefix} ${i}`)]));++test('a bounded scan converges while commits keep landing: it keeps its cursor and re-examines the changed paths before it', () => each(async engine => {+ const s = await source(engine, 'unidx7149-busy', files('notes', 20));+ await s.sync();+ await s.legacy({ 'zz/late.md': note('Late') });+ const first = await refreshUnindexedFiles(engine, s.id, { batch: 4, maxScanned: 4 });+ expect(first.record).toMatchObject({ complete: false, cursor: 'notes/f03.md', scanned: 4 });+ let record = first.record, passes = 1;+ while (!record.complete && passes < 12) {+ // Every maintenance run sees a new commit: one file lands before the cursor, one after it.+ await s.legacy({ [`notes/a${passes}.md`]: note(`Early ${passes}`), [`zz/m${passes}.md`]: note(`Mid ${passes}`) });+ record = (await refreshUnindexedFiles(engine, s.id, { batch: 4, maxScanned: 4 })).record;+ passes++;+ }+ expect(record.complete).toBe(true);+ expect(passes).toBeLessThanOrEqual(10);+ expect(record.started_at).toBe(first.record.started_at);+ expect(record.target).toBe(git(s.root, 'rev-parse', 'HEAD'));+ const expected = ['zz/late.md', ...Array.from({ length: passes - 1 }, (_, i) => [`notes/a${i + 1}.md`, `zz/m${i + 1}.md`]).flat()].sort();+ expect([...record.pending].sort()).toEqual(expected);+ expect(record.unindexed).toBe(expected.length);+ expect([...await readGitHoldRetryPaths(engine, s.id, await s.incarnation())].sort()).toEqual(expected);+}), 240_000);++test('the maintenance phase serves the least recently scanned source first, so a source a large one starved is scanned on the next run', () => each(async engine => {+ const a = await source(engine, 'unidx7149-a', files('notes', 3));+ const b = await source(engine, 'unidx7149-b', files('notes', 3));+ await a.sync(); await b.sync();+ await a.legacy({ 'notes/legacy-a.md': note('Legacy A') });+ await b.legacy({ 'notes/legacy-b.md': note('Legacy B') });+ // A clock that moves 20 s per reading under a 50 s phase budget: the first source scanned uses the phase up.+ let clock = 1_000_000_000_000;+ const now = () => (clock += 20_000);+ const run = async () => { const start = clock; return runUnindexedFilesPhase(engine, { dryRun: false, now, deadlineAtMs: start + 150_000 + 20_000 }); };+ const skipped = (phase: Awaited<ReturnType<typeof run>>) => (phase.details.skipped as Array<{ source_id: string; reason: string }>).map(entry => entry.source_id);+ const scannedIds = (phase: Awaited<ReturnType<typeof run>>) => (phase.details.sources as Array<{ source_id: string }>).map(entry => entry.source_id);+ const first = await run();+ expect(scannedIds(first)[0]).not.toBe(b.id);+ expect(skipped(first)).toContain(b.id);+ const second = await run();+ expect(scannedIds(second)[0]).toBe(b.id);+ expect((await readUnindexedFiles(engine, [b.id])).get(b.id)).toMatchObject({ unindexed: 1, pending: ['notes/legacy-b.md'] });+}), 240_000);++test('a source gets one minute of scan budget per started 100k live pages, at most five', () => {+ expect([0, 1, 100_000, 100_001, 245_000, 311_000, 2_000_000].map(unindexedBudgetForPages)).toEqual([60_000, 60_000, 60_000, 120_000, 180_000, 240_000, 300_000]);+});++test('a sync pass that stops before its stamp still consumes the re-screens it settled; doctor reports the imported files ok, not waiting', () => each(async engine => {+ const s = await source(engine, 'unidx7149-stop', files('notes', 4));+ await s.sync();+ await s.legacy({ 'notes/legacy-1.md': note('Legacy 1'), 'notes/legacy-2.md': note('Legacy 2') });+ expect((await refreshUnindexedFiles(engine, s.id)).scheduled.sort()).toEqual(['notes/legacy-1.md', 'notes/legacy-2.md']);+ const abort = new AbortController();+ // The pass imports in its first round and is stopped as its second (confirming) round starts, before any stamp.+ installFaultHook(async (point, detail) => {+ if (point !== 'sync:round_start' || detail.sourceId !== s.id || (detail as { round?: number }).round !== 2) return;+ abort.abort();+ throw Object.assign(new Error('stopped before the stamp'), { name: 'AbortError' });+ });+ let result;+ try { result = await s.sync({ signal: abort.signal }); } finally { installFaultHook(undefined); }+ expect(result).toMatchObject({ status: 'partial', reason: 'timeout' });+ expect((await engine.getPage('notes/legacy-1', { sourceId: s.id }))?.title).toBe('Legacy 1');+ expect((await engine.getPage('notes/legacy-2', { sourceId: s.id }))?.title).toBe('Legacy 2');+ expect(await readGitHoldRetryPaths(engine, s.id, await s.incarnation())).toEqual([]);+ expect((await s.doctor()).details).toMatchObject({ sources: [{ source_id: s.id, state: 'ok', waiting: 0, still_unindexed: 0 }] });+}), 240_000);++test('doctor counts a scheduled path that has a page as settled even while the re-screen row still names it', () => each(async engine => {+ const s = await source(engine, 'unidx7149-row', files('notes', 2));+ await s.sync();+ await s.legacy({ 'notes/legacy.md': note('Legacy') });+ await refreshUnindexedFiles(engine, s.id);+ await s.sync();+ expect((await engine.getPage('notes/legacy', { sourceId: s.id }))?.title).toBe('Legacy');+ await requestGitHoldRetry(engine, s.id, await s.incarnation(), ['notes/legacy.md']);+ expect((await s.doctor()).details).toMatchObject({ sources: [{ source_id: s.id, state: 'ok', waiting: 0, still_unindexed: 0 }] });+}), 240_000);