Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embed): the folded image sweep reports fileless pages without failing the text run (#6529)

garrytan2979da07ccd9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec1cfd9715..0efd925dbc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,12 +12,12 @@ identifiers and attribution are available in the pre-removal Git revision
## [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.
+**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: every sweep names the first path it tried, and the explicit `--images` sweep 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`.
+- **`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 an explicit `--images` 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`: image import failures count, while fileless image pages are reported (`images.missingFile`, one stderr line naming the first path tried) and leave the exit code to the text run, so a routine `embed --stale` stays green over an out-of-scope backlog of fileless pages; 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.
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index fc38dc5d7b..2796cc5983 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; 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-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; the explicit `--images` CLI (`runEmbedStaleImagesCli`) counts an all-missing, nothing-rebuilt sweep as failures (`sweepFoundNoFiles`), 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`: import failures count toward the run's failures, fileless pages are reported once on stderr (`missingFile`, first sample) and leave the exit code to the text run; 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/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3fd7bde91b..ef58505dc3 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -469,7 +469,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ 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`.' },
+ { 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); the folded sweep only reports fileless pages. 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/embed-stale-images.ts b/src/core/embed-stale-images.ts
index 6c24233c3b..3f864b0aa7 100644
--- a/src/core/embed-stale-images.ts
+++ b/src/core/embed-stale-images.ts
@@ -103,14 +103,14 @@ 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;
}
+/** Every candidate without a file and nothing rebuilt: the explicit `--images` sweep did no work, so it must not read as success. */
+function sweepFoundNoFiles(result: StaleImageSweepResult): boolean {
+ return result.candidates > 0 && result.rebuilt === 0 && result.missingFile === result.candidates;
+}
+
/**
* #6529: the image sweep plain `embed --stale` runs before its text drain on a
* multimodal install (`GBRAIN_EMBEDDING_MULTIMODAL=true`), so image pages get
@@ -122,10 +122,16 @@ export async function runStaleImageSweepFirst(engine: BrainEngine, opts: { sourc
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. */
+/**
+ * Folds the image sweep into the text run's result: image pages count as failures only when the sweep failed on them.
+ * Pages whose file is gone from the checkout are reported (`images.missingFile`, the first `missing_samples` line on
+ * stderr), never failed: the text run's exit code is the text run's, so a routine `embed --stale` stays green while an
+ * out-of-scope backlog of fileless image pages remains (#6529).
+ */
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.missingFile > 0) serr(`[embed] images: ${sweep.missingFile} image page(s) have no source file in the checkout and were not rebuilt (first: ${sweep.missing_samples[0]}); delete those pages or restore the files.`);
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.`);
@@ -142,6 +148,10 @@ export async function runEmbedStaleImagesCli(engine: BrainEngine, args: string[]
const srcI = args.indexOf('--source');
const dryRun = args.includes('--dry-run');
const result = await embedStaleImages(engine, { sourceId: srcI >= 0 ? args[srcI + 1] : undefined, dryRun, costCap });
+ if (sweepFoundNoFiles(result)) {
+ result.failures += result.missingFile;
+ result.failure_samples.push(...result.missing_samples.slice(0, SAMPLE_CAP - result.failure_samples.length));
+ }
const capped = costCap?.hit();
if (capped) noteEmbedCostStop(result, capped, args);
if (args.includes('--json')) console.log(JSON.stringify(result));
diff --git a/test/embed-stale-images-managed-6529.test.ts b/test/embed-stale-images-managed-6529.test.ts
index a6ad479436..3f2f380e4a 100644
--- a/test/embed-stale-images-managed-6529.test.ts
+++ b/test/embed-stale-images-managed-6529.test.ts
@@ -21,7 +21,7 @@ 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 { embedStaleImages, runEmbedStaleImagesCli } 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';
@@ -128,7 +128,7 @@ describe('#6529 embed --stale --images on a managed brain', () => {
}
}), 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 () =>
+ test('explicit --images 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;
@@ -136,7 +136,7 @@ describe('#6529 embed --stale --images on a managed brain', () => {
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 });
+ const swept = await runEmbedStaleImagesCli(engine, ['--stale', '--images', '--source', sourceId, '--json']);
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`);
@@ -145,6 +145,22 @@ describe('#6529 embed --stale --images on a managed brain', () => {
}
}), 240_000);
+ test('plain embed --stale reports fileless image pages in `images` and leaves the exit code to the text run', 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']);
+ rmSync(join(root, 'notes', 'gone.png'));
+
+ const result = await runEmbed(engine, ['--stale', '--source', sourceId, '--json']);
+ const images = result && 'images' in result ? result.images : undefined;
+ expect(images).toMatchObject({ candidates: 1, rebuilt: 0, missingFile: 1, failures: 0, failure_samples: [] });
+ expect(images?.missing_samples[0]).toContain(join(root, 'notes', 'gone.png'));
+ expect(result?.failures).toBe(0);
+ expect(providerCalls).toBe(0);
+ }
+ }), 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) {