Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: report the work that did not happen (#7193)

garrytand828604d83a9
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 58a3adf7eb..b3cd32d853 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -38,6 +38,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`.
- `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--retry-parked] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. `--retry-parked` retries parked tombstones once within `--older-than` and rename holds; the dry run lists `parked`, `retried` and `blocked`, and the consent names the parked count. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. `pages ghosts [--source <id>] [--json]` (#6696 B5, `pages-ghosts.ts`) lists ghost pages read-only through `scanGhostSource`. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).
-- `src/commands/pages-unsearchable.ts` — `gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json]` (#6696 B3, read-only): one row per (page, embedding state) from `listEmbeddingStateRows` with reason, chunks, bytes and the state's rendered fix; every state but `embedded` unless `--state` names one; `--limit` 1-1000 (default 50) with `complete`; an unknown `--state` or bad `--limit` throws `invalid_params` naming the valid values. Test: `test/pages-unsearchable.test.ts`.
+- `src/commands/pages-unsearchable.ts` — `gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json]` (#6696 B3, read-only): one row per (page, embedding state) from `listEmbeddingStateRows` with reason, chunks, bytes and the state's rendered fix; every state but `embedded` unless `--state` names one; `--limit` 1-1000 (default 50) with `complete`; an unknown `--state` or bad `--limit` throws `invalid_params` naming the valid values; adds `semantic_unsearchable` (+keyword_only) and `awaiting_sync` (held files) (#7193). Test: `test/pages-unsearchable.test.ts`.
- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration,transfer-administration}.ts` — trusted local `sources writer status|failures|claim|transfer` (failures: [Managed sync bookkeeping](managed-sync-bookkeeping.md)) and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts. `transfer-administration.ts` owns `transfer prepare|accept|cancel`: `cancel <source> --expected-epoch <n>` (intent `writer_transfer_cancel`, `--dry-run` previews) runs `cancelWriterTransfer` in `ownership.ts` on the owner host under the coordination lock and `FOR UPDATE`, requires `draining` at that epoch, returns the worktree to `active` and clears the prepared manifest while keeping the epoch, so an accept bound to it refuses `writer_transfer_conflict`. Prepare stamps `prepared_at`. Test: `test/pathological/c5-writer-transfer-cancel.test.ts` (both engines).
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index aec9a3f82e..cb7b2c2a76 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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`. Wave B: a segmented page is embedded by `page-body/segmented-embedding.ts` (vector-less live rows by chunk_index keyset with the title and plain tier, metered per page, installed by chunk_index and exact text onto rows still in the live generation; never the body or every chunk), from here, `gbrain embed` and the post-commit embedding effect (`data.occurrence_ids` limits an append's effect to the new occurrences).
- `src/core/content-drift-sweep.ts` — the content-drift sweep (#4246) as a resumable pass: `runContentDriftSweep(engine, { sourceId?, signal?, deadline?, stopped?, assertOwned?, timeBudgetMs?, batchRows? })` runs `engine-sql/chunks.ts` `invalidateContentDriftBatch` (5,000 chunk rows past the cursor in id order, bounded before any md5) one transaction per batch, committing the cursor in config row `embed.content_drift_sweep.<column>.<all|source:id>` with the batch under a `FOR UPDATE` lock on that row, so concurrent runs share one pass. A run stops at its 60 s budget, the job deadline or an abort; a completed pass restarts after `embed.content_drift.pass_interval_hours` (default 24) unless it fit in one batch. A failed batch is returned as `state: 'failed'` with the error and recorded as `last_error` (cleared by the next committed batch); a missing v133/v221 column is `unsupported`; an `assertOwned` throw propagates. `embedAllStale` (`EmbedResult.content_drift`), `embedStaleForSource` (`contentDrift`) and the embed, embed-backfill and cycle embed results carry the status; doctor `content_drift_sweep` reads the saved rows.
-- `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: an unsealed page only in the `reimport` class (`page-state/projection-class.ts`; `sealable`, `protected` and `archived` are counted, never candidates), a sealed one with no `embedding_image` chunk or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true` (`incomplete_sealed`); `ocr_required` counts distrusted reimport pages (the dry run's expectation with OCR off, the importer's refusals after a run), 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-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: an unsealed page only in the `reimport` class (`page-state/projection-class.ts`; `sealable`, `protected` and `archived` are counted, never candidates), a sealed one with no `embedding_image` chunk or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true` (`incomplete_sealed`); `ocr_required` counts distrusted reimport pages (the dry run's expectation with OCR off, the importer's refusals after a run), 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. An explicit `--images` run that rebuilds none of its candidates (files missing, left unchanged or needing OCR) reports `status: nothing_rebuilt` with a `reason` by cause and counts every candidate as failed, so it exits 1 (#7193; `test/image-distrusted-reimport.test.ts`).
- `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/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index f2155e7851..dfb0a6a6b3 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -404,6 +404,14 @@ completes in seconds on an 80K-page PGLite brain.
runs `gbrain pages unsearchable --source <id> --json` (read-only) and follows
each row's `fix`.
+`unsearchable` (the count doctor and `get_brain_health` report) leaves out
+`keyword_only` chunks, which keyword search reads but vector search cannot;
+`semantic_unsearchable` adds them, and the human headline leads with it.
+`awaiting_sync` counts files no state can see yet because sync holds them
+(`new_files` with no page, `stale_pages` whose newer file is held) and the
+source's sync freshness; `gbrain sync status --source <id> --json` says why.
+An unknown `--source` names the source it most likely meant.
+
Every chunk, and every live page with no chunk row, is in exactly one state,
derived from the rows against the active embedding column (no stored status):
diff --git a/llms-full.txt b/llms-full.txt
index 876bf92711..e915ea5414 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10785,6 +10785,14 @@ completes in seconds on an 80K-page PGLite brain.
runs `gbrain pages unsearchable --source <id> --json` (read-only) and follows
each row's `fix`.
+`unsearchable` (the count doctor and `get_brain_health` report) leaves out
+`keyword_only` chunks, which keyword search reads but vector search cannot;
+`semantic_unsearchable` adds them, and the human headline leads with it.
+`awaiting_sync` counts files no state can see yet because sync holds them
+(`new_files` with no page, `stale_pages` whose newer file is held) and the
+source's sync freshness; `gbrain sync status --source <id> --json` says why.
+An unknown `--source` names the source it most likely meant.
+
Every chunk, and every live page with no chunk row, is in exactly one state,
derived from the rows against the active embedding column (no stored status):
diff --git a/src/commands/pages-unsearchable.ts b/src/commands/pages-unsearchable.ts
index a47fd8626b..6a910c29eb 100644
--- a/src/commands/pages-unsearchable.ts
+++ b/src/commands/pages-unsearchable.ts
@@ -5,12 +5,20 @@
* the state's protocol fix. States and their exits: src/core/embedding-state.ts.
* Without `--state` every state but `embedded` is listed. The listing is
* bounded (`--limit`, default 50); `complete: false` means more rows exist.
+ *
+ * #7193: `unsearchable` keeps its doctor meaning; `semantic_unsearchable` adds
+ * the `keyword_only` units vector search cannot reach, and the headline leads
+ * with it. `awaiting_sync` counts files no state can see yet: the source's
+ * held files (new files with no page, pages whose newer file is held) and its
+ * sync freshness, when a resident reports it.
*/
import type { BrainEngine } from '../core/engine.ts';
import { cliRenderContext, renderAction } from '../core/agent-output.ts';
import { opError } from '../core/ops/contract.ts';
import { resolveSourceId } from '../core/source-resolver.ts';
import { embeddingsDisabled } from '../core/embedding-disabled.ts';
+import { readHeldCoverage } from '../core/persistence/held-reads.ts';
+import { readSourceFreshness } from '../core/notifier/status.ts';
import {
DELETED_PAGE_PURGE_WINDOW_HOURS, EMBEDDING_STATE_DOCS, EMBEDDING_STATES, embeddingStateFix, readEmbeddingState,
type EmbeddingState, type EmbeddingStateRow,
@@ -77,12 +85,22 @@ export async function runPagesUnsearchable(engine: BrainEngine, args: string[]):
};
});
const complete = found.length <= parsed.limit;
+ const semanticUnsearchable = summary.unsearchable === null ? null : summary.unsearchable + (summary.counts.keyword_only ?? 0);
+ const [held] = await readHeldCoverage(engine, { sourceId });
+ const [freshness] = await readSourceFreshness(engine, { sourceId }, held ? [held] : []);
+ const awaitingSync = { held_files: (held?.missing ?? 0) + (held?.stale ?? 0), new_files: held?.missing ?? 0, stale_pages: held?.stale ?? 0,
+ sync_state: freshness?.state ?? 'not_reported' };
if (parsed.json) {
console.log(JSON.stringify({ source_id: sourceId, state: parsed.state, limit: parsed.limit, complete, active_column: summary.active_column,
- counts: summary.counts, unsearchable: summary.unsearchable, rows }, null, 2));
+ counts: summary.counts, unsearchable: summary.unsearchable, semantic_unsearchable: semanticUnsearchable, awaiting_sync: awaitingSync, rows }, null, 2));
return;
}
- console.log(`Source ${sourceId} (active column '${summary.active_column}'): ${summary.unsearchable} unsearchable; ${EMBEDDING_STATES.map(s => `${s} ${summary.counts[s] ?? 0}`).join(', ')}.`);
+ console.log(`Source ${sourceId} (active column '${summary.active_column}'): ${semanticUnsearchable} not reachable by vector search (${summary.unsearchable} unsearchable + `
+ + `${summary.counts.keyword_only ?? 0} keyword_only); ${EMBEDDING_STATES.map(s => `${s} ${summary.counts[s] ?? 0}`).join(', ')}.`);
+ if (awaitingSync.held_files > 0 || awaitingSync.sync_state === 'behind') {
+ console.log(`Not yet in any state: ${awaitingSync.held_files} file(s) held by sync (${awaitingSync.new_files} new, ${awaitingSync.stale_pages} newer than their page); sync ${awaitingSync.sync_state}. `
+ + `gbrain sync status --source ${sourceId} --json shows why.`);
+ }
if (rows.length === 0) { console.log(parsed.state ? `No pages in state ${parsed.state}.` : 'Nothing unsearchable.'); return; }
for (const row of rows) {
console.log(` ${row.state.padEnd(20)} ${row.slug} chunks=${row.chunks} bytes=${row.bytes} ${row.reason}`);
diff --git a/src/core/embed-stale-images.ts b/src/core/embed-stale-images.ts
index 42b06c5100..7c292bd5e1 100644
--- a/src/core/embed-stale-images.ts
+++ b/src/core/embed-stale-images.ts
@@ -65,6 +65,9 @@ export interface StaleImageSweepResult extends EmbedCostStopFields {
failure_samples: string[];
/** Up to 5 `source:slug: no file at <path tried>` lines for the candidates without a source file. */
missing_samples: string[];
+ /** #7193: the explicit `--images` sweep rebuilt none of its candidates (exit 1); `reason` says why, by cause. */
+ status?: 'nothing_rebuilt';
+ reason?: string;
}
const SAMPLE_CAP = 5;
@@ -142,9 +145,20 @@ export async function embedStaleImages(
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;
+/**
+ * Candidates and nothing rebuilt: the explicit `--images` sweep did no work, so it must not read as success (#7193: not
+ * only when every file is missing; files the importer left unchanged or refused for want of OCR count too). Every
+ * unrebuilt candidate becomes a failure, so the exit is 1 (agent operator protocol: failed), and `reason` names the causes.
+ */
+function markNothingRebuilt(result: StaleImageSweepResult): void {
+ if (result.candidates === 0 || result.rebuilt > 0) return;
+ result.status = 'nothing_rebuilt';
+ result.reason = `rebuilt 0 of ${result.candidates} candidate image page(s): ${result.missingFile} missing source file, ${result.skipped} left unchanged by the importer, `
+ + `${result.ocr_required} need a fresh OCR pass (GBRAIN_EMBEDDING_IMAGE_OCR=true), ${result.failures} failed`;
+ const missingOnly = result.missingFile === result.candidates;
+ result.failures = result.candidates;
+ result.failure_samples.push(...result.missing_samples.slice(0, SAMPLE_CAP - result.failure_samples.length));
+ if (!missingOnly) result.failure_samples.push(result.reason);
}
/**
@@ -184,11 +198,8 @@ 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 (!dryRun && !capped) markNothingRebuilt(result);
if (capped) noteEmbedCostStop(result, capped, args);
if (args.includes('--json')) console.log(JSON.stringify(result));
else {
@@ -199,6 +210,7 @@ export async function runEmbedStaleImagesCli(engine: BrainEngine, args: string[]
}
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 (result.reason) serr(`[embed] images: nothing rebuilt; ${result.reason}.`);
if (capped) (args.includes('--json') ? serr : console.log)(embedCostStopVerdict(result, capped));
return result;
}
diff --git a/src/core/minions/handlers/embed-backfill.ts b/src/core/minions/handlers/embed-backfill.ts
index 0e065a5543..847aea5d3c 100644
--- a/src/core/minions/handlers/embed-backfill.ts
+++ b/src/core/minions/handlers/embed-backfill.ts
@@ -49,7 +49,7 @@ import type { ContentDriftSweepStatus } from '../../content-drift-sweep.ts';
import { createEmbedStallWatchdog, resolveEmbedStallAbortSeconds } from '../../embed-stall.ts';
import { currentEmbeddingSignature } from '../../embedding.ts';
import { readEmbedBackfillBlockers } from '../../embed-backfill-stall.ts';
-import { budgetLimitedField, type BudgetLimitedReport } from '../../held-embedding.ts';
+import { budgetLimitedField, readBudgetLimited, type BudgetLimitedReport } from '../../held-embedding.ts';
import { UnrecoverableError } from '../errors.ts';
import { type DbPacer, createDbPacer, createNoopPacer } from '../../db-pacer.ts';
import { resolvePaceMode, loadPaceModeConfig, readPaceEnv } from '../../pace-mode.ts';
@@ -370,7 +370,11 @@ export function makeEmbedBackfillHandler(
// in a row while an entire corpus sat stripped. NULLed chunks stay NULL
// for the next (fixed-config) run to pick up.
if ((result.remaining ?? 0) > 0 || (result.blocked ?? 0) > 0) {
- const message = `embed-backfill: incomplete; ${result.remaining ?? 0} chunks remain and ${result.blocked ?? 0} projections are blocked. Durable progress is retained; inspect provider and projection readiness before retrying.`;
+ // #7193: the stale count leaves out large pages held for approval or at their cap; the remainder names them too.
+ const held = await readBudgetLimited(engine, { sourceId, signature: currentEmbeddingSignature() }).catch(() => null);
+ const heldNote = held && held.pending_chunks > 0
+ ? ` (${held.pending_chunks} of them on ${held.held + held.capped} large page(s) held for approval or at their spend cap; gbrain embed --held --dry-run --source ${sourceId} lists them)` : '';
+ const message = `embed-backfill: incomplete; ${(result.remaining ?? 0) + (held?.pending_chunks ?? 0)} chunks remain${heldNote} and ${result.blocked ?? 0} projections are blocked. Durable progress is retained; inspect provider and projection readiness before retrying.`;
// #6803: a run that embedded nothing records its blocker fingerprint, so
// automatic submission backs off and stops after identical failures
// (embed-backfill-stall.ts); a retry of this job that finds the same
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index b3b5c2a880..6c34995daa 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -622,14 +622,33 @@ async function assertSourceExists(engine: BrainEngine, id: string): Promise<void
[id],
);
if (rows.length === 0) {
+ const nearest = await nearestSourceId(engine, id);
throw new SourceTargetError(
`Source "${id}" not found or is archived. Available active sources: ` +
`run \`gbrain sources list\` to see registered sources, ` +
- `or create/restore "${id}" before retrying.`,
+ `or create/restore "${id}" before retrying.${nearest ? ` Did you mean "${nearest}"?` : ''}`,
);
}
}
+/**
+ * #7193: the active source an unknown id most likely meant: the one whose id or name it names exactly or is the only
+ * prefix of (`notes` for `notes-brain`), else the nearest id by edit distance (levenshtein.ts). Never throws.
+ */
+async function nearestSourceId(engine: BrainEngine, id: string): Promise<string | null> {
+ try {
+ const sources = await engine.executeRaw<{ id: string; name: string | null }>('SELECT id, name FROM sources WHERE archived = false ORDER BY id');
+ const named = sources.filter(s => s.name === id);
+ if (named.length === 1) return named[0]!.id;
+ const prefixed = sources.filter(s => s.id.startsWith(id) || (s.name ?? '').startsWith(id));
+ if (prefixed.length === 1) return prefixed[0]!.id;
+ const { suggestNearest } = await import('./levenshtein.ts');
+ return suggestNearest(id, sources.map(s => s.id));
+ } catch {
+ return null;
+ }
+}
+
/**
* Predicate: is this error one of THIS module's user-facing throws (an
* unknown / archived source from `assertSourceExists`, or an invalid
diff --git a/test/held-embedding-budgets.test.ts b/test/held-embedding-budgets.test.ts
index 60df7aa72d..d39b0a5ec4 100644
--- a/test/held-embedding-budgets.test.ts
+++ b/test/held-embedding-budgets.test.ts
@@ -204,5 +204,16 @@ for (const backend of testBackends()) {
expect(result.budget_limited!.by_source[0]!.fix.command).toMatch(/^gbrain embed --held --source default --max-usd \d+\.\d\d/);
expect(await budgetLimitedField(engine, 'alpha', null)).toMatchObject({ budget_limited: { held: 1 } });
}, 60_000);
+
+ test('#7193: an incomplete embed-backfill counts the held pages\' chunks in "N chunks remain" and names them', async () => {
+ await holdPageEmbedding(engine, await largePage('chats/held-remaining', 'default', 3), 'upgrade_backfill');
+ await holdPageEmbedding(engine, await largePage('chats/held-elsewhere', 'alpha', 2), 'upgrade_backfill');
+ const controller = new AbortController();
+ const job = { id: 1, name: 'embed-backfill', data: { sourceId: 'default' }, attempts_made: 0, signal: controller.signal, deadlineAtMs: null,
+ shutdownSignal: controller.signal, updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] } as unknown as MinionJobContext;
+ const handler = makeEmbedBackfillHandler(engine, { runStale: async () => ({ embedded: 0, chunksProcessed: 0, pagesProcessed: 0, invalidated: 0, lastCursor: null, done: true, aborted: false,
+ remaining: 2, blocked: 1, complete: false }) });
+ await expect(handler(job)).rejects.toThrow('embed-backfill: incomplete; 5 chunks remain (3 of them on 1 large page(s) held for approval or at their spend cap; gbrain embed --held --dry-run --source default lists them) and 1 projections are blocked.');
+ }, 60_000);
});
}
diff --git a/test/image-distrusted-reimport.test.ts b/test/image-distrusted-reimport.test.ts
index be95b465cb..d12132456d 100644
--- a/test/image-distrusted-reimport.test.ts
+++ b/test/image-distrusted-reimport.test.ts
@@ -16,7 +16,7 @@ import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { importImageFile, _resetOcrRunBudgetForTests } from '../src/core/import-file.ts';
-import { embedStaleImages } from '../src/core/embed-stale-images.ts';
+import { embedStaleImages, runEmbedStaleImagesCli } from '../src/core/embed-stale-images.ts';
import { operationsByName } from '../src/core/operations.ts';
import { configureGateway, resetGateway, __setGenerateTextTransportForTests } from '../src/core/ai/gateway.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -128,6 +128,24 @@ for (const backend of backends) {
}, 120_000);
}
+ test('#7193: an explicit --images sweep that rebuilds none of its candidates fails and says why', async () => {
+ const engine = await freshEngine(backend);
+ await distrustedImage(engine);
+ const logs: string[] = [];
+ const origLog = console.log;
+ console.log = (...args: unknown[]) => { logs.push(args.map(String).join(' ')); };
+ let swept: Awaited<ReturnType<typeof runEmbedStaleImagesCli>>;
+ try {
+ swept = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true', GBRAIN_EMBEDDING_IMAGE_OCR: 'false' }, () =>
+ runEmbedStaleImagesCli(engine, ['--stale', '--images', '--json']));
+ } finally { console.log = origLog; }
+ expect(swept).toMatchObject({ rebuilt: 0, ocr_required: 1, missingFile: 0, status: 'nothing_rebuilt' });
+ expect(swept.candidates).toBeGreaterThan(0);
+ expect(swept.failures).toBe(swept.candidates);
+ expect(swept.reason).toContain('1 need a fresh OCR pass (GBRAIN_EMBEDDING_IMAGE_OCR=true)');
+ expect(JSON.parse(logs.at(-1)!)).toMatchObject({ status: 'nothing_rebuilt', failures: swept.candidates });
+ }, 120_000);
+
test('a successful fresh OCR pass attests the image again', async () => {
const engine = await freshEngine(backend);
const { file, slug } = await distrustedImage(engine);
diff --git a/test/pages-unsearchable.test.ts b/test/pages-unsearchable.test.ts
index c64657c390..ba733986fb 100644
--- a/test/pages-unsearchable.test.ts
+++ b/test/pages-unsearchable.test.ts
@@ -132,6 +132,32 @@ describe('gbrain pages unsearchable', () => {
await expect(run(['--limit', '0'])).rejects.toMatchObject({ code: 'invalid_params' });
});
+ test('#7193: semantic_unsearchable adds keyword_only to unsearchable, and the headline leads with it', async () => {
+ const out = JSON.parse(await run(['--source', 'default', '--json'])) as Listing & { semantic_unsearchable: number };
+ expect(out.unsearchable).toBe(4);
+ expect(out.semantic_unsearchable).toBe(5);
+ expect(await run(['--source', 'default'])).toContain('5 not reachable by vector search (4 unsearchable + 1 keyword_only)');
+ });
+
+ test('#7193: files held behind sync are counted in awaiting_sync, which no embedding state sees', async () => {
+ const before = JSON.parse(await run(['--source', 'default', '--json'])) as { awaiting_sync: Record<string, unknown> };
+ expect(before.awaiting_sync).toEqual({ held_files: 0, new_files: 0, stale_pages: 0, sync_state: 'not_reported' });
+ const [src] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id = 'default'");
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op, fingerprint, completed_keys) VALUES ('sync-hold-summary', $1,
+ jsonb_build_array(jsonb_build_object('source_id', 'default', 'incarnation', $2::text, 'count', 3, 'stale', 1)))`, [`default:${src!.incarnation}`, src!.incarnation]);
+ const held = JSON.parse(await run(['--source', 'default', '--json'])) as { awaiting_sync: Record<string, unknown>; counts: Record<string, number> };
+ expect(held.awaiting_sync).toMatchObject({ held_files: 3, new_files: 2, stale_pages: 1 });
+ expect(held.counts.pending).toBe(3);
+ expect(await run(['--source', 'default'])).toContain('3 file(s) held by sync (2 new, 1 newer than their page)');
+ });
+
+ test('#7193: an unknown --source suggests the source it most likely meant', async () => {
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('notes-brain','notes-brain') ON CONFLICT DO NOTHING");
+ await expect(run(['--source', 'notes'])).rejects.toThrow('Did you mean "notes-brain"?');
+ await expect(run(['--source', 'defalt'])).rejects.toThrow('Did you mean "default"?');
+ await expect(run(['--source', 'zzzzzzzz'])).rejects.toThrow(/not found or is archived\. Available active sources: run `gbrain sources list` to see registered sources, or create\/restore "zzzzzzzz" before retrying\.$/);
+ });
+
test('human output names each row and its fix', async () => {
const out = await run(['--source', 'default']);
expect(out).toContain('pending');