Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): image pages on a managed multimodal brain get their image vector (#6529)
garrytan55f53f6b1d1e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bb9e2da9a2..ec1cfd9715 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.180.0] - 2026-10-12++**Image pages on a managed multimodal brain get their image vector (#6529).** With `GBRAIN_EMBEDDING_MULTIMODAL=true`, a managed `gbrain sync` now imports image files through the coordinated image importer instead of holding every one as `managed_image_sync_unsupported`, so the page is created with its OCR text, its image vector and its `source_path` in the same publication; holds from earlier syncs are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. `gbrain embed --stale --images` works on a managed brain (it used to be refused by the legacy writer), finds the image pages whose `source_path` was never recorded through their slug, and a plain `gbrain embed --stale` runs that sweep first on a multimodal install. Doctor's new `image_embedding_coverage` check reports the image pages search cannot see, which `embed_coverage_pct` counted as embedded. No migration; the image vector and OCR text are the paid calls the importer already made for `gbrain import`, now also made at sync and sweep time. Image pages whose file is no longer in the checkout are not re-imported: the sweep names the first path it tried and exits non-zero when it could rebuild nothing.++### Itemized changes++- **Managed sync imports images when multimodal embedding is on.** `freezeEntry` freezes an image entry as its bytes in base64 (binary-safe reads through `readPinnedBytes` / `readBlobBytes`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged; an oversize image takes the `file_too_large` hold), `prepareManagedSyncMutation` routes it to `src/core/persistence/sync-image.ts`, and `prepareManagedSyncImage` runs `importImageFile` with `prepare`, the same coordinated path `gbrain import` uses: the importer decides the hash no-op before any provider call, OCRs and embeds otherwise, `--no-embed` skips both, a company plan refuses, a Git rename publishes the new slug and retires the old page. A screening preparation never pays for an image: the no-op waiver and `unchangedManagedImport` leave image paths to the admitted request, and identical bytes are a no-op by hash. `holdRescreenDue` re-screens a `managed_image_sync_unsupported` hold whenever multimodal embedding is on; with it off the hold's message, fix and the runbook row now say images are held while multimodal embedding is off and name the switch. Tests: `test/managed-sync-images-5493.test.ts` (PGLite and Postgres).+- **`gbrain embed --stale --images` works on managed brains and reports honestly.** On a managed brain the sweep imports through `importManagedFile` (the coordinated importer), only files inside the source root; a page with a NULL `source_path` is located by its slug (the lower-cased repo-relative path) and the import records the path (`missingSourcePath` in the result). The result carries `missing_samples` (up to 5 `source:slug: no file at <path tried>` lines, the first printed to stderr), and a sweep whose every candidate lacks a file and that rebuilt nothing counts them as failures, so it exits non-zero instead of 0. Plain `gbrain embed --stale` (no `--slugs`) runs the sweep first on a multimodal install, inside the same cost cap, and folds it into the result as `images`; the blocked-projection hint points at that sweep's samples, or at `GBRAIN_EMBEDDING_MULTIMODAL=true` on a text-only install. Tests: `test/embed-stale-images-managed-6529.test.ts`.+- **Doctor `image_embedding_coverage`.** Counts live image pages, those without an `embedding_image` chunk, those with no recorded `source_path`, and the `managed_image_sync_unsupported` holds; ok with no image pages or with multimodal embedding off (informational), warns on a multimodal install with the counts and the `embed --stale --images` / `sync --no-pull` fix. Read-only. Test: `test/doctor-image-embedding-coverage.test.ts`.+- **Every image import records `source_path`.** The legacy importer's hash-skip path (`importImageFile` on an unchanged, complete image) now refreshes `source_path` the way the Markdown path does, so a re-import of an older page records the origin it never had. Pages imported before this release keep a NULL `source_path` until the sweep or a sync writes it.+## [0.60.178.0] - 2026-10-12**Batch entity lookups respect quarantine.** `entity` with `names` now hides quarantined pages from remote callers the way a single-name `entity` lookup and `get_page` already do, whichever way the name resolves, and a quarantined identity sibling no longer appears beside a page for remote callers, in batch rows or in a single-name card. Trusted local callers see the same results as before. No migration, no paid call.diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 37322dc742..6dd512a660 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -132,6 +132,7 @@ src/commands/schema.ts 0 filesystem_guard Schema manifest scaffolding and forkssrc/core/ingestion/sources/inbox-folder.ts 0 filesystem_guard Inbox archive moves refuse managed canonical input paths before emitting the event or moving source bytes.src/core/persistence/links-preparation.ts 2 coordinator Automatic graph projections publish inside canonical page transactions; delayed reconciliation locks all affected page keys and compares the originating revision.src/core/persistence/sync-prepare.ts 8 coordinator Managed imports and deletes validate the recorded raw file hash plus enumerated page identity/revision; a managed rename moves the page with updateSlug and re-infers an implicit type inside the same journal publication after the renamed page's identity and revision are rechecked; the source-exclusive final checkpoint requires every selected receipt to be committed. Its importFromContent calls carry prepare and run inside the coordinator publication. The checkpoint also stamps sources.chunker_version after a full walk (#5566), inside the same source-exclusive publication; the column is outside managed_writer_guard's protected checkpoint tuple.+src/core/persistence/sync-image.ts 2 coordinator The managed sync image branch prepares through importImageFile with prepare and applies inside the coordinator publication after the sync-wide and import validations rerun; a Git rename versions and soft-deletes the old slug's page in that same transaction, and source_path is stamped there too.src/core/persistence/sync-run.ts 1 coordinator The managed up-to-date heartbeat stamps only sources.last_sync_at inside withCoordinatedWrite, scoped to the checked source id and incarnation; no checkpoint, commit or content-freshness column changes.src/commands/enrich.ts 0 coordinator A managed brain preflights maintenance authority before any model spend and publishes each enriched page through publishMaintenancePage; unmanaged enrichment writes through the put_page operation.src/core/persistence/source-lifecycle.ts 7 coordinator Native affected roots precede topology, source, principal and receipt guards; every shared-root generation and old queued intent changes together.diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex 7fe0ca6387..b9cedb4193 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -13,10 +13,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE` (= `BUDGET_STOP_EXIT_CODE` 11; was 3, which A3 reserves for confirmation_required) unless `stopped: drained` with `remaining: 0` (a null count is exit 11, never a drained success; `--json` adds `resume_command`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `--stale` progress (#5968) is exact chunk accounting through `src/core/embed-stale-progress.ts`: `onProgress(done, total, embedded)` carries cumulative stale chunks against a total that grows by heal splits, behind-cursor rows and re-entries, the CLI ticks `embed.pages` by the delta and forwards the grown total with `setTotal`, and `done <= total` holds at every callback. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. Its result prints from `runEmbed` only without `--json`; under `--json` the CLI dispatch writes the one document. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`. #6223: pages still blocked after bounded projection recovery no longer end `--stale` early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with `gbrain embed --stale --images` / `gbrain sync --full` for image and media pages. Fix wave 13 P1.18 (#6400): `runEmbed` takes the CLI's consent outcome; a finite approved `cap_usd` runs the foreground text and `--images` paths under `embedCostCap` (`src/core/embed-cost-cap.ts`) and returns `reason: 'cost_cap'` (exit `BUDGET_STOP_EXIT_CODE` from `src/cli/commands/embed.ts`, which now returns the Authorization from `authorizeEmbed`); `--background` stores it on the row through `maybeBackground(...spendAuthorization)` (PGLite runs inline, metered). `--slugs` takes the arguments up to the next flag. Tests: `test/embed-max-usd-metered.serial.test.ts`, `test/e2e/embed-background-cap.test.ts`.+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `--stale` progress (#5968) is exact chunk accounting through `src/core/embed-stale-progress.ts`: `onProgress(done, total, embedded)` carries cumulative stale chunks against a total that grows by heal splits, behind-cursor rows and re-entries, the CLI ticks `embed.pages` by the delta and forwards the grown total with `setTotal`, and `done <= total` holds at every callback. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. Its result prints from `runEmbed` only without `--json`; under `--json` the CLI dispatch writes the one document. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`. #6223: pages still blocked after bounded projection recovery no longer end `--stale` early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with `gbrain embed --stale --images` / `gbrain sync --full` for image and media pages. Fix wave 13 P1.18 (#6400): `runEmbed` takes the CLI's consent outcome; a finite approved `cap_usd` runs the foreground text and `--images` paths under `embedCostCap` (`src/core/embed-cost-cap.ts`) and returns `reason: 'cost_cap'` (exit `BUDGET_STOP_EXIT_CODE` from `src/cli/commands/embed.ts`, which now returns the Authorization from `authorizeEmbed`); `--background` stores it on the row through `maybeBackground(...spendAuthorization)` (PGLite runs inline, metered). `--slugs` takes the arguments up to the next flag. Tests: `test/embed-max-usd-metered.serial.test.ts`, `test/e2e/embed-background-cap.test.ts`. #6529: `runEmbed` with `--stale` (no `--slugs`) first runs `runStaleImageSweepFirst` (`core/embed-stale-images.ts`, multimodal installs only) inside the same cost cap and folds it into `EmbedResult.images`; the text pass's blocked-projection hint (`core/embedding-readiness.ts`) then points at that sweep's `missing_samples` instead of a separate `--images` command, and at `GBRAIN_EMBEDDING_MULTIMODAL=true` or `--images` / `sync --full` on a text-only install.- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob.- `src/commands/doctor/checks/atom-holds.ts` — `extract_atoms_held_failed` (#6325, BRAIN, registered before `fence_integrity`). Lists `listHeldManagedAtoms` (`persistence/atom-maintenance.ts`): managed atom pages and transcripts held after `MAX_DETERMINISTIC_FAILURES` failed extractions of their current content (code `held_failed`) that no later run completed, each with its last request id, failure, `receipt_command` and `retry_command`. Warns with a paid `fix` (the reviewed `gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'` retry of the first item). Local doctor only; `run_doctor` does not include it. Tests: `test/managed-atoms-retry.test.ts`.- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. Test: `test/doctor-fence-integrity.test.ts`.- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.+- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 072be1e307..49679ac62f 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -8,6 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sync-applicability.ts` — agent-first operator wave E4. `syncContentDirectory(engine, {sourceId, repoPath})` resolves the sync root exactly as `performSync` does and returns it when it is a gbrain-owned content directory (under `<GBRAIN_HOME>/.gbrain/content/`, or an owned `--content-root` recorded in the shared-skills setup receipt) with no `.git` at the root; null otherwise (fail-open). `performSync` calls `assertSyncApplicable` first, so such a source refuses with `sync_not_applicable` (reason `content_directory`, fix `gbrain import <dir> [--no-embed] --source <id>`, `git init` named only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal could `git init` it. `sync --all` skips these sources with one line; the dream cycle's sync phase reports them `skipped` (`details.reason: sync_not_applicable`). The CLI `sync` record renders fix-carrying OperationErrors through `renderCliError` (`src/cli/commands/sync.ts`). Pinned by `test/sync-applicability.test.ts`.- `src/core/sync-upstream.ts` — upstream observation for remote-tracking sources (#5255/#5176). `observeUpstream(root, syncedCommit)` reads the checkout's `@{upstream}` commit, the newer of the `FETCH_HEAD` and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and `rev-list --count` of upstream commits the synced commit lacks; `recordUpstreamObservation` (called by `performSync` in `src/commands/sync/perform.ts` after every non-dry-run legacy or managed sync, best-effort) writes them to `sources.upstream_checked_at` / `upstream_commit` / `upstream_behind`, which `managed_writer_guard` does not protect. `upstreamFreshness` is doctor `sync_freshness`'s separate "upstream checked" verdict (a `remote_url` source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. `managedPullWarning` / `UpstreamRefresh` back the cycle sync phase (`runPhaseSync` in `src/core/cycle.ts`), which runs a managed `pull: true` as no-pull and reports `details.upstream_refresh` (`pulled|failed|skipped_managed|not_requested`) plus a `managed_pull_skipped` warning when the checkout tracks an upstream. A managed brain's fix (the warning and doctor's behind/unknown verdict) is `gbrain sources refresh <source>`; an unmanaged one's is `gbrain sync --source <source>`. Tests: `test/managed-cycle-pull-upstream.test.ts`, the pull row of `test/managed-phase-matrix.test.ts`.-- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`, `RESOLVER.md`, skipped at any depth); `SYNC_ROOT_SKIP_FILES` (#5186, W14 P1.5b) adds the bootstrap scaffolding `AGENTS.md` / `CLAUDE.md` at depth 0 only, and `isSyncMetafile(path)` is the one predicate `classifySync` and the bulk-import collector (`commands/import.ts`) share (the managed effect scan's `isMetafilePage` in `persistence/effects.ts` still reads `SYNC_SKIP_FILES` directly), so an earlier-indexed root `agents` page survives under the #1433 guard (`test/sync-root-agents-metafile.test.ts`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped.+- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`, `RESOLVER.md`, skipped at any depth); `SYNC_ROOT_SKIP_FILES` (#5186, W14 P1.5b) adds the bootstrap scaffolding `AGENTS.md` / `CLAUDE.md` at depth 0 only, and `isSyncMetafile(path)` is the one predicate `classifySync` and the bulk-import collector (`commands/import.ts`) share (the managed effect scan's `isMetafilePage` in `persistence/effects.ts` still reads `SYNC_SKIP_FILES` directly), so an earlier-indexed root `agents` page survives under the #1433 guard (`test/sync-root-agents-metafile.test.ts`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped. `isMultimodalEnabled(env)` (`GBRAIN_EMBEDDING_MULTIMODAL=true`) is the one predicate managed discovery, the hold re-screen, `embed --stale`, the blocked-projection hint and doctor `image_embedding_coverage` read for whether images are imported and embedded.+- `src/core/persistence/sync-image.ts` — #6529: managed sync's image branch. With multimodal embedding on, `freezeEntry` (`sync-run.ts`) freezes an image entry as its bytes in base64 (`frozenImageIntent`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged) and `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncImage`, which runs `importImageFile` with `prepare` (the coordinated path `gbrain import` uses in `import-prepare.ts`): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (`--no-embed` skips both; the caption chunk's text vector is deferred to `embed --stale`), and the apply records `source_path`, releases the path's hold and re-reads the snapshot. A company plan refuses (`profile_incompatible`), a screening preparation (`sameContentAtOrigin`, the no-op waiver in `sync-waivers.ts` and `unchangedManagedImport` in `import-mutations.ts` return early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refuse `source_changed`, and a Git rename publishes the new slug and soft-deletes the old page. `import-file.ts` records `source_path` on the legacy importer's hash-skip path too (`refreshSourcePath`), so no image import leaves it NULL. Tests: `test/managed-sync-images-5493.test.ts` (both engines), `test/embed-stale-images-managed-6529.test.ts`.- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?, expectedFileBytes?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 812221de78..bd2321da70 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -19,7 +19,7 @@- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) cancels a head whose predecessor ended without committing, and under lanes a member whose predecessor is unfinished releases its claim and waits; `cancelOrphanedLaneRows` uses the same rule, so a member released mid-group (its group fell back to the single path and an earlier member went back to the queue) never publishes after that member fails. Test: `test/sync-group-member-order.test.ts`. #6402: a group head whose window predecessor was not admitted is cancelled naming it.- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out.-- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `screenFrozenImport` admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.+- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence and slug-conflict holds (`HoldRepairRoute.fences` + `slug_conflicts`) preview the content-repair lane, `gbrain repair content --source <id>` (`contentRepairArgv`, #6377; the text says the next maintenance run repairs the fence and slug-conflict holds it can by itself when `FenceAutoRepair.active`), other holds preview `gbrain repair frontmatter`, a mixed source names both; one fence hold's own fix stays that file's `gbrain repair fences --only <path>` preview (`fenceHoldFix`). One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). #6278: `preparation_stalled` holds carry `meta.stall` (request, step, `waiting_on`, attempts, the writing gbrain version, the sync's resume arguments) and count under `stalled` in the summary row and `HoldRepairRoute`; `gitHoldFix` routes them to `gbrain sources writer status --source <id> --json`, then `sources retry-held`, then the option-preserving sync (`stalledHoldSteps`), never to frontmatter repair, and `holdRescreenDue` re-screens them on a gbrain version change; `buildHoldReport` routes the escalation text by code. `screenFrozenImport` admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`; `freezeEntry` reads each entry's pinned blob and content through `readPinnedBlob` / `readPinnedContent` (via `sync-screen.ts` `pinnedBlob` / `pinnedContent`): a miss lists that entry and up to 255 of the next committed imports in one `ls-tree` and loads their contents (8 MiB slices cut by window position, not read order; over-bound blobs excluded) in one `cat-file --batch`, kept per (Git root, full commit id) until the next window, so a managed first sync spawns a few Git processes per window instead of an `ls-tree` and a `git show` per page; a non-commit target, a window git refuses to list, or a blob the window cannot answer falls back to the per-entry read (`__setPinnedWindowForTests(0)` restores per-entry reads; `test/managed-sync-pinned-reads.test.ts` proves identical rows on PGLite and Postgres). `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; `stalled` coverage routes a `preparation_stalled` hold to the host operator's writer-status fix instead of a file repair; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493/#6529: managed discovery admits image imports whenever multimodal embedding is on (company plans refuse). Off, `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, dry-run screen too) before any content read, whatever `sync.holds` says: the rest of the source imports, the hold is keyed by the pinned blob (or working bytes), and `holdRescreenDue` re-screens it on change, removal, multimodal on or `sources retry-held`. On, `freezeEntry` freezes the bytes as base64 (`pinnedImageBytes`, `frozenImageIntent`), an oversize image takes `oversizeHold`, identical bytes are a no-op by hash, and `sync-prepare.ts` routes the entry to `sync-image.ts`. The summary row counts `images`; those holds never count toward `holds_escalated` or `git_held_files`.- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). `managedRepairRoot` resolves the owner through `checkOwner` (`owner-refusal.ts`) and refuses `owner_unavailable` with the condition as its reason; `submitManagedFileRepair` re-reads the source's `RepairBusySet` (`repair-busy.ts`) right before admission and refuses `sync_in_progress` when a write in flight or an unfinished sync's frozen manifest names the path, origin, slug or a rename endpoint (#6278: a sync can start while a fence repair waits on its model call). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`. `syncGitTopLevel` answers the checkout's `git rev-parse --show-toplevel` once per root and sync run, reading it again when the top level's `.git` entry is replaced or removed or a `.git` appears between it and the root. #6278: `prepareManagedSyncMutation` calls `enterClaimStep` at each await boundary (`managed_sync_active`, `authority`, `worktree_binding`, `configured_root`, `knowledge_publication`, `manifest_entry`, `git_rev_parse`, `origin_check`, `page_snapshot`, `import_screen`, `import_content`, `canonical_projections` and the rest, each naming `git`, `fs` or `db` where it knows), so a stall reports its step; the consumer's budget and the cancellation reaching those boundaries are in persistence-stalls.md.- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 8924b934ce..fc38dc5d7b 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embed-skip.ts` — 5-site shared predicate for the soft-block embed-skip filter. Exports `shouldSkipEmbedding(frontmatter): boolean` (JS predicate for callers holding the page in memory), `EMBED_SKIP_SQL_FRAGMENT` (parameterized SQL clause shared by Postgres + PGLite via `executeRaw`), and `buildEmbedSkipMarker(reason: string)` (writes `frontmatter.embed_skip = {at: ISO_TIMESTAMP, reason}` so the JSONB shape stays uniform). The 5 sites: `embed.ts --stale`, `embed.ts --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks`. Single source of truth so the filter cannot drift. Pinned by `test/embed-skip.test.ts` (cross-site invariant + JSONB shape).- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines. #5902: without an explicit `concurrency`, `embedStaleForSource` (the unpaced `embed-backfill` job and the remediation embed step) runs `resolveStaleEmbedConcurrency` workers from `src/core/embed-concurrency.ts`: `min(20, max(1, floor(poolMax/2)))` of the engine's real pool (`getPoolDiagnostics().poolMax`, a worker's instance pool included), 20 without a pool; an explicit `GBRAIN_EMBED_CONCURRENCY` keeps the full-pool clamp. Pinned by `test/embed-stale-pool-default.test.ts` + `test/e2e/embed-stale-pool-default-postgres.test.ts`.-- `src/core/embed-stale-images.ts` — `gbrain embed --stale --images [--source <id>] [--dry-run] [--json]` (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`): selects live image pages whose index `importImageFile`'s hash-skip would call incomplete (unsealed or stale projection, no `embedding_image` chunk, or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true`), resolves each file from the source's `local_path` (the `default` source falls back to `sync.repo_path`; a subpath-scoped `source_path` resolves against the checkout's git root) and hands it back to `importImageFile`, so OCR budget, protected-OCR refusal and the rebuild stay in the importer. Reports candidates, rebuilt, unchanged, missing source files and failures (`failures > 0` exits non-zero). Pinned by `test/embed-stale-images.test.ts`. Under a cost cap (fix wave 13 P1.18) each import is metered and the sweep stops before the next image once the cap refused; a refused image is not a failure.+- `src/core/embed-stale-images.ts` — `gbrain embed --stale --images [--source <id>] [--dry-run] [--json]` (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`): selects live image pages whose index `importImageFile`'s hash-skip would call incomplete (unsealed or stale projection, no `embedding_image` chunk, or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true`), resolves each file from the source's `local_path` (the `default` source falls back to `sync.repo_path`; a subpath-scoped `source_path` resolves against the checkout's git root; a page with no recorded `source_path` is located by its slug, which is the lower-cased repo-relative path, and counted in `missingSourcePath`) and hands it back to the importer, so OCR budget, protected-OCR refusal and the rebuild stay there. #6529: on a managed brain the import goes through `importManagedFile` (the coordinated importer; the legacy writer refuses a managed brain), only for a file inside the source root, and the import records `source_path`. Reports candidates, rebuilt, unchanged, missing source files (`missing_samples`: up to 5 `source:slug: no file at <path tried>` lines, the first printed) and failures; a sweep whose every candidate lacks a file and that rebuilt nothing counts those as failures, so it never exits 0 as a quiet success. `runStaleImageSweepFirst` is the sweep a plain `gbrain embed --stale` (no `--slugs`) runs before its text drain when multimodal embedding is on, and `foldImageSweep` folds it into the `EmbedResult` as `images` (its failures count); a text-only install skips it and keeps the `--images` hint. Pinned by `test/embed-stale-images.test.ts` and `test/embed-stale-images-managed-6529.test.ts` (both engines). Under a cost cap (fix wave 13 P1.18) each import is metered and the sweep stops before the next image once the cap refused; a refused image is not a failure.- `src/core/embed-budget-stop.ts` — the loud time-budget stop for `gbrain embed --stale`. `noteEmbedBudgetStop(engine, result, {sourceId, signature, includeNullSignature, skip})` counts the stale chunks left (same predicate as the catch-up remaining count) and, when any remain, sets `reason: 'time_budget'`, `remaining_stale` and `resume_command` (`gbrain embed --stale --catch-up [--source X] [--include-null-signature]`) on the result; `skip` covers dry runs, `--catch-up` and caller aborts. `embedBudgetStopVerdict(result)` is the stdout verdict `runEmbed` prints; `src/cli/commands/embed.ts` maps the reason to `BUDGET_STOP_EXIT_CODE` (failures still win with 1). Called from every budget exit in `embedAllStale` (readiness-phase deadline returns and the main drain). Pinned by `test/embed.serial.test.ts` ("time-budget stop is loud").- `src/core/embed-cost-cap.ts` — fix wave 13 P1.18 (from #6400): the approved `--max-usd` (or derived/default) cap of a foreground `gbrain embed`. `embedCostCap(cap, source)` builds a BudgetTracker plus an AbortController; the first refused reservation aborts the run's signal before the refusal propagates, so page/batch catches treat it as shutdown (no failure, quarantine strike or per-chunk fan-out) and installed vectors stay banked. `noteEmbedCostStop` records `reason: 'cost_cap'`, `budget_reason` (`cost`/`no_pricing`), cap, spend and the resume command (the run without its approval flags); `embedCostStopVerdict` is the stdout line (stderr under `--json`). The gateway side: `embedMultimodal` reserves before any provider call (each image at `MULTIMODAL_IMAGE_TOKEN_CEILING`, Voyage's 16M-pixel maximum at 560 pixels per token) and settles at Voyage's reported `usage.total_tokens`; `generateOcrText` reserves and sends `maxOutputTokens: OCR_MAX_OUTPUT_TOKENS`, the bound it reserved (`test/gateway-ocr-reserve.test.ts`).diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 76998e0b3f..39402c92e1 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -269,6 +269,7 @@ or a physical projection that leaves attribution untouched):- `src/core/persistence/page-prepare.ts` (6): page request preparer.- `src/core/persistence/prepared-maintenance.ts` (4): managed maintenance request preparer.- `src/core/persistence/semantic-pages.ts` (1): `add_timeline_entry` request preparer.+- `src/core/persistence/sync-image.ts` (2): managed sync image request preparer; a Git rename retires the old page inside the same publication.- `src/core/persistence/sync-prepare.ts` (4): managed sync request preparer.- `src/core/persistence/takes-prepare.ts` (3): takes request preparer.- `src/core/repair/captured-facts.ts` (1): a request on managed brains; the unmanaged captured-facts expiry runs in `maintenanceTransaction`.diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex b9b2b7b636..ef3ebda2d6 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -92,7 +92,7 @@ Every hold and error has three fields, from one table| `file_too_large` | page | none | yes | always || `content_rejected` | page | none | yes | always || `parser_regression` | page | upgrade | yes | always: a gbrain bug |-| `managed_image_sync_unsupported` | page | none | no | never: images stay held by design |+| `managed_image_sync_unsupported` | page | none | no | never: images stay held while multimodal embedding is off || `revision_conflict` | page | retry | no | the same path fails again after a rerun || `page_identity_changed` | page | retry | no | the same path fails again after a rerun || `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 996143692c..328050cbf4 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -155,7 +155,7 @@ with each file and fix the ones that need no guessing."*| <a id="invalid_frontmatter-ambiguous_protected_key"></a>`invalid_frontmatter` (`ambiguous_protected_key`) | A key that decides access or provenance (`visibility`, `derived_from`, …) is malformed, duplicated, swallowed into another value, rewritten by quoting, or inside an unclosed fence. gbrain never reads such a key as a broader value. | Edit the file by hand: write the key on one line with one quoted value. Ask the user which visibility is intended; never guess it. || <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. The hold has three outcomes once the content-repair lane's `slug-conflicts` kind runs it (the maintenance run's `content_repair` phase, `gbrain sync unblock --apply`, or `gbrain repair content --source <source>`): **removed** (the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token: the stray `slug:` line is removed, the file imported and committed, the hold cleared, with a receipt; a model under the `fences.repair` caps makes the same call when the two pages are not obviously different), **merge recommended** ([`merge_recommended`](#merge_recommended): the two files describe the same thing; gbrain recommends the merge and names the canonical page but never merges pages by itself), or **undecided** ([`content_repair_needs_human`](#content_repair_needs_human)). Until that kind ships, the lane leaves the hold to the frontmatter repair preview below. | Nothing to run when the lane removes the line: the hold clears on the sync it prints. For a recommendation or an undecided hold, `gbrain sync status --source <source> --json` carries the paragraph (`human_reason`): merge the unique sections into the canonical page by hand or decide which page keeps the slug, delete or edit the file, commit, then `gbrain sync --source <source> --no-pull`. By hand at any time: remove the `slug:` line or make it match the path, or move the file to the path its slug names (`gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line, for approval). || <a id="file_too_large"></a>`file_too_large` | Over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read). The limit is fixed. | Split the file into smaller files and commit, or leave it out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`. The next `gbrain sync --source <source> --no-pull` clears the hold. |-| <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | With multimodal embedding on (`embedding_multimodal` / `GBRAIN_EMBEDDING_MULTIMODAL`), sync admits image files, but managed sync has no image importer yet. Each image import is held instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken; keeping them held is fine. To stop holding images, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`) or turn multimodal embedding off; either clears the holds on the next `gbrain sync --source <source> --no-pull`. A held image is re-screened when it changes and on `gbrain sources retry-held <source>`. |+| <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | Managed sync imports image files only while multimodal embedding is on (`GBRAIN_EMBEDDING_MULTIMODAL=true`): the image page, its OCR text and its image vector are built by the coordinated image importer at preparation, and `source_path` is recorded. While multimodal embedding is off, each image import is held with this code instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken. To import the images, set `GBRAIN_EMBEDDING_MULTIMODAL=true` on the owner and run `gbrain sync --source <source> --no-pull`: the next discovery re-screens every image hold and imports the files (#6529). To stop holding them instead, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`); that clears the holds on the next sync. A held image is also re-screened when it changes and on `gbrain sources retry-held <source>`. || <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. || <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host. See [expire versus purge](memory-boundaries.md#purge). || <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. |diff --git a/llms-full.txt b/llms-full.txtindex d19692b31f..1d5e00fc31 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -7021,7 +7021,7 @@ Every hold and error has three fields, from one table| `file_too_large` | page | none | yes | always || `content_rejected` | page | none | yes | always || `parser_regression` | page | upgrade | yes | always: a gbrain bug |-| `managed_image_sync_unsupported` | page | none | no | never: images stay held by design |+| `managed_image_sync_unsupported` | page | none | no | never: images stay held while multimodal embedding is off || `revision_conflict` | page | retry | no | the same path fails again after a rerun || `page_identity_changed` | page | retry | no | the same path fails again after a rerun || `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |diff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjsindex 6c1f8e6b76..f640bc5466 100644--- a/scripts/check-core-guard-coverage.mjs+++ b/scripts/check-core-guard-coverage.mjs@@ -28,6 +28,7 @@ const EXEMPT = {'src/core/persistence/file-repair.ts': 'publishes bytes the owner approved with gbrain repair frontmatter --apply','src/core/persistence/grandfather.ts': 'adopts pages that already exist at activation; no content change','src/core/persistence/import-prepare.ts': 'owner-run local import (gbrain import); doctor reports any overage',+ 'src/core/persistence/sync-image.ts': 'owner git edits (managed sync image branch, prepared through importImageFile as import-prepare.ts is); doctor core_memory reports any overage','src/core/persistence/connector-sync.ts': 'connector-owned pages; core marking is owner-written frontmatter the connector never sets','src/core/persistence/connector-google-receipts.ts': 'connector receipt rows, not page text','src/core/persistence/projection-reindex.ts': 'rebuilds derived projections; page text is unchanged',diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e1859121e8..2e6873a30a 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -17,7 +17,7 @@ src/core/cycle.ts 3303 ratchet +2 System One v1 S9: extract_facts phase tail runsrc/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog countsrc/core/engine.ts 2787 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts)-src/core/import-file.ts 2025 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured)+src/core/import-file.ts 2027 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)src/core/pglite-engine.ts 3026 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts)diff --git a/src/commands/doctor/checks/image-embedding-coverage.ts b/src/commands/doctor/checks/image-embedding-coverage.tsnew file mode 100644index 0000000000..6d039473b0--- /dev/null+++ b/src/commands/doctor/checks/image-embedding-coverage.ts@@ -0,0 +1,63 @@+/**+ * #6529 `image_embedding_coverage`: the image side of search, reported apart+ * from text coverage. Image pages carry a text vector (their caption or OCR+ * projection), so `embed_coverage_pct` reads as done while the image vector+ * (`content_chunks.embedding_image`) is missing and image search never works.+ * Counts live image pages without an image vector, image pages whose+ * `source_path` was never recorded (the sweep finds them by slug), and the+ * images managed sync holds as `managed_image_sync_unsupported`. Warns only+ * on a multimodal install (`GBRAIN_EMBEDDING_MULTIMODAL=true`): without the+ * image provider the counts are informational.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { isMultimodalEnabled } from '../../../core/sync.ts';+import { readGitImageHoldCounts } from '../../../core/persistence/sync-holds.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';++export async function imageEmbeddingCoverageCheck(engine: BrainEngine): Promise<Check> {+ const name = 'image_embedding_coverage';+ try {+ const [row] = await engine.executeRaw<{ image_pages: number | string; without_image_vector: number | string; null_source_path: number | string }>(+ `SELECT count(*)::int AS image_pages,+ count(*) FILTER (WHERE NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id AND c.embedding_image IS NOT NULL))::int AS without_image_vector,+ count(*) FILTER (WHERE p.source_path IS NULL)::int AS null_source_path+ FROM pages p WHERE p.page_kind = 'image' AND p.deleted_at IS NULL`);+ const sources = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived');+ const holds = await readGitImageHoldCounts(engine, sources.map(source => source.id));+ const unsupportedHolds = [...holds.values()].reduce((sum, count) => sum + count, 0);+ const multimodal = isMultimodalEnabled();+ const details = { image_pages: Number(row?.image_pages ?? 0), without_image_vector: Number(row?.without_image_vector ?? 0),+ null_source_path: Number(row?.null_source_path ?? 0), unsupported_holds: unsupportedHolds, multimodal };+ if (details.image_pages === 0 && unsupportedHolds === 0) return { name, status: 'ok', message: 'No image pages indexed yet.', details };+ const parts = [`${details.without_image_vector} of ${details.image_pages} image page(s) have no image vector`,+ ...(details.null_source_path ? [`${details.null_source_path} with no recorded source_path`] : []),+ ...(unsupportedHolds ? [`${unsupportedHolds} held as managed_image_sync_unsupported`] : [])];+ if (!multimodal) {+ return { name, status: 'ok', details, message: `${parts.join('; ')}. Multimodal embedding is off (GBRAIN_EMBEDDING_MULTIMODAL), so image search is not expected to work; `+ + 'text coverage of these pages is counted with the other pages.' };+ }+ if (details.without_image_vector === 0 && unsupportedHolds === 0 && details.null_source_path === 0) {+ return { name, status: 'ok', details, message: `All ${details.image_pages} image page(s) have an image vector.` };+ }+ return { name, status: 'warn', details, message: `${parts.join('; ')}. Text coverage counts these pages as embedded, but image search does not see them. `+ + 'Fix: run gbrain embed --stale --images (gbrain embed --stale runs it first on this install; a page with no source_path is found by its slug and gets it recorded), '+ + 'and gbrain sync --no-pull --source <id> imports held images now that multimodal embedding is on.' };+ } catch (e) {+ return { name, status: 'warn', message: `image embedding coverage scan skipped: ${e instanceof Error ? e.message : String(e)}` };+ }+}++async function runImageEmbeddingCoverage(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ ctx.progress.heartbeat('image_embedding_coverage');+ const check = await imageEmbeddingCoverageCheck(connectedEngine(ctx));+ checks.push({ name: 'image_embedding_coverage', status: check.status, message: check.message, ...(check.details ? { details: check.details } : {}) });+ return checks;+}++export const imageEmbeddingCoverageEntry: DoctorEntry = {+ name: 'image_embedding_coverage',+ emits: ['image_embedding_coverage'],+ run: runImageEmbeddingCoverage,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 6a0f9bed2c..dbefaed85c 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -79,6 +79,7 @@ import {salienceEntry,} from './checks/knowledge-health.ts';import { queueHealthEntry, indexAuditEntry, imageAssetsEntry } from './checks/queue-assets.ts';+import { imageEmbeddingCoverageEntry } from './checks/image-embedding-coverage.ts';import { globalMaintenanceTimeoutsEntry } from './checks/global-maintenance-timeouts.ts';import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';@@ -173,6 +174,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [grantNewOpsEntry,indexAuditEntry,imageAssetsEntry,+ imageEmbeddingCoverageEntry,syncFreshnessEntry,gitConvergenceEntry,decideHealthEntry,diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex a13fe6a3ac..5f6a3314c3 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -322,6 +322,8 @@ export interface EmbedResult {* misreporting embed failures.*/lock_skipped?: boolean;+ /** #6529: the image sweep a `--stale` run on a multimodal install made before its text drain (core/embed-stale-images.ts). */+ images?: StaleImageSweepResult;/*** Set when the single-flight lock heartbeat discovered the lock was stolen* (refresh matched 0 rows) or kept erroring: mutual exclusion is gone, so@@ -994,7 +996,9 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConfif (costCap) opts.signal = costCap.signal;try {- const result = costCap ? await costCap.metered(() => runEmbedCore(engine, opts)) : await runEmbedCore(engine, opts);+ // #6529: a multimodal install rebuilds its image pages first, inside the same cap (lazy: keeps import-file out of embed's graph).+ const images = stale && slugsIdx < 0 ? await (await import('../core/embed-stale-images.ts')).runStaleImageSweepFirst(engine, { sourceId, dryRun, costCap }) : null;+ const result = (await import('../core/embed-stale-images.ts')).foldImageSweep(costCap ? await costCap.metered(() => runEmbedCore(engine, opts)) : await runEmbedCore(engine, opts), images);if (progressDone !== null) progress.finish();const capped = costCap?.hit();if (capped) {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 13077c7ba1..3fd7bde91b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -467,6 +467,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.177.0', text: 'The atom-extraction phase (`extract_atoms`) now honors a schema pack that declares one of the built-in extractable types (meeting, source, article, video, book, original) as `extractable: false`, the way facts extraction already did: such pages are no longer mined into atoms. gbrain-base declares meeting and source extractable and is unchanged; on gbrain-recommended, `source` pages stop being atom-extracted. A pack that does not mention a built-in type keeps it extractable.' },// Fix wave 15 group 1 (managed sync authority and data safety).{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },+ // #6529 (GBRA-79). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps both rows to the release (0.60.180.0 placeholder) at the merge slot.+ { since: '0.60.178.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },+ { since: '0.60.178.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0). Doctor gains `image_embedding_coverage`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex cb7cdf1abc..ebe7d2994d 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -72,14 +72,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],+ 'init': ['--access', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--adopt-slug-path', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--dry-run', '--enable', '--exclude', '--exit-code', '--expected-epoch', '--explain', '--file', '--fix', '--follow', '--force', '--get', '--get-url', '--git-dir', '--git-path', '--grammar-diagnostics', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--manifest', '--name-only', '--no-accept-pending', '--no-cron', '--no-rebase', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--full', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex ce464d4e8d..f5d52b5594 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -133,6 +133,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['extraction_date_grounding','hidden_by_search_policy','image_assets',+ // #6529: image pages without an image vector, apart from text coverage (plus NULL source_path and held images).+ 'image_embedding_coverage','integrity','jsonb_integrity',// #4222 — near-empty entity pages that accreted huge edge counts (junkdiff --git a/src/core/embed-stale-images.ts b/src/core/embed-stale-images.tsindex b32ae2f03f..6c24233c3b 100644--- a/src/core/embed-stale-images.ts+++ b/src/core/embed-stale-images.ts@@ -9,6 +9,16 @@* sweep selects the same incompleteness `importImageFile`'s hash-skip checks* and hands each file back to it, so the rebuild, the OCR budget and the* protected-OCR refusal all stay in one place.+ *+ * #6529: on a managed brain the file goes through the source's canonical owner+ * (`importManagedFile`, the same coordinated path `gbrain import` takes) instead+ * of the legacy writer, which a managed brain refuses. A page whose+ * `source_path` was never recorded is looked up by its slug (an image slug is+ * its repo-relative path) and the import records `source_path`. A sweep that+ * finds no file for any candidate is a failure (non-zero exit) that names the+ * paths it tried; `missing_samples` names them on a partial sweep too. Plain+ * `embed --stale` runs this sweep first on a multimodal install+ * (`runStaleImageSweepFirst`), inside the run's cost cap.*/import { existsSync } from 'fs';@@ -16,9 +26,12 @@ import { execFileSync } from 'child_process';import { join } from 'path';import type { BrainEngine } from './engine.ts';import { importImageFile } from './import-file.ts';+import { importManagedFile } from './persistence/import-mutations.ts';+import { readManagedMode } from './persistence/managed-mode.ts';import { safeChunksFilter } from './search/safe-chunks.ts';import { serr } from './console-prefix.ts';import { gitChildEnv } from './git-env.ts';+import { isMultimodalEnabled } from './sync.ts';import { embedCostStopVerdict, noteEmbedCostStop, type EmbedCostCap, type EmbedCostStopFields } from './embed-cost-cap.ts';export interface StaleImageSweepResult extends EmbedCostStopFields {@@ -27,10 +40,16 @@ export interface StaleImageSweepResult extends EmbedCostStopFields {/** Candidates the importer left unchanged (complete by its own check, or refused). */skipped: number;missingFile: number;+ /** Candidates whose `pages.source_path` was NULL; the sweep located them by slug and the import recorded the path. */+ missingSourcePath: number;failures: number;failure_samples: string[];+ /** Up to 5 `source:slug: no file at <path tried>` lines for the candidates without a source file. */+ missing_samples: string[];}+const SAMPLE_CAP = 5;+export async function embedStaleImages(engine: BrainEngine,opts: { sourceId?: string; dryRun: boolean; costCap?: EmbedCostCap | null },@@ -46,23 +65,34 @@ export async function embedStaleImages(OR NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id AND c.embedding_image IS NOT NULL)OR ($1 AND COALESCE(p.frontmatter->>'ocr_status', '') <> 'done' AND btrim(p.compiled_truth) = ''))ORDER BY p.id`, params);- const result: StaleImageSweepResult = { candidates: rows.length, rebuilt: 0, skipped: 0, missingFile: 0, failures: 0, failure_samples: [] };+ const result: StaleImageSweepResult = { candidates: rows.length, rebuilt: 0, skipped: 0, missingFile: 0, missingSourcePath: rows.filter(row => row.source_path === null).length,+ failures: 0, failure_samples: [], missing_samples: [] };const fail = (row: { source_id: string; slug: string }, error: string) => {result.failures++;- if (result.failure_samples.length < 5) result.failure_samples.push(`${row.source_id}:${row.slug}: ${error}`);+ if (result.failure_samples.length < SAMPLE_CAP) result.failure_samples.push(`${row.source_id}:${row.slug}: ${error}`);};if (opts.dryRun) return result;const repoPath = await engine.getConfig('sync.repo_path').catch(() => null);+ const managed = await readManagedMode(engine);const gitRoots = new Map<string, string | null>();const cap = opts.costCap;for (const row of rows) {// Fix wave 13 P1.18: the approved cap stops the sweep before the next image; a refused image is not a failure.if (cap?.hit()) break;const root = row.local_path ?? (row.source_id === 'default' ? repoPath : null);- const file = root && row.source_path ? locateSourceFile(root, row.source_path, gitRoots) : null;- if (!file) { result.missingFile++; continue; }+ // An image slug is the lower-cased repo-relative path, so it names the file when the importer never recorded source_path.+ const sourcePath = row.source_path ?? row.slug;+ const file = root ? locateSourceFile(root, sourcePath, gitRoots) : null;+ if (!file) {+ result.missingFile++;+ if (result.missing_samples.length < SAMPLE_CAP) result.missing_samples.push(`${row.source_id}:${row.slug}: no file at ${root ? join(root, sourcePath) : `<source ${row.source_id} has no local path>`}`);+ continue;+ }+ // A managed brain imports through the source's owner (the coordinated importer, as `gbrain import` does); the legacy writer refuses it.+ // The owner reads only files inside the source root: a subpath-scoped page found under the git root is reported, not copied in.+ if (managed && file !== join(root!, sourcePath)) { fail(row, `${file} is outside source ${row.source_id}'s root ${root}; a managed brain imports only files inside the source root`); continue; }try {- const run = () => importImageFile(engine, file, row.source_path!, { sourceId: row.source_id });+ const run = () => managed ? importManagedFile(engine, file, sourcePath, { sourceId: row.source_id }) : importImageFile(engine, file, sourcePath, { sourceId: row.source_id });const imported = cap ? await cap.metered(run) : await run();if (imported.status === 'imported') result.rebuilt++;else if (cap?.hit()) break;@@ -73,12 +103,39 @@ export async function embedStaleImages(fail(row, e instanceof Error ? e.message : String(e));}}+ // Every candidate without a file and nothing rebuilt: the sweep did no work, so it must not read as success.+ if (result.candidates > 0 && result.rebuilt === 0 && result.missingFile === result.candidates) {+ result.failures += result.missingFile;+ result.failure_samples.push(...result.missing_samples.slice(0, SAMPLE_CAP - result.failure_samples.length));+ }+ return result;+}++/**+ * #6529: the image sweep plain `embed --stale` runs before its text drain on a+ * multimodal install (`GBRAIN_EMBEDDING_MULTIMODAL=true`), so image pages get+ * their image vector, OCR text and sealed projection in the same run instead of+ * a printed `--images` command; a text-only install gets null (and keeps the hint).+ */+export async function runStaleImageSweepFirst(engine: BrainEngine, opts: { sourceId?: string; dryRun: boolean; costCap?: EmbedCostCap | null }): Promise<StaleImageSweepResult | null> {+ if (!isMultimodalEnabled()) return null;+ return embedStaleImages(engine, opts);+}++/** Folds the image sweep into the text run's result: image pages count as failures only when the sweep failed on them. */+export function foldImageSweep<T extends { failures: number; failure_samples: string[]; images?: StaleImageSweepResult }>(result: T, sweep: StaleImageSweepResult | null): T {+ if (!sweep) return result;+ result.images = sweep;+ if (sweep.failures > 0) {+ result.failures += sweep.failures;+ result.failure_samples.push(`${sweep.failures} image page(s) could not be rebuilt by the image sweep (${sweep.failure_samples.slice(0, 3).join('; ')}); every other stale image was rebuilt first.`);+ }return result;}/** The `gbrain embed --stale --images` CLI surface (dispatched from commands/embed.ts). */export async function runEmbedStaleImagesCli(engine: BrainEngine, args: string[], costCap: EmbedCostCap | null = null): Promise<StaleImageSweepResult> {- if (!args.includes('--stale') || process.env.GBRAIN_EMBEDDING_MULTIMODAL !== 'true') {+ if (!args.includes('--stale') || !isMultimodalEnabled()) {serr('Usage: gbrain embed --stale --images [--source <id>] [--dry-run] [--json] (requires GBRAIN_EMBEDDING_MULTIMODAL=true)');process.exit(1);}@@ -88,8 +145,9 @@ export async function runEmbedStaleImagesCli(engine: BrainEngine, args: string[]const capped = costCap?.hit();if (capped) noteEmbedCostStop(result, capped, args);if (args.includes('--json')) console.log(JSON.stringify(result));- else console.log(`[embed] images: ${result.candidates} incomplete, ${dryRun ? '(dry run) nothing rebuilt'+ else console.log(`[embed] images: ${result.candidates} incomplete${result.missingSourcePath ? ` (${result.missingSourcePath} with no recorded source_path, located by slug)` : ''}, ${dryRun ? '(dry run) nothing rebuilt': `${result.rebuilt} rebuilt, ${result.skipped} unchanged, ${result.missingFile} missing source file, ${result.failures} failed`}`);+ if (result.missing_samples.length) serr(`[embed] first missing image file: ${result.missing_samples[0]}`);if (result.failures > 0) serr(`[embed] first image failure: ${result.failure_samples[0]}`);if (capped) (args.includes('--json') ? serr : console.log)(embedCostStopVerdict(result, capped));return result;diff --git a/src/core/embedding-readiness.ts b/src/core/embedding-readiness.tsindex 8e3373912a..dd853a0d6a 100644--- a/src/core/embedding-readiness.ts+++ b/src/core/embedding-readiness.ts@@ -2,6 +2,7 @@ import type { BrainEngine } from './engine.ts';import { readProjectionSnapshot, queuePageProjection, preparePageProjection, installPageProjection } from './page-state/projections.ts';import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from './search/embedding-column.ts';import { QUARANTINE_FILTER_FRAGMENT } from './quarantine.ts';+import { isMultimodalEnabled } from './sync.ts';export async function countArchivedEmbeddingWork(engine: BrainEngine, opts: { sourceId?: string; signature?: string; includeNullSignature?: boolean; includeUnsealed?: boolean } = {}, activeColumn?: string | null): Promise<number> {const column = activeColumn === undefined ? (await resolveActiveEmbeddingColumnFromEngine(engine)).name : activeColumn;@@ -68,7 +69,9 @@ export async function reportBlockedProjections(engine: BrainEngine, opts: Projecconst sourceArg = opts.sourceId ? ` --source ${opts.sourceId}` : '';samples.push(`${blocked} page(s) still need a text projection, so their chunks were not embedded (${named.map(page => `${page.source_id}:${page.slug}`).join(', ')}${more}); every other stale chunk was embedded. `+ (pages.some(page => page.page_kind !== 'markdown' && page.page_kind !== 'code')- ? `Image and media pages are rebuilt only by their importer: run gbrain embed --stale --images${sourceArg} (needs GBRAIN_EMBEDDING_MULTIMODAL=true) or gbrain sync --full${sourceArg}. ` : '')+ ? isMultimodalEnabled()+ ? `Image and media pages are rebuilt only by their importer; this run's image sweep (images: missing_samples) could not rebuild these: restore their source files, then run gbrain embed --stale${sourceArg} again. `+ : `Image and media pages are rebuilt only by their importer: set GBRAIN_EMBEDDING_MULTIMODAL=true so gbrain embed --stale${sourceArg} sweeps them (or run gbrain embed --stale --images${sourceArg}), or run gbrain sync --full${sourceArg}. ` : '')+ 'Rerun gbrain embed --stale to retry bounded projection recovery.');return new Set(pages.map(page => `${page.source_id}::${page.slug}`));}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 33806a7db0..a4122be13e 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1874,6 +1874,8 @@ export async function importImageFile(if (opts.prepare) return opts.prepare({ slug: imageSlug, observedRevision: existing.knowledge_revision ?? null, noop: true,result: { slug: imageSlug, status: 'skipped', chunks: 0 }, validate: async () => {}, apply: async () => {} });await engine.transaction(tx => assertImportBase(tx, imageSlug, sourceOpts.sourceId, existing));+ // #6529: an unchanged, complete image still records its origin (#4588's skip-path heal for images).+ await refreshSourcePath(engine, imageSlug, sourceOpts.sourceId, relativePath, existing, null);return { slug: imageSlug, status: 'skipped', chunks: 0 };}}diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.tsindex 23bdd21da6..ececb54882 100644--- a/src/core/persistence/import-mutations.ts+++ b/src/core/persistence/import-mutations.ts@@ -274,6 +274,9 @@ async function submitManagedImports(ctx: OperationContext, batch: string, params/** Runs the managed-import preparer on an unadmitted request; true only when the no-op kernel finds nothing to publish. */async function unchangedManagedImport(ctx: OperationContext, binding: WorktreeBinding, intent: ManagedImportIntent, snapshot: PageSnapshot | null): Promise<boolean> {if (!snapshot) return false;+ // #6529: an image's preparation is provider work (OCR, the multimodal vector) unless its index is already complete, so the+ // screen would pay for every incomplete image and the owner would pay again. The owner decides the hash no-op (one importer call).+ if (isImageFilePath(intent.sourcePath)) return false;try {const authority = await submissionAuthority(ctx, 'put_page', binding.source_id, binding.source_incarnation, intent.slug);const row = screeningRequest({ source_id: binding.source_id, source_incarnation: binding.source_incarnation, slug: intent.slug,diff --git a/src/core/persistence/sync-blobs.ts b/src/core/persistence/sync-blobs.tsindex f84a461208..ebf423c9b8 100644--- a/src/core/persistence/sync-blobs.ts+++ b/src/core/persistence/sync-blobs.ts@@ -35,9 +35,14 @@ export function readTreeBlobs(gitRoot: string, target: string, gitPaths: string[return out;}-/** Decoded blob contents by id, read through `git cat-file --batch` in bounded chunks. */+/** Decoded (UTF-8) blob contents by id, read through `git cat-file --batch` in bounded chunks. */export function readBlobContents(gitRoot: string, blobs: TreeBlob[]): Map<string, string> {- const out = new Map<string, string>();+ return new Map([...readBlobBytes(gitRoot, blobs)].map(([oid, bytes]) => [oid, bytes.toString('utf8')]));+}++/** #6529: the raw bytes of blobs by id (an image import keeps its bytes), read through `git cat-file --batch` in bounded chunks. */+export function readBlobBytes(gitRoot: string, blobs: TreeBlob[]): Map<string, Buffer> {+ const out = new Map<string, Buffer>();const pending = [...new Map(blobs.filter(blob => blob.size <= SYNC_READ_BOUND).map(blob => [blob.oid, blob])).values()];while (pending.length) {const chunk: TreeBlob[] = [];@@ -50,7 +55,7 @@ export function readBlobContents(gitRoot: string, blobs: TreeBlob[]): Map<stringconst [oid, kind, size] = output.subarray(offset, newline).toString('utf8').split(' ');if (kind === 'missing' || size === undefined) { offset = newline + 1; continue; }const start = newline + 1, end = start + Number(size);- out.set(oid!, output.subarray(start, end).toString('utf8'));+ out.set(oid!, Buffer.from(output.subarray(start, end)));offset = end + 1;}}@@ -71,7 +76,7 @@ const COMMIT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;* replaces the window.*/let pinned: PinnedWindow | null = null;-interface PinnedWindow { gitRoot: string; target: string; paths: string[]; blobs: Map<string, TreeBlob | null>; slices: number[] | null; loaded: Array<{ slice: number; contents: Map<string, string> }> }+interface PinnedWindow { gitRoot: string; target: string; paths: string[]; blobs: Map<string, TreeBlob | null>; slices: number[] | null; loaded: Array<{ slice: number; contents: Map<string, Buffer> }> }let pinnedWindowSize = PINNED_WINDOW;/** Test seam: replace the pinned window size (0 reads every entry alone, as before windows; null restores it); returns the restore function. */export function __setPinnedWindowForTests(size: number | null): () => void {@@ -126,6 +131,11 @@ export function readPinnedBlob(gitRoot: string, target: string, gitPath: string,* slices stay loaded, so reads in any order cost one process per slice.*/export function readPinnedContent(gitRoot: string, target: string, gitPath: string, upcoming: () => string[]): string | null {+ return readPinnedBytes(gitRoot, target, gitPath, upcoming)?.toString('utf8') ?? null;+}++/** #6529: `readPinnedContent` before decoding: the raw bytes of the pinned blob (an image import), or null when the window cannot answer. */+export function readPinnedBytes(gitRoot: string, target: string, gitPath: string, upcoming: () => string[]): Buffer | null {if (!pinnedWindowSize || !COMMIT_ID.test(target)) return null;const window = pinnedWindow(gitRoot, target, gitPath, upcoming);const blob = window?.blobs.get(gitPath);@@ -137,7 +147,7 @@ export function readPinnedContent(gitRoot: string, target: string, gitPath: striif (!loaded) {const blobs = window.paths.slice(starts[slice], starts[slice + 1] ?? window.paths.length).map(path => window.blobs.get(path)).filter((next): next is TreeBlob => !!next && next.size <= SYNC_READ_BOUND);- try { loaded = { slice, contents: readBlobContents(gitRoot, blobs) }; } catch { return null; }+ try { loaded = { slice, contents: readBlobBytes(gitRoot, blobs) }; } catch { return null; }window.loaded = [...window.loaded, loaded].slice(-PINNED_SLICES_KEPT);}return loaded.contents.get(blob.oid) ?? null;diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex 0afacbcc1f..45871550c9 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -57,7 +57,7 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [{ code: 'file_too_large', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'Split the file or exclude it with sync.exclude.' },{ code: 'content_rejected', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The content-sanity gate rejected the file; remove the junk or change junk_disposition.' },{ code: 'parser_regression', class: 'page', safe_actions: ['upgrade'], needs_human: true, escalate: 'always: a gbrain bug', human_reason: 'Report the file and gbrain version, then upgrade or pin the last good release.' },- { code: 'managed_image_sync_unsupported', class: 'page', safe_actions: ['none'], needs_human: false, escalate: 'never: images stay held by design', human_reason: 'Leave images held, or exclude them with sync.exclude.' },+ { code: 'managed_image_sync_unsupported', class: 'page', safe_actions: ['none'], needs_human: false, escalate: 'never: images stay held while multimodal embedding is off', human_reason: 'Leave images held, exclude them with sync.exclude, or set GBRAIN_EMBEDDING_MULTIMODAL=true so the next sync imports them.' },// Older releases recorded these as run failures; a rerun on this release holds the page instead.{ code: 'revision_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },{ code: 'page_identity_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 6c6c13a14e..93c6a9e54e 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -43,6 +43,7 @@ import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair,import { contentHoldDocs, contentHoldFix } from '../content-repair/hold-fix.ts';import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';import type { SyncRename } from './sync-discovery.ts';+import { isMultimodalEnabled } from '../sync.ts';import { VERSION } from '../../version.ts';export const GIT_HOLD_OP = 'sync-hold';@@ -387,10 +388,13 @@ export async function readGitHoldListing(engine: Exec, sourceIds: string[], limi* screened fences with an older version than this one. #6278: a* `preparation_stalled` hold re-screens when the gbrain version changed (the* stall was the owner's, not the file's); otherwise it waits for- * `sources retry-held`.+ * `sources retry-held`. #6529: a `managed_image_sync_unsupported` hold+ * re-screens whenever multimodal embedding is on, since managed sync then+ * imports the image instead of holding it.*/export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression'].includes(record.code)+ || (record.code === 'managed_image_sync_unsupported' && isMultimodalEnabled())|| record.meta.recovery_version < RECOVERY_VERSION|| (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION)|| (record.code === 'preparation_stalled' && record.meta.stall?.gbrain_version !== VERSION);@@ -530,8 +534,8 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cwhy: 'The operator chose to reject external instruction-like content; changing that setting is a user decision. Editing the file and committing clears the hold on the next sync.' };case 'managed_image_sync_unsupported':return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'user', requires_exclusive: false,- user_message: `Managed sync does not import images yet, so ${record.path} is held and the rest of source ${source} keeps syncing. Keeping images held is fine; to stop holding them, leave images out of the source with sync.exclude or turn off multimodal embedding.`,- why: 'Whether images stay in the source is the user\'s call. The hold clears when the file is deleted or excluded, and a held image is re-screened when it changes or on gbrain sources retry-held.',+ user_message: `Multimodal embedding is off, so managed sync holds ${record.path} and the rest of source ${source} keeps syncing. Keeping images held is fine; to import them, set GBRAIN_EMBEDDING_MULTIMODAL=true for the gbrain process (image embeddings can cost money) and sync again; to stop holding them, leave images out of the source with sync.exclude.`,+ why: 'Whether images are embedded is the user\'s call (it costs provider calls). With GBRAIN_EMBEDDING_MULTIMODAL=true the next sync imports every held image; the hold also clears when the file is deleted or excluded, and is re-screened when it changes or on gbrain sources retry-held.',verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };case 'parser_regression':return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'user', requires_exclusive: false,diff --git a/src/core/persistence/sync-image.ts b/src/core/persistence/sync-image.tsnew file mode 100644index 0000000000..7181e30caa--- /dev/null+++ b/src/core/persistence/sync-image.ts@@ -0,0 +1,102 @@+/**+ * #6529: managed sync's image branch. With `GBRAIN_EMBEDDING_MULTIMODAL=true`+ * (`isMultimodalEnabled`, the predicate `embed --stale --images` and the import walker use), a frozen+ * image entry is imported through the coordinated image importer+ * (`importImageFile` with `prepare`, as `gbrain import` does in+ * import-prepare.ts) instead of being held as `managed_image_sync_unsupported`.+ * The frozen content is the image's bytes as base64 (never a UTF-8 decode);+ * `rawHash` stays the sha256 of the file bytes, so the publication's+ * working-tree check (`syncRawHash`) and the hash no-op work unchanged. OCR+ * and the multimodal vector are provider work the owner does at preparation,+ * inside the sync preparation budget; `--no-embed` skips both. The page's+ * `source_path` is recorded on every publication, a hash no-op included.+ */+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { importImageFile } from '../import-file.ts';+import type { OperationError } from '../ops/contract.ts';+import type { RegistryCode } from '../error-registry.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import { ownerImportTrust } from '../trust/channel.ts';+import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';+import { sha256 } from './digest.ts';+import type { PreparedMutation } from './coordinator.ts';+import type { WriteRequest } from './model.ts';+import type { PreparedContentImport } from './prepared-import.ts';++/** The frozen intent fields of an image entry: the bytes as base64 and their hash (`rawHash` and `content` agree on a committed, clean file). */+export function frozenImageIntent(bytes: Buffer): { content: string; contentHash: string } {+ return { content: bytes.toString('base64'), contentHash: sha256(bytes) };+}++/** An image's "same content" is its byte hash: the preparer's no-op verdict would cost provider work. */+export function sameImageBytes(bytes: Buffer | null, page: { content_hash?: string | null } | undefined): boolean {+ return !!bytes && page?.content_hash === sha256(bytes);+}++export interface ManagedSyncImageContext {+ root: string;+ snapshot: PageSnapshot | null;+ /** A Git rename: the page at this slug (the old path's) is retired when the image publishes at the new slug. */+ renamedFrom?: { slug: string };+ noEmbed: boolean;+ companyApproval: boolean;+ /** The sync-wide validation (cursor, authority, file hash, origin); runs with the import's own under the apply transaction. */+ validate: (tx: BrainEngine) => Promise<void>;+ /** Clears the path's hold (if any) when the import commits. */+ releaseHold: (tx: BrainEngine) => Promise<void>;+ /** The caller's publication refusal, so the image branch names requests, retries and codes the way the text branch does. */+ refuse: (code: RegistryCode, message: string, cause: string) => OperationError;+ clock?: ClaimPhaseClock;+ /** A no-op screen without admission (`sameContentAtOrigin`, the waiver): never provider work. */+ screening?: boolean;+}++/**+ * Prepares one frozen image import: the coordinated importer decides a hash+ * no-op (the same bytes, a complete index) before any provider call, OCRs and+ * embeds otherwise, and hands back the guarded apply. The text embedding of+ * the image's caption chunk is deferred to `embed --stale`, as `gbrain import`+ * defers it. A renamed image publishes as a new page at the new slug and+ * soft-deletes the old one (its single chunk and file row are rebuilt from the+ * same bytes; an image page has no history worth carrying across the move).+ */+export async function prepareManagedSyncImage(engine: BrainEngine, row: WriteRequest, p: { content: string; sourcePath: string; path: string; rawHash: string | null; lineEndingOnly?: boolean },+ ctx: ManagedSyncImageContext): Promise<PreparedMutation> {+ const { snapshot, refuse } = ctx;+ if (ctx.companyApproval) throw refuse('profile_incompatible', 'Company source approval permits only committed Markdown content.',+ `A company-brain source imports only committed Markdown, and ${row.slug} is an image; remove it from the approved revision.`);+ if (ctx.screening) throw refuse('invalid_params', 'An image import is prepared only under its admitted request.',+ `${row.slug} is an image: its preparation does provider work, so it is never screened without admission.`);+ const bytes = Buffer.from(p.content, 'base64');+ const contentHash = sha256(bytes);+ if (snapshot && !p.lineEndingOnly && p.rawHash !== contentHash && snapshot.page.content_hash !== p.rawHash) {+ throw refuse('source_changed', 'Newer image bytes disagree with the pinned import.',+ `The working tree holds newer bytes for ${row.slug} than the pinned import; sync did not overwrite them. Preserve the local edit and commit it.`);+ }+ const filePath = join(ctx.root, p.path);+ if (!existsSync(filePath)) throw refuse('source_changed', 'The imported image left the working tree.',+ `${p.path} is no longer in the working tree of ${row.source_id}, so nothing was imported from it; commit the removal or restore the file, then sync again.`);+ let prepared: Omit<PreparedContentImport, 'parsedPage'> | undefined;+ enterClaimStep(ctx.clock, 'image_import', undefined, 'db');+ const result = await importImageFile(engine, filePath, p.sourcePath, { sourceId: row.source_id, noEmbed: ctx.noEmbed, bytes,+ prepare: async value => { prepared = value; return value.result; } });+ if (!prepared || prepared.slug !== row.slug) throw refuse('invalid_params', result.error ?? 'The image could not be prepared.',+ `${p.sourcePath} could not be prepared as page ${row.slug}${result.error ? ` (${result.error})` : ''}; fix the file, then sync again.`);+ const ready = prepared;+ if (ready.observedRevision !== (snapshot?.revision ?? null)) throw refuse('revision_conflict', 'The image page changed during preparation.',+ `Page ${row.slug} changed while this sync was being prepared.`);+ const mutation: PreparedMutation = { observedRevision: ready.observedRevision, trust: await ownerImportTrust(engine, row, null, p.sourcePath),+ validate: async tx => { await ctx.validate(tx); await ready.validate(tx); },+ noop: ready.noop && !ctx.renamedFrom, contentUnchanged: ready.noop && !ctx.renamedFrom, deferEmbedding: true, apply: async tx => {+ if (ctx.renamedFrom) { await tx.createVersion(ctx.renamedFrom.slug, { sourceId: row.source_id }); await tx.softDeletePage(ctx.renamedFrom.slug, { sourceId: row.source_id }); }+ await ready.apply(tx);+ await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);+ await ctx.releaseHold(tx);+ mutation.postimage = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ return { status: ctx.renamedFrom ? 'renamed' : ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,+ chunks: ready.result.chunks, noop: ready.noop && !ctx.renamedFrom, imported_file: true, ...(ctx.renamedFrom ? { renamed_from: ctx.renamedFrom.slug } : {}) };+ } };+ return mutation;+}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex deb748be81..80b10be30b 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -13,7 +13,8 @@ import { importFromContent, importCodeFile, verifyPageReadable } from '../importimport { screenImportContent, screenNormalized, type ContentRefusal, type ImportScreenResult, type ImportSanityConfig } from '../import-screen.ts';import { ContentSanityBlockError } from '../content-sanity.ts';import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, type ParseOpts } from '../markdown.ts';-import { resolveSlugForPath, slugifyPath, isCodeFilePath } from '../sync.ts';+import { resolveSlugForPath, slugifyPath, isCodeFilePath, isImageFilePath } from '../sync.ts';+import { prepareManagedSyncImage } from './sync-image.ts';import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';import { sameCanonicalImport } from '../page-state/import-guard.ts';import { assertPageRevision } from '../page-state/types.ts';@@ -315,6 +316,39 @@ async function recordSliceCursor(tx: BrainEngine, row: WriteRequest, p: { syncOpif (settled) await clearSyncSlice(tx, row.source_id, row.source_incarnation, p.syncOptions);else await writeSyncSlice(tx, row.source_id, row.source_incarnation, p.syncOptions, p.slice!);}++/** The code-file branch of `prepareManagedSyncMutation`: `importCodeFile` with `prepare`, text embedding deferred to `embed --stale` (the image branch is `sync-image.ts`). */+async function prepareManagedSyncCode(engine: BrainEngine, row: WriteRequest, p: { content: string; sourcePath: string; rawHash: string | null; lineEndingOnly?: boolean; companyApproval: boolean },+ ctx: { snapshot: Snapshot | null; validate: (tx: BrainEngine) => Promise<void>; releaseHold: (tx: BrainEngine) => Promise<void>; clock?: ClaimPhaseClock;+ refuse: (code: RegistryCode, message: string, cause: string) => OperationError; contentRefusal: (refusal: ContentRefusal) => OperationError }): Promise<PreparedMutation> {+ const { snapshot, validate, releaseHold, clock, refuse } = ctx;+ if (p.companyApproval) throw refuse('profile_incompatible', 'Company source approval permits only committed Markdown content.',+ `A company-brain source imports only committed Markdown, and ${row.slug} is a code file; remove it from the approved revision.`);+ if (snapshot && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && snapshot.page.compiled_truth !== p.content) {+ throw refuse('source_changed', 'Newer code file bytes disagree with the pinned import.',+ `The working tree holds newer bytes for ${row.slug} than the pinned import; sync did not overwrite them. Preserve the local edit and commit it.`);+ }+ const codeScreen = screenImportContent({ content: p.content, path: p.sourcePath });+ if (codeScreen.status === 'refused') throw ctx.contentRefusal(codeScreen.refusal);+ let prepared: PreparedContentImport | undefined;+ enterClaimStep(clock, 'code_import', undefined, 'db');+ const result = await importCodeFile(engine, p.sourcePath, p.content, { sourceId: row.source_id, noEmbed: true,+ prepare: async value => { prepared = value; return value.result; } });+ if (!prepared || prepared.slug !== row.slug) throw refuse('invalid_params', result.error ?? 'The code file identity could not be prepared.',+ `The code file could not be prepared as page ${row.slug}.`);+ const ready = prepared;+ if (ready.observedRevision !== (snapshot?.revision ?? null)) throw refuse('revision_conflict', 'The code page changed during preparation.',+ `Page ${row.slug} changed while this sync was being prepared.`);+ return { observedRevision: ready.observedRevision, trust: await ownerImportTrust(engine, row, null, p.sourcePath),+ validate: async tx => { await validate(tx); await ready.validate(tx); },+ noop: ready.noop, deferEmbedding: true, apply: async tx => {+ await ready.apply(tx);+ await releaseHold(tx);+ return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,+ chunks: result.chunks, noop: ready.noop, imported_file: true };+ } };+}+export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock,screening?: { unsaved: true }): Promise<PreparedMutation> {const engine = boundedReads(unbounded, clock);@@ -454,33 +488,14 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr} };if (typeof p.content !== 'string' || typeof p.sourcePath !== 'string' || typeof p.path !== 'string') throw syncPublicationRefusal('storage_error', 'The frozen import content is missing.', row, p,'The stored intent has no frozen file content to import.');- if (isCodeFilePath(p.sourcePath)) {- if (p.companyApproval) throw syncPublicationRefusal('profile_incompatible', 'Company source approval permits only committed Markdown content.', row, p,- `A company-brain source imports only committed Markdown, and ${row.slug} is a code file; remove it from the approved revision.`);- if (snapshot && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && snapshot.page.compiled_truth !== p.content) {- throw syncPublicationRefusal('source_changed', 'Newer code file bytes disagree with the pinned import.', row, p,- `The working tree holds newer bytes for ${row.slug} than the pinned import; sync did not overwrite them. Preserve the local edit and commit it.`);- }- const codeScreen = screenImportContent({ content: p.content, path: p.sourcePath });- if (codeScreen.status === 'refused') throw syncContentRefusal(codeScreen.refusal, row, p);- let prepared: PreparedContentImport | undefined;- enterClaimStep(clock, 'code_import', undefined, 'db');- const result = await importCodeFile(engine, p.sourcePath, p.content, { ...source, noEmbed: true,- prepare: async value => { prepared = value; return value.result; } });- if (!prepared || prepared.slug !== row.slug) throw syncPublicationRefusal('invalid_params', result.error ?? 'The code file identity could not be prepared.', row, p,- `The code file could not be prepared as page ${row.slug}.`);- const ready = prepared;- if (ready.observedRevision !== (snapshot?.revision ?? null)) throw syncPublicationRefusal('revision_conflict', 'The code page changed during preparation.', row, p,- `Page ${row.slug} changed while this sync was being prepared.`);- return { observedRevision: ready.observedRevision, trust: await ownerImportTrust(engine, row, null, p.sourcePath),- validate: async tx => { await validate(tx); await ready.validate(tx); },- noop: ready.noop, deferEmbedding: true, apply: async tx => {- await ready.apply(tx);- await releaseHold(tx);- return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,- chunks: result.chunks, noop: ready.noop, imported_file: true };- } };+ // #6529: an image entry (frozen as base64 bytes) takes the coordinated image importer; its text embedding waits for embed --stale.+ if (isImageFilePath(p.sourcePath)) {+ return prepareManagedSyncImage(engine, row, { content: p.content, sourcePath: p.sourcePath, path: p.path, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly },+ { root, snapshot, ...(moved && moved.slug !== row.slug ? { renamedFrom: { slug: moved.slug } } : {}), noEmbed: p.processingOptions?.noEmbed === true, companyApproval: !!p.companyApproval, validate, releaseHold, clock, screening: !!screening,+ refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause) });}+ if (isCodeFilePath(p.sourcePath)) return prepareManagedSyncCode(engine, row, { content: p.content, sourcePath: p.sourcePath, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly, companyApproval: !!p.companyApproval },+ { snapshot, validate, releaseHold, clock, refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause), contentRefusal: refusal => syncContentRefusal(refusal, row, p) });const schema = p.companyApproval?.schema;if (schema && p.processingOptions?.noSchemaPack) throw syncPublicationRefusal('profile_incompatible', 'Company source approval requires its pinned schema pack.', row,{ ...p, processingOptions: { ...p.processingOptions!, noSchemaPack: false } },diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 1606a97b3d..09d53ca377 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -14,7 +14,7 @@ import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer, type WriteWait } from './service.ts';import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';import { syncCursorOptions } from './sync-slices.ts';-import { isImageFilePath } from '../sync.ts';+import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';@@ -43,7 +43,8 @@ import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';import { isContentRefusal } from '../import-screen.ts';import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';-import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, pinnedContent, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';+import { dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';+import { frozenImageIntent, sameImageBytes } from './sync-image.ts';import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';import { fileChangedAfterAdmission, headCommittedBytes, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';@@ -318,14 +319,12 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass// #5988: company-profile sources never hold; their approved manifest keeps refusing.const screening = entry?.action === 'import' && !cursor.companyPlan ? run.screen ?? null : null;let blob: TreeBlob | null = null, oversize: { size: number | null } | undefined;+ // #6529: an image entry is frozen as its bytes (base64) for the coordinated image importer when multimodal embedding is on.+ const image = !!entry && entry.action === 'import' && !cursor.companyPlan && isImageFilePath(entry.path);+ let imageBytes: Buffer | null = null;if (entry) {assertSyncEntryOrigin(cursor, entry);- if (entry.action === 'import' && !cursor.companyPlan && isImageFilePath(entry.path)) {- const imageBlob = entry.working ? null : pinnedBlob(cursor, entry.path);- let bytes: Buffer | null = null;- if (!imageBlob) { try { bytes = readSyncFile(cursor.root, entry.path); } catch (error) { if (!isSyncReadBound(error)) throw error; } }- return { hold: managedImageHold(entry, bytes === null ? null : bytes.toString('utf8'), imageBlob) };- }+ if (image && !isMultimodalEnabled()) return { hold: heldImageEntry(cursor, entry) };const originScope = syncOriginScope(cursor);// #5522: another cursor of this source may have imported this new file since enumeration.// #5984 G3: the page snapshot is read beside the origin check (they are independent reads of committed state).@@ -343,12 +342,14 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, asslet bytes: Buffer | null = null;try { bytes = readSyncFile(cursor.root, entry.path); }catch (error) { if (!screening || !isSyncReadBound(error)) throw error; oversize = { size: null }; }- if (screening && !entry.working) {+ if ((screening || image) && !entry.working) {// #5988: an over-bound pinned blob is held by its size before its content is loaded.blob = pinnedBlob(cursor, entry.path);if (blob && blob.size > SYNC_READ_BOUND) oversize = { size: blob.size };}rawHash = bytes === null ? null : sha256(bytes);+ if (image && oversize) return { hold: oversizeHold(entry, entry.slug!, entry.pageId ?? null, oversize.size, blob) };+ if (image) imageBytes = pinnedImageBytes(cursor, entry);if (entry.action === 'import' && cursor.companyPlan) {const company = currentCompanyBrainSync(cursor.sourceId);const blob = company?.entries.get(entry.path);@@ -357,15 +358,15 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass`Source ${cursor.sourceId}'s approved company-brain content manifest no longer includes ${entry.path} for this run (its approval changed, or the file is no longer an included path), so nothing was imported for it. If the approval changed, inspect and approve the repository again first (gbrain sources inspect --help).`);content = (await readCommittedBlob(cursor.companyPlan.revision!, blob, cursor.companyPlan.limits)).toString('utf8');assertActive();- } else content = entry.action === 'import' && !oversize ? pinnedContent(cursor, entry) : null;+ } else content = imageBytes ? frozenImageIntent(imageBytes).content : entry.action === 'import' && !oversize ? pinnedContent(cursor, entry) : null;// #6340: working-tree bytes that differ from the pinned blob but are committed at HEAD (a commit past the pin on a// live checkout) are imported as HEAD has them; the pin..HEAD diff later re-imports the same bytes as a no-op.// Uncommitted bytes keep the pinned content and reach the publication screen (idea from PR #6323).- if (entry.action === 'import' && !cursor.companyPlan && !entry.working && content !== null && rawHash !== null && rawHash !== sha256(content)) {+ if (entry.action === 'import' && !cursor.companyPlan && !image && !entry.working && content !== null && rawHash !== null && rawHash !== sha256(content)) {const head = headCommittedBytes(cursor, entry.path);if (head && head.rawHash === rawHash) { content = head.content; blob = { oid: head.oid, size: bytes!.length }; }}- lineEndingOnly = bytes !== null && content !== null && bytes.equals(Buffer.from(bytes.toString('utf8'))) &&+ lineEndingOnly = !image && bytes !== null && content !== null && bytes.equals(Buffer.from(bytes.toString('utf8'))) &&bytes.toString('utf8').replace(/\r\n/g, '\n') === content.replace(/\r\n/g, '\n');slug = entry.slug!; pageId = occupant?.page.id ?? entry.pageId ?? null; revision = occupant ? occupant.revision : entry.revision ?? null;frozenSnapshot = snapshot;@@ -380,7 +381,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assassertActive();return { hold: pageChangedHold(entry, slug, observedPageId ?? pageId, frozenIntent, { proof, revision: observedRevision, why }), overtaken: true };};- if (occupant && (content === null || !await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal))) {+ if (occupant && (content === null || !(image ? sameImageBytes(imageBytes, occupant.page) : await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal)))) {if (holdsOn) return pageHold(`another run of this source imported page ${slug} from ${entry.path} with different content`, occupant.page.id, occupant.revision);throw syncRunRefusal('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.', retry,`Page ${slug} was imported from ${entry.path} by another run of source ${cursor.sourceId} with different content after this run enumerated it, so the run stopped before admitting it.`);@@ -394,7 +395,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass// The page moved but still holds exactly what this import carries: re-bind the entry to it (the waiver screen passes it).const rebind = entry.action === 'import' && !moved && !foreignOrigin && snapshot !== null && snapshot.page.deleted_at == null&& (snapshot.page.id === pageId || pageId === null) && content !== null- && await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal);+ && (image ? sameImageBytes(imageBytes, snapshot.page) : await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal));assertActive();if (!rebind) return pageHold(`page ${slug} was ${snapshot === null || snapshot.page.deleted_at != null ? 'deleted' : foreignOrigin ? 're-bound to another file' : 'edited'} in the database`,snapshot?.page.id ?? null, snapshot?.revision ?? null);@@ -412,7 +413,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass`Page ${moved.slug}, which ${entry.path} was renamed from, changed or was deleted after this sync enumerated it, so the run stopped before admitting the rename.`);}}- if (screening) {+ if (screening && !image) {const hold = await screenFrozenImport(engine, { cursor, entry, slug, pageId, snapshot, content, rawHash, lineEndingOnly, blob, oversize,retryCommand: checkpointRetryCommand(retry) }, screening);assertActive();diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex b9a5b100e6..0961b17cbd 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -23,13 +23,13 @@ import { fenceMessage, type FenceMessageLocation } from '../fence-repair/reasonsimport { completeFenceLocation, FENCE_VERSION, type ReceiptFenceLocation } from '../fence-repair/refusal.ts';import { fenceFileLine } from '../fence-repair/hold-fix.ts';import { slugConflictHoldMessage } from '../import-file.ts';-import { isImageFilePath, resolveSlugForPath } from '../sync.ts';+import { isImageFilePath, isMultimodalEnabled, resolveSlugForPath } from '../sync.ts';import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { VERSION } from '../../version.ts';import { sha256 } from './digest.ts';import { readPagePurgeTombstones } from './page-purge.ts';import { readSyncContent, readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';-import { PINNED_WINDOW, readBlobContents, readPinnedBlob, readPinnedContent, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';+import { PINNED_WINDOW, readBlobBytes, readBlobContents, readPinnedBlob, readPinnedBytes, readPinnedContent, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { screenSyncImport, type SyncImportScreenInput } from './sync-prepare.ts';import type { SyncProcessingOptions } from './sync-authority.ts';import { gitHoldItem, readSyncHoldPolicy, readSyncImportProvenance, type GitHoldItem, type GitHoldRecord, type PreparationStallMeta, type SyncHoldPolicy } from './sync-holds.ts';@@ -80,6 +80,34 @@ export function pinnedContent(cursor: SyncDiscovery & { index: number }, entry:return content ?? readSyncContent(cursor, entry);}+/**+ * #6529: `pinnedContent` for an image entry: the frozen bytes, never decoded as+ * text. A committed entry's pinned blob is read binary-safe with the entries+ * after it (one `cat-file --batch` per window slice); a working-tree entry is+ * read from the file. Throws `source_changed` when the committed blob or the file is gone.+ */+export function pinnedImageBytes(cursor: SyncDiscovery & { index: number }, entry: SyncEntry): Buffer {+ const bytes = (() => {+ if (entry.working) return readSyncFile(cursor.root, entry.path);+ const gitPath = syncGitPath(cursor, entry.path);+ const windowed = readPinnedBytes(cursor.gitRoot, cursor.target, gitPath, upcomingGitPaths(cursor));+ if (windowed) return windowed;+ const blob = readTreeBlobs(cursor.gitRoot, cursor.target, [gitPath]).get(gitPath);+ return blob ? readBlobBytes(cursor.gitRoot, [blob]).get(blob.oid) ?? null : null;+ })();+ if (bytes) return bytes;+ throw opError('source_changed', 'The discovered image disappeared.',+ `${entry.path} left ${cursor.sourceId} between discovery and import, so nothing was imported from it. Run gbrain sync --no-pull --source ${cursor.sourceId} to rediscover the tree.`);+}++/** #5493: the hold `freezeEntry` returns for an image import while multimodal embedding is off, keyed by the pinned blob or the working bytes (an over-bound file keys by nothing). */+export function heldImageEntry(cursor: SyncDiscovery & { index: number }, entry: SyncEntry): HeldEntry {+ const blob = entry.working ? null : pinnedBlob(cursor, entry.path);+ let bytes: Buffer | null = null;+ if (!blob) { try { bytes = readSyncFile(cursor.root, entry.path); } catch (error) { if (!isSyncReadBound(error)) throw error; } }+ return managedImageHold(entry, bytes === null ? null : bytes.toString('utf8'), blob);+}+function heldEntry(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null,refusal: { code: GitHoldRecord['code']; reason?: GitHoldRecord['meta']['reason']; key?: string; line?: number; message: string; fence?: FenceMessageLocation },content: string | null, blob: Pick<TreeBlob, 'oid'> | null | undefined): HeldEntry {@@ -134,14 +162,22 @@ export function preparationStalledHold(entry: Pick<SyncEntry, 'path' | 'sourcePa}/**- * #5493: managed sync has no image importer, so an image import is held as- * incomplete coverage instead of refusing the run. The hold names the pinned- * blob (or the working-tree bytes), so discovery re-screens it when the file- * changes, leaves the source, or `sources retry-held` asks.+ * #5493 / #6529: with multimodal embedding off, managed sync has no image+ * importer, so an image import is held as incomplete coverage instead of+ * refusing the run. The hold names the pinned blob (or the working-tree+ * bytes), so discovery re-screens it when the file changes, leaves the source,+ * `sources retry-held` asks, or `GBRAIN_EMBEDDING_MULTIMODAL=true` turns the+ * coordinated image importer on (`holdRescreenDue`).*/-export function managedImageHold(entry: SyncEntry, content: string | null, blob: TreeBlob | null | undefined): HeldEntry {+export function managedImageHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld' | 'slug' | 'pageId'>, content: string | null, blob: TreeBlob | null | undefined): HeldEntry {return heldEntry(entry, entry.slug!, entry.pageId ?? null, { code: 'managed_image_sync_unsupported',- message: `${entry.path} is an image, which managed sync does not import yet; the rest of the source synced.` }, content, blob);+ message: `${entry.path} is an image, and managed sync imports images only with GBRAIN_EMBEDDING_MULTIMODAL=true (multimodal embedding is off on this install); the rest of the source synced.` }, content, blob);+}++/** #5988: the hold of a file over the sync read bound, whose content is never read (#6529: shared with the image freeze). */+export function oversizeHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null, size: number | null, blob: TreeBlob | null | undefined): HeldEntry {+ return heldEntry(entry, slug, pageId, { code: 'file_too_large',+ message: `File too large (${size ?? 'over 10485760'} bytes; the sync read bound is ${SYNC_READ_BOUND} bytes). Split the content into smaller files or leave it out of the source.` }, null, blob);}const purgeTombstonesByRun = new WeakMap<SyncScreenRun, Promise<Map<string, string>>>();@@ -171,11 +207,7 @@ export interface FrozenImportScreen {*/export async function screenFrozenImport(engine: BrainEngine, input: FrozenImportScreen, run: SyncScreenRun): Promise<HeldEntry | null> {const { entry, slug, pageId, snapshot, content, blob } = input;- if (input.oversize || content === null) {- const size = input.oversize?.size ?? blob?.size ?? null;- return heldEntry(entry, slug, pageId, { code: 'file_too_large',- message: `File too large (${size ?? 'over 10485760'} bytes; the sync read bound is ${SYNC_READ_BOUND} bytes). Split the content into smaller files or leave it out of the source.` }, null, blob);- }+ if (input.oversize || content === null) return oversizeHold(entry, slug, pageId, input.oversize?.size ?? blob?.size ?? null, blob);if (entry.renameHeld) {return heldEntry(entry, slug, pageId, { code: 'rename_held', reason: 'rename_source_changed', message: `${entry.path} is a rename of page ${entry.renameHeld.slug}, which changed after the rename was recorded, so the page was not moved.` }, content, blob);}@@ -228,8 +260,11 @@ export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscoverytry {const blob = entry.working ? null : blobs.get(syncGitPath(discovery, entry.path)) ?? null;if (isImageFilePath(entry.path)) {- const hold = managedImageHold(entry, blob ? null : readSyncFile(discovery.root, entry.path)?.toString('utf8') ?? null, blob);- held.push(gitHoldItem({ version: 1, source_id: discovery.sourceId, incarnation: discovery.incarnation, ...hold,+ // #6529: with multimodal embedding on, the coordinated image importer takes the entry (only its size is screened).+ const hold = isMultimodalEnabled()+ ? blob && blob.size > SYNC_READ_BOUND ? oversizeHold(entry, entry.slug!, entry.pageId ?? null, blob.size, blob) : null+ : managedImageHold(entry, blob ? null : readSyncFile(discovery.root, entry.path)?.toString('utf8') ?? null, blob);+ if (hold) held.push(gitHoldItem({ version: 1, source_id: discovery.sourceId, incarnation: discovery.incarnation, ...hold,observed_at: observed, held_at: observed, updated_at: observed, run_id: null, mode: 'managed' }));continue;}diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.tsindex 96d6139913..6ecbe4e8e3 100644--- a/src/core/persistence/sync-waivers.ts+++ b/src/core/persistence/sync-waivers.ts@@ -13,6 +13,7 @@ import { startClaimPhase } from './claim-phase.ts';import { inspectUnchanged, screeningRequest, type NoopKernelWaiver } from './noop-kernel.ts';import { validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';import { readSyncFile, syncRawHash } from './sync-discovery.ts';+import { isImageFilePath } from '../sync.ts';import { getWorktreeBinding } from './ownership.ts';import { assertSyncPageOrigin, syncOriginScope } from './sync-origin.ts';import { faultPoint } from './fault-points.ts';@@ -257,6 +258,8 @@ export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCurfrozenSnapshot?: PageSnapshot | null): Promise<NoopKernelWaiver[] | null> {const intent = pending.intent;if (intent.kind !== 'managed_sync_import' || intent.renameFrom || pending.pageId === null || typeof intent.path !== 'string' || typeof intent.content !== 'string') return null;+ // #6529: an image's preparation is provider work; its hash no-op is decided under the admitted request instead.+ if (isImageFilePath(intent.path)) return null;try {const snapshot = frozenSnapshot !== undefined ? frozenSnapshot : await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });const row = screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: pending.slug, page_id: pending.pageId,diff --git a/src/core/sync.ts b/src/core/sync.tsindex 9955e1dde9..595241d549 100644--- a/src/core/sync.ts+++ b/src/core/sync.ts@@ -270,8 +270,9 @@ export function isMarkdownFilePath(path: string): boolean {return path.endsWith('.md') || path.endsWith('.mdx');}-function isMultimodalEnabled(): boolean {- return process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true';+/** The image side of the brain is on: the sync walker admits images, managed sync imports them (#6529) and `embed --stale` sweeps them. */+export function isMultimodalEnabled(env: NodeJS.ProcessEnv = process.env): boolean {+ return env.GBRAIN_EMBEDDING_MULTIMODAL === 'true';}function isAllowedByStrategy(path: string, strategy: SyncStrategy): boolean {diff --git a/test/doctor-image-embedding-coverage.test.ts b/test/doctor-image-embedding-coverage.test.tsnew file mode 100644index 0000000000..5db006199f--- /dev/null+++ b/test/doctor-image-embedding-coverage.test.ts@@ -0,0 +1,93 @@+/**+ * #6529: `image_embedding_coverage` doctor check. Text coverage hid the image+ * side of search: image pages carry a text vector (caption or OCR projection),+ * so `embed_coverage_pct` read as done while 99% of them had no+ * `embedding_image`. The check reports image pages without an image vector,+ * image pages whose `source_path` was never recorded, and the images managed+ * sync still holds as `managed_image_sync_unsupported`, apart from text coverage.+ *+ * Both engines (PGLite in-memory; Postgres when DATABASE_URL is set). No provider calls.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { importImageFile } from '../src/core/import-file.ts';+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';+import { imageEmbeddingCoverageCheck } from '../src/commands/doctor/checks/image-embedding-coverage.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');+const dir = mkdtempSync(join(tmpdir(), 'gbrain-6529-doctor-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) {+ 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 engine.disconnect();+ await closePostgres?.();+ rmSync(dir, { recursive: true, force: true });+});++async function source(engine: BrainEngine) {+ const sourceId = `s${randomUUID().replace(/-/g, '').slice(0, 12)}`;+ const root = join(dir, sourceId); mkdirSync(join(root, 'photos'), { recursive: true });+ writeFileSync(join(root, 'photos', 'a.png'), PNG);+ writeFileSync(join(root, 'photos', 'b.png'), Buffer.concat([PNG, Buffer.from([0])]));+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [sourceId, root]);+ return { sourceId, root };+}++describe('image_embedding_coverage doctor check', () => {+ test('image pages without an image vector, without source_path, and held images are counted apart from text coverage', async () => {+ for (const engine of engines) {+ const { sourceId, root } = await source(engine);+ for (const name of ['a', 'b']) expect((await importImageFile(engine, join(root, 'photos', `${name}.png`), `photos/${name}.png`, { sourceId, noEmbed: true })).status).toBe('imported');+ await engine.executeRaw("UPDATE pages SET source_path=NULL WHERE source_id=$1 AND slug='photos/b.png'", [sourceId]);+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);+ const now = new Date().toISOString();+ await writeGitHold(engine, { source_id: sourceId, incarnation, path: 'photos/c.png', source_path: 'photos/c.png', slug: 'photos/c.png', page_id: null,+ code: 'managed_image_sync_unsupported', message: 'photos/c.png is an image, which managed sync does not import yet.', upstream_version: null,+ observed_at: now, run_id: null, mode: 'managed', meta: { recovery_version: 1 } });++ const on = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, () => imageEmbeddingCoverageCheck(engine));+ expect(on.name).toBe('image_embedding_coverage');+ expect(on.status).toBe('warn');+ expect(on.details).toMatchObject({ image_pages: 2, without_image_vector: 2, null_source_path: 1, unsupported_holds: 1, multimodal: true });+ expect(on.message).toContain('2 of 2 image page(s) have no image vector');+ expect(on.message).toContain('gbrain embed --stale --images');+ expect(on.message).toContain('1 held as managed_image_sync_unsupported');+ expect(on.message).toContain('1 with no recorded source_path');++ const off = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: undefined }, () => imageEmbeddingCoverageCheck(engine));+ expect(off.status).toBe('ok');+ expect(off.details).toMatchObject({ image_pages: 2, without_image_vector: 2, multimodal: false });+ expect(off.message).toContain('GBRAIN_EMBEDDING_MULTIMODAL');++ await engine.executeRaw("DELETE FROM pages WHERE source_id=$1", [sourceId]);+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE fingerprint LIKE $1', [`${sourceId}:%`]);+ }+ expect(categorizeCheck('image_embedding_coverage')).toBe('brain');+ }, 120_000);++ test('a brain with no image pages is ok without naming a sweep', async () => {+ for (const engine of engines) {+ const check = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, () => imageEmbeddingCoverageCheck(engine));+ expect(check.status).toBe('ok');+ expect(check.details).toMatchObject({ image_pages: 0, without_image_vector: 0 });+ expect(check.message).not.toContain('embed --stale --images');+ }+ }, 60_000);+});diff --git a/test/embed-stale-images-managed-6529.test.ts b/test/embed-stale-images-managed-6529.test.tsnew file mode 100644index 0000000000..a6ad479436--- /dev/null+++ b/test/embed-stale-images-managed-6529.test.ts@@ -0,0 +1,184 @@+/**+ * #6529: `gbrain embed --stale --images` on a managed brain. The sweep called+ * the legacy importer, which a managed brain refuses+ * (`assertUnmanagedCanonicalWriter`); it treated a NULL `pages.source_path` as+ * a missing file although an image slug is the repo-relative path; and a sweep+ * that found no file for any candidate exited 0. Plain `embed --stale` printed+ * the `--images` command instead of running the sweep on a multimodal install.+ *+ * Both engines (PGLite in-memory; Postgres when DATABASE_URL is set). The+ * Voyage multimodal endpoint is a fetch stub ($0); text embedding is stubbed+ * through the gateway transport seam.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { embedStaleImages } from '../src/core/embed-stale-images.ts';+import { importImageFile } from '../src/core/import-file.ts';+import { runEmbed } from '../src/commands/embed.ts';+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(realpathSync.native(tmpdir()), 'gbrain-6529-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');+const NOTE = '---\ntitle: Plain\n---\nAn ordinary note.\n';+const env = { GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true', GBRAIN_EMBEDDING_IMAGE_OCR: 'false' };+const origFetch = globalThis.fetch;+let providerCalls = 0;++function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+function commit(root: string, message: string): string {+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);+ return git(root, 'rev-parse', 'HEAD');+}+/**+ * A Git source claimed by this host; `files` maps a path to Markdown text or raw PNG bytes.+ * `legacyImages` are imported metadata-only through the legacy writer before managed persistence is on (vectorless pages).+ */+async function managedSource(engine: BrainEngine, files: Record<string, string | Buffer>, legacyImages: string[] = []) {+ const sourceId = `i${randomUUID().replace(/-/g, '').slice(0, 20)}`;+ const root = join(home, sourceId); mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q');+ for (const [path, body] of Object.entries(files)) {+ writeFileSync(join(root, path), body);+ }+ const head = commit(root, 'initial');+ 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,\'{}\')', [sourceId, root]);+ for (const path of legacyImages) expect((await importImageFile(engine, join(root, path), path, { sourceId, noEmbed: true })).status).toBe('imported');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { sourceId, root, head };+}+async function imagePage(engine: BrainEngine, sourceId: string, slug: string) {+ const [row] = await engine.executeRaw<{ source_path: string | null; page_kind: string; has_vector: boolean; sealed: boolean }>(+ `SELECT p.source_path, p.page_kind, p.text_projection_revision IS NOT DISTINCT FROM p.knowledge_revision AS sealed,+ EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id AND c.embedding_image IS NOT NULL) AS has_vector+ FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL`, [sourceId, slug]);+ return row ?? null;+}++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);++beforeEach(() => {+ providerCalls = 0;+ // The Voyage multimodal endpoint is a fetch stub (one 1024-d vector per input); text embedding runs through the SDK transport seam (1536-d).+ globalThis.fetch = (async (url: unknown, init?: { body?: string }) => {+ if (!String(url).includes('voyageai.com')) return origFetch(url as string, init as RequestInit);+ providerCalls++;+ const n = (init?.body ? JSON.parse(init.body) as { inputs?: unknown[] } : {}).inputs?.length ?? 1;+ return new Response(JSON.stringify({ data: Array.from({ length: n }, (_, index) => ({ embedding: Array.from({ length: 1024 }, () => 0.1), index })),+ model: 'voyage-multimodal-3', usage: { total_tokens: 10 * n } }), { status: 200, headers: { 'Content-Type': 'application/json' } });+ }) as unknown as typeof fetch;+ __setEmbedTransportForTests((async (args: { values: unknown[] }) => ({ embeddings: args.values.map(() => Array.from({ length: 1536 }, () => 0.1)) })) as never);+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_multimodal_model: 'voyage:voyage-multimodal-3', embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'test-key', VOYAGE_API_KEY: 'test-key' } });+});+afterEach(() => { globalThis.fetch = origFetch; __setEmbedTransportForTests(null); resetGateway(); });++afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ });+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++describe('#6529 embed --stale --images on a managed brain', () => {+ test('rebuilds a vectorless image through the coordinator, finds a NULL source_path page through its slug and records source_path', async () =>+ withEnv(env, async () => {+ for (const engine of engines) {+ providerCalls = 0;+ const { sourceId } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/photo.png': PNG, 'notes/unpathed.png': PNG }, ['notes/photo.png', 'notes/unpathed.png']);+ expect(await imagePage(engine, sourceId, 'notes/photo.png')).toMatchObject({ source_path: 'notes/photo.png', has_vector: false });+ expect(providerCalls).toBe(0);+ // The page came from an importer that never recorded its origin (the production shape of #6529).+ await engine.executeRaw("UPDATE pages SET source_path=NULL WHERE source_id=$1 AND slug='notes/unpathed.png'", [sourceId]);++ const preview = await embedStaleImages(engine, { sourceId, dryRun: true });+ expect(preview.candidates).toBe(2);++ const swept = await embedStaleImages(engine, { sourceId, dryRun: false });+ expect(swept).toMatchObject({ candidates: 2, rebuilt: 2, missingFile: 0, missingSourcePath: 1, failures: 0, failure_samples: [] });+ expect(await imagePage(engine, sourceId, 'notes/photo.png')).toMatchObject({ has_vector: true, sealed: true });+ expect(await imagePage(engine, sourceId, 'notes/unpathed.png')).toMatchObject({ source_path: 'notes/unpathed.png', has_vector: true });+ expect(providerCalls).toBe(2);++ expect((await embedStaleImages(engine, { sourceId, dryRun: false })).candidates).toBe(0);+ }+ }), 240_000);++ test('a sweep that finds no file for any candidate is a failure naming the path it tried, never a quiet success', async () =>+ withEnv(env, async () => {+ for (const engine of engines) {+ providerCalls = 0;+ const { sourceId, root } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/gone.png': PNG }, ['notes/gone.png']);+ await engine.executeRaw("UPDATE pages SET source_path=NULL WHERE source_id=$1 AND slug='notes/gone.png'", [sourceId]);+ rmSync(join(root, 'notes', 'gone.png'));++ const swept = await embedStaleImages(engine, { sourceId, dryRun: false });+ expect(swept).toMatchObject({ candidates: 1, rebuilt: 0, missingFile: 1, missingSourcePath: 1 });+ expect(swept.failures).toBeGreaterThan(0);+ expect(swept.failure_samples[0]).toContain(`${sourceId}:notes/gone.png`);+ expect(swept.failure_samples[0]).toContain(join(root, 'notes', 'gone.png'));+ expect(swept.missing_samples?.[0]).toContain(join(root, 'notes', 'gone.png'));+ }+ }), 240_000);++ test('plain embed --stale runs the image sweep itself on a multimodal install and keeps the hint on a text-only one', async () =>+ withEnv(env, async () => {+ for (const engine of engines) {+ providerCalls = 0;+ const { sourceId } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/photo.png': PNG }, ['notes/photo.png']);+ expect((await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true })).status).toBe('first_sync');+ expect(await imagePage(engine, sourceId, 'notes/photo.png')).toMatchObject({ has_vector: false });++ const textOnly = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'false' }, () => runEmbed(engine, ['--stale', '--source', sourceId, '--dry-run', '--json']));+ expect(textOnly && 'images' in textOnly ? textOnly.images : undefined).toBeUndefined();++ const result = await runEmbed(engine, ['--stale', '--source', sourceId, '--json']);+ expect(result && 'images' in result ? result.images : undefined).toMatchObject({ candidates: 1, rebuilt: 1, failures: 0 });+ expect(result?.failures).toBe(0);+ expect(await imagePage(engine, sourceId, 'notes/photo.png')).toMatchObject({ has_vector: true });+ }+ }), 240_000);+});++describe('#6529 source_path is recorded on every image import path', () => {+ test('an unchanged, complete image re-imported through the legacy writer records the origin it never had', async () =>+ withEnv(env, async () => {+ for (const engine of engines) {+ const sourceId = `i${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, sourceId);+ mkdirSync(join(root, 'notes'), { recursive: true });+ writeFileSync(join(root, 'notes', 'legacy.png'), PNG);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [sourceId, root]);+ expect((await importImageFile(engine, join(root, 'notes', 'legacy.png'), 'notes/legacy.png', { sourceId, noEmbed: true })).status).toBe('imported');+ await engine.executeRaw("UPDATE pages SET source_path=NULL WHERE source_id=$1 AND slug='notes/legacy.png'", [sourceId]);+ expect((await importImageFile(engine, join(root, 'notes', 'legacy.png'), 'notes/legacy.png', { sourceId, noEmbed: true })).status).toBe('skipped');+ expect(await imagePage(engine, sourceId, 'notes/legacy.png')).toMatchObject({ source_path: 'notes/legacy.png', has_vector: false });+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ }+ }), 120_000);+});diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 3cfa0bbb75..76bc6e9c5a 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -146,6 +146,7 @@" [OK] grant_new_ops_available: Every active client and token can call the operations its scopes allow."," [OK] image_assets: No image assets indexed yet"," [OK] ocr_health: OCR not in use (or no images ingested with OCR opt-in)",+ " [OK] image_embedding_coverage: No image pages indexed yet."," [FAIL] sync_freshness: Source 'notes' has never been synced. Run `gbrain sync --source <id> --no-pull` for each stale source. 1 writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status"," [OK] canonical_content_writes: 1 writer-owned content source(s); no pending canonical publication or recovery."," [INFO] backup_coverage: Not urgent yet: the brain holds 5 page(s)+fact(s) and is under 7 days old (backup coaching starts at 25 items or 7 days). 2 knowledge asset(s) lack verified recovery: default (not_a_git_repo), notes (no git remote). A source repo with a pushed git remote restores its Markdown files only, never DB-only pages, facts, config or credentials. Run `gbrain backup status` for each asset's fix command.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 9f4dda7359..f87f23f40d 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1502,6 +1502,19 @@"name": "ocr_health","status": "ok"},+ {+ "category": "brain",+ "details": {+ "image_pages": 0,+ "multimodal": false,+ "null_source_path": 0,+ "unsupported_holds": 0,+ "without_image_vector": 0+ },+ "message": "No image pages indexed yet.",+ "name": "image_embedding_coverage",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex cf9414acfd..984b9d0131 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1605,6 +1605,19 @@"name": "ocr_health","status": "ok"},+ {+ "category": "brain",+ "details": {+ "image_pages": 0,+ "multimodal": false,+ "null_source_path": 0,+ "unsupported_holds": 0,+ "without_image_vector": 0+ },+ "message": "No image pages indexed yet.",+ "name": "image_embedding_coverage",+ "status": "ok"+ },{"category": "brain","details": {@@ -4671,6 +4684,19 @@"name": "ocr_health","status": "ok"},+ {+ "category": "brain",+ "details": {+ "image_pages": 0,+ "multimodal": false,+ "null_source_path": 0,+ "unsupported_holds": 0,+ "without_image_vector": 0+ },+ "message": "No image pages indexed yet.",+ "name": "image_embedding_coverage",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 1cad35188d..956f43374d 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1597,6 +1597,19 @@"name": "ocr_health","status": "ok"},+ {+ "category": "brain",+ "details": {+ "image_pages": 0,+ "multimodal": false,+ "null_source_path": 0,+ "unsupported_holds": 0,+ "without_image_vector": 0+ },+ "message": "No image pages indexed yet.",+ "name": "image_embedding_coverage",+ "status": "ok"+ },{"category": "brain","details": {@@ -4652,6 +4665,19 @@"name": "ocr_health","status": "ok"},+ {+ "category": "brain",+ "details": {+ "image_pages": 0,+ "multimodal": false,+ "null_source_path": 0,+ "unsupported_holds": 0,+ "without_image_vector": 0+ },+ "message": "No image pages indexed yet.",+ "name": "image_embedding_coverage",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 02d8a90bf1..e5514a7b78 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1369,6 +1369,19 @@"name": "ocr_health","status": "ok"},+ {+ "category": "brain",+ "details": {+ "image_pages": 0,+ "multimodal": false,+ "null_source_path": 0,+ "unsupported_holds": 0,+ "without_image_vector": 0+ },+ "message": "No image pages indexed yet.",+ "name": "image_embedding_coverage",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 668ae9e6d4..436d9a5e97 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1388,6 +1388,19 @@"name": "ocr_health","status": "ok"},+ {+ "category": "brain",+ "details": {+ "image_pages": 0,+ "multimodal": false,+ "null_source_path": 0,+ "unsupported_holds": 0,+ "without_image_vector": 0+ },+ "message": "No image pages indexed yet.",+ "name": "image_embedding_coverage",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 152293efff..efdc376260 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1380,6 +1380,19 @@"name": "ocr_health","status": "ok"},+ {+ "category": "brain",+ "details": {+ "image_pages": 0,+ "multimodal": false,+ "null_source_path": 0,+ "unsupported_holds": 0,+ "without_image_vector": 0+ },+ "message": "No image pages indexed yet.",+ "name": "image_embedding_coverage",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex c3527b980b..227972f87c 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -621,6 +621,10 @@"category": "brain","name": "ocr_health"},+ {+ "category": "brain",+ "name": "image_embedding_coverage"+ },{"category": "brain","name": "sync_freshness"diff --git a/test/managed-sync-images-5493.test.ts b/test/managed-sync-images-5493.test.tsindex fafae1f133..68ef0b4bb5 100644--- a/test/managed-sync-images-5493.test.ts+++ b/test/managed-sync-images-5493.test.ts@@ -1,13 +1,21 @@/**- * #5493: with multimodal embedding on, the sync admission set includes images,- * but the managed sync importer has no image branch. One committed image used- * to refuse the whole managed sync (`writer_coordinator_required`) before any- * page write, so the checkpoint never advanced. Each image import is now held- * (`managed_image_sync_unsupported`): the rest of the run imports, the image is- * recorded as incomplete coverage (a durable hold, not an import), and a later- * sync re-screens it when the file changes, leaves, or `sources retry-held` asks.+ * Managed sync and images. #5493: with multimodal embedding on, the sync+ * admission set includes images, but managed sync had no image branch, so+ * each image import was held as `managed_image_sync_unsupported` and the rest+ * of the run imported. #6529: the coordinated image importer takes the entry+ * instead. A committed image is frozen as its bytes (never a UTF-8 decode) and+ * imported through `importImageFile` under the owner's guarded transaction:+ * page, chunk with `embedding_image`, file row and `source_path`. An unchanged+ * image is a hash no-op (no provider call); a renamed image moves to its new+ * slug; a deleted image deletes its page. Holds an older release wrote are+ * re-screened and imported once the flag is on. With the flag off the hold+ * stays and names the flag.+ *+ * Both engines (PGLite in-memory; Postgres when DATABASE_URL is set). The+ * Voyage multimodal endpoint is a fetch stub ($0); text embedding is stubbed+ * through the gateway transport seam.*/-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import { execFileSync } from 'node:child_process';import { copyFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';@@ -15,13 +23,15 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { BrainEngine } from '../src/core/engine.ts';-import { importImageFile } from '../src/core/import-file.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { readGitSourceHolds, requestGitHoldRetry } from '../src/core/persistence/sync-holds.ts';-import { printHoldNotes } from '../src/commands/sync-diagnostics.ts';-import { gitHeldFilesCheck } from '../src/commands/doctor/checks/git-holds.ts';+import { readGitSourceHolds, writeGitHold } from '../src/core/persistence/sync-holds.ts';+import { managedImageHold } from '../src/core/persistence/sync-screen.ts';+import { readTreeBlobs } from '../src/core/persistence/sync-blobs.ts';+import { sha256 } from '../src/core/persistence/digest.ts';+import { importImageFile } from '../src/core/import-file.ts';+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';@@ -29,8 +39,12 @@ const home = mkdtempSync(join(realpathSync.native(tmpdir()), 'gbrain-5493-'));const engines: BrainEngine[] = [];let closePostgres: (() => Promise<void>) | undefined;const IMAGE = 'test/fixtures/images/tiny.avif';-const CODE = 'managed_image_sync_unsupported';+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');+const HOLD = 'managed_image_sync_unsupported';const NOTE = '---\ntitle: Plain\n---\nAn ordinary note.\n';+const env = { GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true', GBRAIN_EMBEDDING_IMAGE_OCR: 'false' };+const origFetch = globalThis.fetch;+let providerCalls = 0;function git(root: string, ...args: string[]): string {return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();@@ -40,8 +54,11 @@ function commit(root: string, message: string): string {git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);return git(root, 'rev-parse', 'HEAD');}-/** A Git source claimed by this host; `before` runs while managed persistence is still off. */-async function managedSource(engine: BrainEngine, files: Record<string, string>, before?: (sourceId: string, root: string) => Promise<void>) {+/**+ * A Git source claimed by this host; `files` maps a path to Markdown text, the AVIF fixture or raw PNG bytes.+ * `legacyImages` are imported metadata-only through the legacy writer before managed persistence is on (vectorless pages).+ */+async function managedSource(engine: BrainEngine, files: Record<string, string | Buffer>, legacyImages: string[] = []) {const sourceId = `i${randomUUID().replace(/-/g, '').slice(0, 20)}`;const root = join(home, sourceId); mkdirSync(join(root, 'notes'), { recursive: true });git(root, 'init', '-q');@@ -51,7 +68,7 @@ async function managedSource(engine: BrainEngine, files: Record<string, string>,const head = commit(root, 'initial');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,\'{}\')', [sourceId, root]);- await before?.(sourceId, root);+ for (const path of legacyImages) expect((await importImageFile(engine, join(root, path), path, { sourceId, noEmbed: true })).status).toBe('imported');await claimWorktree(engine, sourceId, root);await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');return { sourceId, root, head };@@ -64,6 +81,13 @@ async function heldPaths(engine: BrainEngine, sourceId: string) {const [holds] = await readGitSourceHolds(engine, { sourceIds: [sourceId] });return (holds?.holds ?? []).map(hold => [hold.path, hold.code]).sort();}+async function imagePage(engine: BrainEngine, sourceId: string, slug: string) {+ const [row] = await engine.executeRaw<{ source_path: string | null; page_kind: string; has_vector: boolean; sealed: boolean }>(+ `SELECT p.source_path, p.page_kind, p.text_projection_revision IS NOT DISTINCT FROM p.knowledge_revision AS sealed,+ EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id AND c.embedding_image IS NOT NULL) AS has_vector+ FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL`, [sourceId, slug]);+ return row ?? null;+}beforeAll(async () => {const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);@@ -73,6 +97,22 @@ beforeAll(async () => {}}, 120_000);+beforeEach(() => {+ providerCalls = 0;+ // The Voyage multimodal endpoint is a fetch stub (one 1024-d vector per input); text embedding runs through the SDK transport seam (1536-d).+ globalThis.fetch = (async (url: unknown, init?: { body?: string }) => {+ if (!String(url).includes('voyageai.com')) return origFetch(url as string, init as RequestInit);+ providerCalls++;+ const n = (init?.body ? JSON.parse(init.body) as { inputs?: unknown[] } : {}).inputs?.length ?? 1;+ return new Response(JSON.stringify({ data: Array.from({ length: n }, (_, index) => ({ embedding: Array.from({ length: 1024 }, () => 0.1), index })),+ model: 'voyage-multimodal-3', usage: { total_tokens: 10 * n } }), { status: 200, headers: { 'Content-Type': 'application/json' } });+ }) as unknown as typeof fetch;+ __setEmbedTransportForTests((async (args: { values: unknown[] }) => ({ embeddings: args.values.map(() => Array.from({ length: 1536 }, () => 0.1)) })) as never);+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_multimodal_model: 'voyage:voyage-multimodal-3', embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'test-key', VOYAGE_API_KEY: 'test-key' } });+});+afterEach(() => { globalThis.fetch = origFetch; __setEmbedTransportForTests(null); resetGateway(); });+afterAll(async () => {await withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }@@ -81,105 +121,101 @@ afterAll(async () => {rmSync(home, { recursive: true, force: true });});-describe('#5493 managed sync with multimodal embedding on', () => {- test('a committed image is held on first and incremental sync; the Markdown imports and the checkpoint advances', async () =>- withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {+describe('managed sync imports images when multimodal embedding is on (#5493 held them, #6529 imports them)', () => {+ test('a committed image imports with its image vector and source_path on the first and an incremental sync; nothing is held', async () =>+ withEnv(env, async () => {for (const engine of engines) {- const { sourceId, root, head } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/photo.png': IMAGE });+ providerCalls = 0;+ const { sourceId, root, head } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/photo.png': PNG });const preview = await performManagedSync(engine, { sourceId, noPull: true, dryRun: true });- expect(preview.would_hold?.map(item => [item.path, item.code])).toEqual([['notes/photo.png', CODE]]);+ expect(preview.would_hold ?? []).toEqual([]);const first = await performManagedSync(engine, { sourceId, noPull: true });expect(first.status).toBe('first_sync');- expect(first.added).toBe(1);- expect(first.held_count).toBe(1);- expect(first.held?.map(item => [item.path, item.code, item.stale])).toEqual([['notes/photo.png', CODE, false]]);- expect(first.held![0].docs).toBe(`docs/guides/write-refusals.md#${CODE}`);- expect(await engine.getPage('notes/plain', { sourceId })).not.toBeNull();- expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2', [sourceId, 'notes/photo.png'])).toEqual([]);+ expect(first.added).toBe(2);+ expect(first.held_count ?? 0).toBe(0);+ expect(await heldPaths(engine, sourceId)).toEqual([]);expect(await lastCommit(engine, sourceId)).toBe(head);- expect(await heldPaths(engine, sourceId)).toEqual([['notes/photo.png', CODE]]);- const lines: string[] = [];- printHoldNotes(first, line => lines.push(line));- expect(lines.some(line => line.startsWith(` Held notes/photo.png: ${CODE}`))).toBe(true);+ expect(await imagePage(engine, sourceId, 'notes/photo.png')).toEqual({ source_path: 'notes/photo.png', page_kind: 'image', has_vector: true, sealed: true });+ expect(providerCalls).toBeGreaterThanOrEqual(1);- copyFileSync(IMAGE, join(root, 'notes', 'second.webp'));+ // An unchanged image is a hash no-op: no provider call on the next run.+ providerCalls = 0;+ copyFileSync(IMAGE, join(root, 'notes', 'second.avif'));writeFileSync(join(root, 'notes', 'later.md'), '---\ntitle: Later\n---\nA note committed after the first sync.\n');const next = commit(root, 'incremental');const incremental = await performManagedSync(engine, { sourceId, noPull: true });expect(incremental.status).toBe('synced');- expect(incremental.held?.map(item => [item.path, item.code])).toEqual([['notes/second.webp', CODE]]);- expect(await engine.getPage('notes/later', { sourceId })).not.toBeNull();+ expect(incremental.held_count ?? 0).toBe(0);expect(await lastCommit(engine, sourceId)).toBe(next);- expect(await heldPaths(engine, sourceId)).toEqual([['notes/photo.png', CODE], ['notes/second.webp', CODE]]);+ expect(await imagePage(engine, sourceId, 'notes/second.avif')).toMatchObject({ source_path: 'notes/second.avif', has_vector: true });+ expect(providerCalls).toBe(1);++ providerCalls = 0;+ const again = await performManagedSync(engine, { sourceId, noPull: true, full: true });+ expect(again.status).not.toBe('blocked');+ expect(providerCalls).toBe(0);+ expect(await imagePage(engine, sourceId, 'notes/photo.png')).toMatchObject({ has_vector: true });}- }), 180_000);+ }), 240_000);- test('held images are re-screened later: on change, on retry-held, and released when they leave the source', async () =>- withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {+ test('a hold written before this release is re-screened and imported once multimodal embedding is on', async () =>+ withEnv(env, async () => {for (const engine of engines) {- const { sourceId, root } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/a.png': IMAGE, 'notes/b.png': IMAGE });- expect((await performManagedSync(engine, { sourceId, noPull: true })).held_count).toBe(2);-- writeFileSync(join(root, 'notes', 'a.png'), 'changed image bytes');- commit(root, 'change image');- const changed = await performManagedSync(engine, { sourceId, noPull: true });- expect(changed.held?.map(item => item.path)).toEqual(['notes/a.png']);-- const [holds] = await readGitSourceHolds(engine, { sourceIds: [sourceId] });- await requestGitHoldRetry(engine, sourceId, holds!.incarnation, ['notes/b.png']);- const retried = await performManagedSync(engine, { sourceId, noPull: true });- expect(retried.held?.map(item => item.path)).toEqual(['notes/b.png']);-- git(root, 'rm', '-q', 'notes/a.png');- commit(root, 'remove image');- await performManagedSync(engine, { sourceId, noPull: true });- expect(await heldPaths(engine, sourceId)).toEqual([['notes/b.png', CODE]]);+ // The image is committed but synced while multimodal was off (not an entry); an older gbrain then held it.+ const { sourceId, root, head } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/held.png': PNG });+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'false' }, async () => {+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).toBe('first_sync');+ });+ expect(await imagePage(engine, sourceId, 'notes/held.png')).toBeNull();+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);+ const blob = readTreeBlobs(root, head, ['notes/held.png']).get('notes/held.png')!;+ const now = new Date().toISOString();+ await writeGitHold(engine, { source_id: sourceId, incarnation: source.incarnation, path: 'notes/held.png', source_path: 'notes/held.png', slug: 'notes/held.png', page_id: null,+ code: HOLD, message: 'notes/held.png is an image, which managed sync does not import yet; the rest of the source synced.', upstream_version: sha256(PNG.toString('utf8')),+ observed_at: now, run_id: null, mode: 'managed', meta: { recovery_version: 1, blob_oid: blob.oid } });+ expect(await heldPaths(engine, sourceId)).toEqual([['notes/held.png', HOLD]]);++ const synced = await performManagedSync(engine, { sourceId, noPull: true });+ expect(synced.status).not.toBe('blocked');+ expect(await imagePage(engine, sourceId, 'notes/held.png')).toMatchObject({ source_path: 'notes/held.png', has_vector: true });+ expect(await heldPaths(engine, sourceId)).toEqual([]);}- }), 180_000);+ }), 240_000);- test('deleting or renaming an image deletes its page; the renamed-to path is held', async () =>- withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {+ test('with multimodal embedding off, the image hold names the flag that turns the importer on', () => {+ const hold = managedImageHold({ path: 'notes/photo.png', sourcePath: 'notes/photo.png', working: false, slug: 'notes/photo.png' }, null, null);+ expect(hold.code).toBe(HOLD);+ expect(hold.message).toContain('GBRAIN_EMBEDDING_MULTIMODAL=true');+ });++ test('deleting an image deletes its page; renaming one moves it to the new slug', async () =>+ withEnv(env, async () => {for (const engine of engines) {- const { sourceId, root } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/old.png': IMAGE, 'notes/moved.png': IMAGE },- async (id, dir) => {- for (const path of ['notes/old.png', 'notes/moved.png']) expect((await importImageFile(engine, join(dir, path), path, { sourceId: id, noEmbed: true })).error).toBeUndefined();- });- const live = async (path: string) => (await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL', [sourceId, path])).length;- const first = await performManagedSync(engine, { sourceId, noPull: true });- expect(first.status).toBe('first_sync');- expect(first.held?.map(item => [item.path, item.stale])).toEqual([['notes/moved.png', true], ['notes/old.png', true]]);+ providerCalls = 0;+ const { sourceId, root } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/old.png': PNG, 'notes/moved.png': Buffer.concat([PNG, Buffer.from([0])]) });+ const live = async (path: string) => (await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL', [sourceId, path])).length;+ expect((await performManagedSync(engine, { sourceId, noPull: true })).added).toBe(3);expect([await live('notes/old.png'), await live('notes/moved.png')]).toEqual([1, 1]);git(root, 'rm', '-q', 'notes/old.png');commit(root, 'remove image');- await performManagedSync(engine, { sourceId, noPull: true, full: true });+ const removed = await performManagedSync(engine, { sourceId, noPull: true });+ expect(removed.status).toBe('synced');+ expect(removed.deleted).toBe(1);expect([await live('notes/old.png'), await live('notes/moved.png')]).toEqual([0, 1]);- expect(await heldPaths(engine, sourceId)).toEqual([['notes/moved.png', CODE]]);+ providerCalls = 0;git(root, 'mv', 'notes/moved.png', 'notes/archived.png');const next = commit(root, 'rename image');const renamed = await performManagedSync(engine, { sourceId, noPull: true });expect(renamed.status).toBe('synced');- expect(renamed.held?.map(item => [item.path, item.code])).toEqual([['notes/archived.png', CODE]]);+ expect(renamed.renamed).toBe(1);expect(await lastCommit(engine, sourceId)).toBe(next);+ expect([await live('notes/moved.png'), await live('notes/archived.png')]).toEqual([0, 1]);+ expect(await imagePage(engine, sourceId, 'notes/archived.png')).toMatchObject({ source_path: 'notes/archived.png', has_vector: true });+ expect(await heldPaths(engine, sourceId)).toEqual([]);}- }), 180_000);-- test('image holds are incomplete coverage, not a generator fault: they never escalate the sync result or doctor', async () =>- withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {- for (const engine of engines) {- await engine.setConfig('sync.hold_escalate_count', '1');- try {- const { sourceId } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/a.png': IMAGE, 'notes/b.png': IMAGE, 'notes/c.png': IMAGE });- const result = await performManagedSync(engine, { sourceId, noPull: true });- expect(result.held_count).toBe(3);- expect(result.holds_escalated).toBeUndefined();- const check = await gitHeldFilesCheck(engine, [sourceId]);- expect(check.status).toBe('warn');- expect((check.details as { held: number }).held).toBe(3);- } finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.hold_escalate_count'"); }- }- }), 180_000);+ }), 240_000);});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex bf09f798d8..0ebedd9ad4 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -25,7 +25,9 @@ test/decide/conflict-proposals-managed.test.tstest/declared-lineage-visibility.test.tstest/derived-link-reconciliation.test.tstest/doctor-frontmatter-holds.test.ts+test/doctor-image-embedding-coverage.test.tstest/doctor-routing-skill-pack-source.test.ts+test/embed-stale-images-managed-6529.test.tstest/embedding-completion-atomic.serial.test.tstest/engine-sql-facts-keyset.test.tstest/extract-all-stamp-intersection.serial.test.tsdiff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.tsindex ac28c1aa03..e3dfbd4792 100644--- a/test/trust-write-gate-drift.test.ts+++ b/test/trust-write-gate-drift.test.ts@@ -44,6 +44,7 @@ const EXEMPT: Record<string, string> = {'src/core/persistence/connector-google-receipts.ts': 'connector delivery receipts; the connector page publication is gated (connector-sync.ts)','src/core/persistence/file-repair.ts': 'publishes an owner-reviewed repair preview of the owner source','src/core/persistence/grandfather.ts': 'mechanical validate:false stamp under withTrustKeep',+ 'src/core/persistence/sync-image.ts': 'managed sync image import of an owner-committed file through importImageFile, which has no gate seam (its page text is gbrain-generated OCR/caption); import-prepare.ts takes the same image path','src/core/persistence/links-maintenance.ts': 'link extraction from stored page text','src/core/persistence/loop-fact-retirement.ts': 'expires a loop fact (lifecycle)','src/core/persistence/memory-mutations.ts': 'forget (lifecycle); remember is gated in memory-prepare.ts',