Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
doctor: embedding_state check (BRAIN, ops tier) with registered codes and troubleshooting anchor (#6696 B3)
garrytanbe1c05cd20b9
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 287a879b7c..cf1e37c6d7 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -417,6 +417,16 @@ Reasons: `auto_chronicle_off`, `auto_chronicle_invalid`, `slug_bound_client`, `oMore: [docs/guides/life-chronicle.md#skip-and-failure-codes](../../docs/guides/life-chronicle.md#skip-and-failure-codes)+### chunkless_pages_healable++<a id="chunkless_pages_healable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Live pages have body text but no chunk rows, so search cannot read their body. | A page written without the chunking step (an enrichment stub, an interrupted write) has nothing for search to match; `gbrain embed --stale` chunks it first, which makes paid embedding calls. | List them with `gbrain pages unsearchable --state chunkless_healable --json`, then run `gbrain embed --stale --catch-up --yes` once embedding spend is approved. Run: gbrain pages unsearchable --state chunkless_healable --json | agent | `gbrain doctor --only embedding_state --json` | 1 | no |++More: [docs/guides/troubleshooting.md#embedding-state](../../docs/guides/troubleshooting.md#embedding-state)+### claim_already_used<a id="claim_already_used"></a>@@ -761,6 +771,16 @@ Reasons: `pending`, `timeout`, `error`.More: [docs/ENGINES.md#serve-deep-health](../../docs/ENGINES.md#serve-deep-health)+### deleted_page_chunks_overdue++<a id="deleted_page_chunks_overdue"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Chunks of pages soft-deleted longer than the purge window (72h) are still stored. | Search never reads them; the purge lifecycle (`gbrain pages purge-deleted`, the autopilot purge phase) hard-deletes such pages and their chunks. The purge is brain-wide and irreversible, so it needs the user. | Preview with `gbrain pages purge-deleted --dry-run --json`, then run `gbrain pages purge-deleted --yes` once the user agrees. Run: gbrain pages purge-deleted --dry-run --json | agent | `gbrain doctor --only embedding_state --json` | 1 | no |++More: [docs/guides/troubleshooting.md#embedding-state](../../docs/guides/troubleshooting.md#embedding-state)+### delta_cursor_upgrade_required<a id="delta_cursor_upgrade_required"></a>@@ -907,6 +927,16 @@ More: [docs/guides/write-refusals.md#embedding_auth_failed](../../docs/guides/wr|---|---|---|---|---|---|---|| Embedding plane split. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |+### embedding_state_unknown++<a id="embedding_state_unknown"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The ops tier could not count embedding state: the active embedding column has no covering partial index, and the ops tier never scans. | Without an index on `WHERE <active column> IS NULL`, counting vector-less chunks means a full table scan, which the bounded ops tier refuses. | Run the standard tier (`gbrain doctor --only embedding_state --json`) for exact counts. Run: gbrain doctor --only embedding_state --json | agent | `gbrain doctor --only embedding_state --json` | 1 | no |++More: [docs/guides/troubleshooting.md#embedding-state](../../docs/guides/troubleshooting.md#embedding-state)+### embedding_storage_unavailable<a id="embedding_storage_unavailable"></a>diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 262c7fd37c..4b56798677 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -360,6 +360,42 @@ completes in seconds on an 80K-page PGLite brain.<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command exactly as printed. For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count and the exceptions, and after they agree run the apply command it prints, which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*+## Embedding state++**Symptom.** Doctor `embedding_state` warns, `get_brain_health` reports+`unsearchable` above zero, or a page you know exists never shows up in search.++**Say to your agent:** *"Which pages can search not see, and why?"* The agent+runs `gbrain pages unsearchable --source <id> --json` (read-only) and follows+each row's `fix`.++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):++| State | What it means | Exit (each row's `fix`) |+|---|---|---|+| `embedded` | The chunk has a vector in the active column. | None. |+| `pending` | The embed job will embed it (no vector, page live, no `embed_skip`). Doctor `embeddings` ages this backlog and owns its warning. | `gbrain embed --stale --catch-up --source <id> --yes` (paid; preview with `--dry-run`). On a brain keyless by choice keyword search reads these chunks and they do not count as unsearchable. |+| `keyword_only` | The page carries `embed_skip`: the import gate found its body over `content_sanity.bytes_block` (info, by design; its chunks still feed keyword search and are never purged). Removing the marker alone is undone on the next import. | Split the page, or, after the operator approves, `gbrain config set content_sanity.bytes_block <bytes>` then `gbrain sync --source <id> --full`, which re-imports and embeds it. |+| `quarantined` | The content-quality gate hid the page as junk; it has no searchable chunks. Doctor `quarantined_pages` owns its warning. | Review with `gbrain quarantine list --json`; clear a false positive with `gbrain quarantine clear <slug> --source-id <id> --force` (the owner's call). |+| `empty` | A live page with no body text: nothing to index. | Write content to it, or delete the stub (`gbrain delete <slug> --source <id> --force`, restorable) after the user agrees. |+| `deleted_page_chunks` | Chunks of a soft-deleted page. Search never reads them; the purge lifecycle removes them after 72 h (info until then, a warning past it, code `deleted_page_chunks_overdue`). | `gbrain pages purge-deleted --dry-run --json`, then `gbrain pages purge-deleted --yes` once the user agrees (brain-wide, irreversible). |+| `chunkless_healable` | A live page with body text but no chunk rows (written without the chunking step). Doctor warns on a keyed brain (code `chunkless_pages_healable`). | `gbrain embed --stale --catch-up --source <id> --yes` chunks and embeds it (paid). |++`unsearchable` sums `pending`, `quarantined`, `empty` and `chunkless_healable`;+`keyword_only` and `deleted_page_chunks` never count. The doctor's ops tier+reads only index-backed counts: vector-less chunks through the partial index+`WHERE <active column> IS NULL` (`content_chunks_stale_idx` for the default+`embedding` column), gated and deleted pages through their indexes, and+`embedded` as a planner estimate (`basis: estimated`); it omits `empty` and+`chunkless_healable` (`unsearchable_complete: false`). A registry-routed brain+whose active column has no such index reports `unknown` there (code+`embedding_state_unknown`, never a slow scan); the standard tier+(`gbrain doctor --only embedding_state --json`) counts every state exactly.+Pending chunks written by a binary older than the pending-age stamp carry no+age: `details.unstamped_pending` gives their count, this writer's version and+a `created_at` lower bound, and never warns on its own.+## Hybrid search returns only keyword hits**Symptom.** On a large Postgres brain, `gbrain query` answers look keyword-only,diff --git a/src/commands/doctor/checks/embedding-state.ts b/src/commands/doctor/checks/embedding-state.tsnew file mode 100644index 0000000000..55abc7972c--- /dev/null+++ b/src/commands/doctor/checks/embedding-state.ts@@ -0,0 +1,73 @@+/**+ * Doctor `embedding_state` (#6696 B3, BRAIN): where indexed text stands against+ * the ACTIVE embedding column, from the derived classifier in+ * src/core/embedding-state.ts. The ops tier reads only index-backed counts+ * (unknown without a covering partial index); every other tier counts exactly.+ *+ * It warns only on what no other check owns: chunks of pages soft-deleted+ * longer than the purge window (fix: `gbrain pages purge-deleted`), and live+ * pages with body text but no chunk rows on a keyed brain (fix: `gbrain embed+ * --stale`). The pending backlog stays the `embeddings` check's warning (it+ * ages the backlog; this check only counts it), and quarantined pages stay+ * `quarantined_pages`'. keyword_only (embed_skip by design), deleted chunks+ * still inside the window and a brain keyless by choice are information.+ */+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { agentFix, checkError, doctorVerify, infoCheck, keylessEnablementFix } from '../check-fix.ts';+import { EMBEDDING_STATE_DOCS, embeddingStateFix, readEmbeddingState, type EmbeddingState } from '../../../core/embedding-state.ts';++const LABELS: Record<EmbeddingState, string> = {+ embedded: 'embedded', pending: 'pending', keyword_only: 'keyword-only', quarantined: 'quarantined',+ empty: 'empty', deleted_page_chunks: 'on deleted pages', chunkless_healable: 'chunkless (healable)',+};++async function runEmbeddingState(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ ctx.progress.heartbeat('embedding_state');+ try {+ const state = await readEmbeddingState(engine, { mode: ctx.tier === 'ops' ? 'ops' : 'full' });+ const details: Record<string, unknown> = { ...state, exact: state.basis === 'exact' };+ if (state.status === 'unknown') {+ checks.push({ name: 'embedding_state', status: 'warn',+ message: `Embedding state is unknown on the ops tier: the active embedding column '${state.active_column}' has no covering partial index (WHERE ${state.active_column} IS NULL), and the ops tier never scans. The standard tier counts it exactly.`,+ details: { ...details, code: 'embedding_state_unknown', health: 'unknown', exact: false },+ fix: agentFix(['gbrain', 'doctor', '--only', 'embedding_state', '--json'], 'The standard tier counts every embedding state exactly; it reads the database and changes nothing.', 'embedding_state', { docs: EMBEDDING_STATE_DOCS }) });+ return checks;+ }+ const counts = state.counts;+ const deleted = state.deleted_page_chunks as { within_window: number; past_window: number; window_hours: number };+ const enabled = state.embeddings_enabled === true;+ const healable = enabled ? counts.chunkless_healable ?? 0 : 0;+ const listed = (Object.keys(LABELS) as EmbeddingState[]).filter(s => counts[s] !== undefined).map(s => `${counts[s]} ${LABELS[s]}`).join(', ');+ const summary = `Embedding state (${state.basis}, column '${state.active_column}'): ${listed}; ${state.unsearchable}${state.unsearchable_complete ? '' : '+'} unsearchable.`;+ const notes: string[] = [];+ if ((counts.pending ?? 0) > 0) notes.push(enabled ? 'The pending backlog is the embeddings check\'s to age and warn on.' : 'Embeddings are disabled by choice: keyword search reads the pending chunks.');+ if ((counts.quarantined ?? 0) > 0) notes.push('Quarantined pages are reviewed under quarantined_pages.');+ if ((counts.keyword_only ?? 0) > 0) notes.push('Keyword-only chunks sit on embed_skip pages by design (split the page or approve a higher content_sanity.bytes_block; `gbrain pages unsearchable --state keyword_only` lists them).');+ if (deleted.within_window > 0) notes.push(`${deleted.within_window} chunk(s) on pages soft-deleted within ${deleted.window_hours}h wait for the purge lifecycle.`);+ if (deleted.past_window > 0 || healable > 0) {+ const warnings: string[] = [];+ if (deleted.past_window > 0) warnings.push(`${deleted.past_window} chunk(s) belong to pages soft-deleted more than ${deleted.window_hours}h ago; \`gbrain pages purge-deleted\` removes them (preview with --dry-run --json; it is brain-wide and irreversible, so ask the user first).`);+ if (healable > 0) warnings.push(`${healable} live page(s) have body text but no chunk rows, so search cannot read their body; \`gbrain embed --stale\` chunks and embeds them (paid).`);+ const fix = embeddingStateFix(deleted.past_window > 0 ? 'deleted_page_chunks' : 'chunkless_healable', { embeddingsEnabled: enabled, verify: doctorVerify('embedding_state') });+ checks.push({ name: 'embedding_state', status: 'warn', message: [summary, ...warnings, ...notes].join(' '),+ details: { ...details, code: deleted.past_window > 0 ? 'deleted_page_chunks_overdue' : 'chunkless_pages_healable' }, ...(fix ? { fix } : {}) });+ return checks;+ }+ const message = [summary, ...notes].join(' ');+ if (!enabled) {+ checks.push(infoCheck('embedding_state', message, 'disabled_by_choice', keylessEnablementFix(), details));+ } else if ((counts.keyword_only ?? 0) > 0 || deleted.within_window > 0) {+ checks.push(infoCheck('embedding_state', message, (counts.keyword_only ?? 0) > 0 ? 'disabled_by_choice' : 'not_applicable', undefined, details));+ } else {+ checks.push({ name: 'embedding_state', status: 'ok', message, details });+ }+ } catch (err) {+ checks.push(checkError('embedding_state', 'read embedding state', err, { details: { health: 'unknown', exact: false } }));+ }+ return checks;+}++export const embeddingStateEntry: DoctorEntry = { name: 'embedding_state', emits: ['embedding_state'], run: runEmbeddingState, tier: 'ops', opsPglite: 'not_applicable' };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 118498301f..48f92578c5 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -47,6 +47,7 @@ import {rlsEventTriggerEntry,embeddingsEntry,} from './checks/schema-health.ts';+import { embeddingStateEntry } from './checks/embedding-state.ts';import {embeddingProviderEntry,alternativeProvidersEntry,@@ -143,6 +144,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [schemaVersionEntry,rlsEventTriggerEntry,embeddingsEntry,+ embeddingStateEntry,embeddingProviderEntry,alternativeProvidersEntry,embeddingQueryPrefixEntry,diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex cf278f28c8..29324de785 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -110,6 +110,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['embedding_provider',// #5691: query-instruction advisory for instruction-style embedding models.'embedding_query_prefix',+ 'embedding_state','embedding_width_consistency','embeddings','entity_link_coverage',diff --git a/src/core/embedding-state.ts b/src/core/embedding-state.tsindex 8caa41940a..3de0693242 100644--- a/src/core/embedding-state.ts+++ b/src/core/embedding-state.ts@@ -173,12 +173,13 @@ export function embeddingStateVerify(sourceId: string, state: EmbeddingState): {/*** The exit for one state, built only from existing commands (agent operator* protocol: argv, consent, actor, why, requires_exclusive, read-only verify,- * docs). Null for `embedded`, which needs none.+ * docs). Null for `embedded`, which needs none. Without `sourceId` the+ * commands run brain-wide; pass `verify` then (doctor verifies with itself).*/-export function embeddingStateFix(state: EmbeddingState, ctx: { sourceId: string; slug?: string; markerBytes?: number | null; embeddingsEnabled: boolean; verify?: { argv: string[] } }): Action | null {- const verify = ctx.verify ?? embeddingStateVerify(ctx.sourceId, state);+export function embeddingStateFix(state: EmbeddingState, ctx: { sourceId?: string; slug?: string; markerBytes?: number | null; embeddingsEnabled: boolean; verify?: { argv: string[] } }): Action | null {+ const verify = ctx.verify ?? embeddingStateVerify(ctx.sourceId ?? 'default', state);const base = { verify, docs: EMBEDDING_STATE_DOCS, requires_exclusive: false };- const source = ['--source', ctx.sourceId];+ const source = ctx.sourceId ? ['--source', ctx.sourceId] : [];switch (state) {case 'embedded':return null;@@ -204,12 +205,12 @@ export function embeddingStateFix(state: EmbeddingState, ctx: { sourceId: stringthen: reimport };}case 'quarantined':- return { ...base, ask_user: true, argv: ctx.slug ? ['gbrain', 'quarantine', 'clear', ctx.slug, '--source-id', ctx.sourceId, '--force'] : ['gbrain', 'quarantine', 'list', '--json'],+ return { ...base, ask_user: true, argv: ctx.slug ? ['gbrain', 'quarantine', 'clear', ctx.slug, ...(ctx.sourceId ? ['--source-id', ctx.sourceId] : []), '--force'] : ['gbrain', 'quarantine', 'list', '--json'],preview_argv: ['gbrain', 'quarantine', 'list', '--json'], consent: ctx.slug ? ['paid'] : [], actor: 'user',why: 'The content-quality gate hid this page as junk, so it has no searchable chunks. Clearing is the owner\'s judgement for a false positive; it re-imports and embeds the page.',user_message: 'A page was hidden from search as junk. Review it and clear it if it is a false positive?' };case 'empty':- return { ...base, ask_user: true, argv: ctx.slug ? ['gbrain', 'delete', ctx.slug, '--source', ctx.sourceId, '--force'] : ['gbrain', 'list', '--json'],+ return { ...base, ask_user: true, argv: ctx.slug ? ['gbrain', 'delete', ctx.slug, ...source, '--force'] : ['gbrain', 'list', '--json'],consent: ['destructive'], actor: 'user',why: 'The page has no body text, so there is nothing to index. Writing content to it chunks it on the next write; delete it only if it is a stub nobody needs (soft delete, restorable).',user_message: 'A page is empty, so there is nothing to search. Add content to it, or delete the empty stub?' };diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex d7ef18dbd1..f023b16398 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -117,6 +117,7 @@ export const CODES = {connector_fence_below_timeline: { class: 'caller', summary: "A stored page carries a fence the connector render cannot preserve." },connector_holds_exhausted: { class: 'caller', summary: "The source holds the maximum number of failed items; its cursor did not advance." },connector_intent_outdated: { class: 'caller', summary: "The connector request no longer matches the stored connector intent." },+ chunkless_pages_healable: { class: 'consent', summary: "Live pages have body text but no chunk rows, so search cannot read their body.", why: 'A page written without the chunking step (an enrichment stub, an interrupted write) has nothing for search to match; `gbrain embed --stale` chunks it first, which makes paid embedding calls.', docs: 'docs/guides/troubleshooting.md#embedding-state', suggestion: 'List them with `gbrain pages unsearchable --state chunkless_healable --json`, then run `gbrain embed --stale --catch-up --yes` once embedding spend is approved.', fix: { argv: ['gbrain', 'pages', 'unsearchable', '--state', 'chunkless_healable', '--json'], consent: [], actor: 'agent', why: 'Lists the chunkless pages and each one\'s fix; changes nothing.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'embedding_state', '--json'] } } },consent_required: { class: 'consent', summary: "A paid step is waiting for the user's opt-in, so it was skipped and nothing was spent.", why: "A dream-cycle phase that a database-config schema pack newly declares (extract_atoms, synthesize_concepts) did not run before this release; resolving the pack correctly must not start paid model calls on its own (#6393).", suggestion: 'Ask the user; with their agreement run gbrain config set cycle.<phase>.enabled true (the phase skip names the exact command).', fix: { argv: ['gbrain', 'schema', 'active', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows which pack is active and the tier it comes from.', requires_exclusive: false } },consent_timeout: { class: 'consent', summary: "Google connect credential error: consent timeout.", docs: 'docs/guides/google-connect.md#troubleshooting' },consumers_without_heartbeat: { class: 'host_only', summary: "Running write claims on this host are stamped by a process that writes no `persistence_consumers` heartbeat row, so its liveness and mode cannot be read.", why: "Every full consumer on this release renews a heartbeat row every 10 s; a claim owner with no row is a gbrain process from before the heartbeat table (an older `serve`, jobs worker or sync CLI), which also never defers to the resident consumer, so the host may run two full consumers until it is upgraded.", docs: 'docs/guides/troubleshooting.md#consumers-without-heartbeat', suggestion: 'Upgrade and restart the process whose pid the check names (its kind and gbrain version come from the claim stamp); until then the host runs its consumer beside the resident one.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the consumers alive on this host with their heartbeat rows beside the running claims and the owner each claim stamps.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'consumers_without_heartbeat', '--json'] } } },@@ -151,6 +152,7 @@ export const CODES = {suggestion: "Repeat the delta call with the cursor from fix (next_cursor.cursor) instead of since/since_slug, and keep passing next_cursor.cursor afterwards.",docs: 'docs/guides/ambient-recall.md#replay-after-a-degraded-wake',},+ deleted_page_chunks_overdue: { class: 'consent', summary: "Chunks of pages soft-deleted longer than the purge window (72h) are still stored.", why: 'Search never reads them; the purge lifecycle (`gbrain pages purge-deleted`, the autopilot purge phase) hard-deletes such pages and their chunks. The purge is brain-wide and irreversible, so it needs the user.', docs: 'docs/guides/troubleshooting.md#embedding-state', suggestion: 'Preview with `gbrain pages purge-deleted --dry-run --json`, then run `gbrain pages purge-deleted --yes` once the user agrees.', fix: { argv: ['gbrain', 'pages', 'purge-deleted', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the soft-deleted pages the purge would remove; changes nothing.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'embedding_state', '--json'] } } },demo_graph_failed: { class: 'server', summary: "The fictional graph did not verify." },demo_import_failed: { class: 'server', summary: "The fictional page did not import successfully." },demo_verification_failed: { class: 'server', summary: "Expected ownership or decision provenance is missing." },@@ -174,6 +176,7 @@ export const CODES = {embedding_failed: { class: 'server', summary: "Computing embeddings for the content failed." },embedding_model_mismatch: { class: 'unavailable', summary: "The configured provider does not match the active embedding column." },embedding_plane_split: { class: 'unavailable', summary: "Embedding plane split." },+ embedding_state_unknown: { class: 'unavailable', summary: "The ops tier could not count embedding state: the active embedding column has no covering partial index, and the ops tier never scans.", why: 'Without an index on `WHERE <active column> IS NULL`, counting vector-less chunks means a full table scan, which the bounded ops tier refuses.', docs: 'docs/guides/troubleshooting.md#embedding-state', suggestion: 'Run the standard tier (`gbrain doctor --only embedding_state --json`) for exact counts.', fix: { argv: ['gbrain', 'doctor', '--only', 'embedding_state', '--json'], consent: [], actor: 'agent', why: 'The standard tier counts every embedding state exactly; it reads and changes nothing.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'embedding_state', '--json'] } } },embedding_storage_unavailable: { class: 'retryable', summary: "Embedding policy or claim storage is temporarily unavailable." },embedding_unavailable: { class: 'unavailable', summary: "The provider returned an incomplete embedding batch." },embedding_unconfigured: { class: 'host_only', summary: "The selected brain has no verifiable text embedding model and dimensions." },diff --git a/test/doctor-day-zero.test.ts b/test/doctor-day-zero.test.tsindex 18cbffc25b..a146441acc 100644--- a/test/doctor-day-zero.test.ts+++ b/test/doctor-day-zero.test.ts@@ -45,7 +45,9 @@ describe('day-zero keyless doctor', () => {expect(report.health_score).toBeGreaterThanOrEqual(90);expect(report.capped_by).toEqual(['embeddings_disabled']);const info = new Set(report.checks.filter(c => c.severity === 'info').map(c => c.name));- for (const name of ['embeddings', 'embedding_provider', 'takes_count', 'retrieval_reflex_health', 'skill_preconditions', 'cycle_freshness', 'backup_coverage']) {+ // #6696 B3: embedding_state runs on day zero and stays info on a keyless brain.+ expect(report.checks.find(c => c.name === 'embedding_state')).toMatchObject({ status: 'ok', severity: 'info' });+ for (const name of ['embeddings', 'embedding_provider', 'embedding_state', 'takes_count', 'retrieval_reflex_health', 'skill_preconditions', 'cycle_freshness', 'backup_coverage']) {if (report.checks.some(c => c.name === name)) expect(info.has(name), name).toBe(true);}}, 120_000);diff --git a/test/doctor-embedding-state.test.ts b/test/doctor-embedding-state.test.tsnew file mode 100644index 0000000000..af3707c420--- /dev/null+++ b/test/doctor-embedding-state.test.ts@@ -0,0 +1,128 @@+/**+ * Doctor `embedding_state` (#6696 B3): statuses per condition, tier mapping+ * (ops -> index-backed counts, unknown without a covering index; any other or+ * undefined tier -> exact), and no double warning on what `embeddings` and+ * `quarantined_pages` already own.+ *+ * Protects: the BRAIN check an operator and lane B's ops tier read. Regression:+ * warning on the pending backlog (double warn), warning on embed_skip by design,+ * or scanning on the ops tier. PGLite in-memory ($0).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { embeddingStateEntry } from '../src/commands/doctor/checks/embedding-state.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.unsetConfig('search_embedding_column');+ await engine.unsetConfig('embedding_columns');+ await engine.unsetConfig('embedding_disabled');+});++interface Out { name: string; status: string; message: string; severity?: string; readiness_state?: string; details: Record<string, unknown>; fix?: { argv?: string[]; preview_argv?: string[]; verify?: { argv?: string[] } } }++async function run(tier?: 'ops' | 'standard' | 'deep'): Promise<Out> {+ const ctx = { engine, progress: { heartbeat() {} }, ...(tier ? { tier } : {}) } as unknown as DoctorContext;+ const checks = await embeddingStateEntry.run(ctx) as Out[];+ expect(checks).toHaveLength(1);+ return checks[0]!;+}++async function page(slug: string, opts: { body?: string; frontmatter?: Record<string, unknown>; deletedHoursAgo?: number } = {}): Promise<number> {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: opts.body ?? `${slug} body` });+ const [row] = await engine.executeRaw<{ id: number }>(+ `UPDATE pages SET frontmatter = $2::jsonb, deleted_at = CASE WHEN $3::int IS NULL THEN NULL ELSE now() - make_interval(hours => $3::int) END+ WHERE slug = $1 AND source_id = 'default' RETURNING id`, [slug, JSON.stringify(opts.frontmatter ?? {}), opts.deletedHoursAgo ?? null]);+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [row!.id]);+ return row!.id;+}++async function chunk(pageId: number, vector: boolean): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, embedding, embedding_pending_since)+ VALUES ($1, (SELECT count(*) FROM content_chunks WHERE page_id = $1), 'text', ${vector ? 'array_fill(0.1::real, ARRAY[1536])::vector' : 'NULL'}, ${vector ? 'NULL' : 'now()'})`, [pageId]);+}++describe('doctor embedding_state', () => {+ test('entry contract: BRAIN category, ops tier, not applicable on PGLite ops', () => {+ expect(categorizeCheck('embedding_state')).toBe('brain');+ expect(embeddingStateEntry).toMatchObject({ name: 'embedding_state', emits: ['embedding_state'], tier: 'ops', opsPglite: 'not_applicable' });+ });++ test('ok when every chunk is embedded; an undefined tier counts exactly', async () => {+ await chunk(await page('notes/alice-example'), true);+ const c = await run();+ expect(c).toMatchObject({ name: 'embedding_state', status: 'ok' });+ expect(c.severity).toBeUndefined();+ expect(c.details).toMatchObject({ basis: 'exact', exact: true, mode: 'full', unsearchable: 0 });+ });++ test('a pending backlog and quarantined pages stay ok here (embeddings and quarantined_pages own those warnings)', async () => {+ await chunk(await page('notes/acme-example'), false);+ await page('notes/junk-hidden', { frontmatter: { quarantine: { reason: 'junk_pattern', detail: 'captcha', assessed_at: '2026-01-01T00:00:00Z' } } });+ const c = await run('standard');+ expect(c.status).toBe('ok');+ expect(c.details).toMatchObject({ unsearchable: 2 });+ expect(c.message).toContain("embeddings check's to age and warn on");+ expect(c.message).toContain('quarantined_pages');+ });++ test('keyword_only (embed_skip by design) and deleted chunks inside the purge window are info', async () => {+ await chunk(await page('notes/fund-a-oversized', { frontmatter: { embed_skip: { reason: 'oversized', bytes: 600_000, assessed_at: '2026-01-01T00:00:00Z' } } }), false);+ await chunk(await page('notes/deleted-recent', { deletedHoursAgo: 1 }), true);+ const c = await run('standard');+ expect(c).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice' });+ expect(c.message).toContain('pages unsearchable --state keyword_only');+ });++ test('deleted chunks past the purge window warn and point at pages purge-deleted', async () => {+ await chunk(await page('notes/deleted-old', { deletedHoursAgo: 100 }), true);+ const c = await run('deep');+ expect(c.status).toBe('warn');+ expect(c.details.code).toBe('deleted_page_chunks_overdue');+ expect(c.fix?.argv).toEqual(['gbrain', 'pages', 'purge-deleted', '--yes']);+ expect(c.fix?.preview_argv).toEqual(['gbrain', 'pages', 'purge-deleted', '--dry-run', '--json']);+ expect(c.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'embedding_state', '--json']);+ });++ test('a chunkless page with body text warns on a keyed brain and is info on a keyless one', async () => {+ await page('notes/stub-with-body');+ const keyed = await run('standard');+ expect(keyed.status).toBe('warn');+ expect(keyed.details.code).toBe('chunkless_pages_healable');+ expect(keyed.fix?.argv).toEqual(['gbrain', 'embed', '--stale', '--catch-up', '--yes']);+ await engine.setConfig('embedding_disabled', 'true');+ const keyless = await run('standard');+ expect(keyless).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice' });+ });++ test('ops tier: index-backed estimate on the legacy column; unknown (warn, health unknown) without a covering index', async () => {+ await chunk(await page('notes/alice-example'), false);+ const ops = await run('ops');+ expect(ops.status).toBe('ok');+ expect(ops.details).toMatchObject({ basis: 'estimated', exact: false, mode: 'ops', covering_index: 'content_chunks_stale_idx' });+ await engine.executeRaw('ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_reg8 vector(8)');+ await engine.setConfig('embedding_columns', JSON.stringify({ embedding_reg8: { provider: 'openai:text-embedding-3-small', dimensions: 8, type: 'vector' } }));+ await engine.setConfig('search_embedding_column', 'embedding_reg8');+ const unknown = await run('ops');+ expect(unknown.status).toBe('warn');+ expect(unknown.details).toMatchObject({ health: 'unknown', exact: false, reason: 'no_covering_index', code: 'embedding_state_unknown', status: 'unknown' });+ expect(unknown.fix?.argv).toEqual(['gbrain', 'doctor', '--only', 'embedding_state', '--json']);+ expect((await run('standard')).details).toMatchObject({ basis: 'exact', active_column: 'embedding_reg8' });+ });+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 39a0aea1cd..369a12cb20 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -556,6 +556,56 @@"name": "embeddings","status": "ok"},+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 0,+ "keyword_only": 0,+ "pending": 0,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 0,+ "embedded": 0,+ "ratio": null+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": true,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 0,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 0 pending, 0 keyword-only, 0 quarantined, 0 empty, 0 on deleted pages, 0 chunkless (healable); 0 unsearchable.",+ "name": "embedding_state",+ "status": "ok"+ },{"category": "brain","message": "Skipped (no provider credentials). Model: openai:text-embedding-3-large.",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 495967df89..312cb36e54 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -597,6 +597,100 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 0,+ "keyword_only": 0,+ "pending": 0,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 0,+ "embedded": 0,+ "ratio": null+ },+ "covering_index": null,+ "deleted_page_chunks": {+ "past_window": 0,+ "window_hours": 72,+ "within_window": 0+ },+ "embeddings_enabled": false,+ "exact": true,+ "keyword_only": {+ "marker_bytes": 0,+ "pages": 0,+ "reason": "embed_skip",+ "threshold_bytes": 500000+ },+ "mode": "full",+ "omitted_states": [],+ "reason": "embeddings_disabled",+ "status": "known",+ "units": "content_chunks rows, plus one unit per page with no chunk rows",+ "unsearchable": 0,+ "unsearchable_complete": true,+ "unstamped_pending": {+ "count": 0,+ "created_at_lower_bound": null,+ "writer_version": "<version>"+ }+ },+ "fix": {+ "actor": "user",+ "argv": [+ "gbrain",+ "init",+ "--force",+ "--embedding-model",+ "voyage:voyage-4",+ "--embedding-dimensions",+ "1024",+ "--path",+ "<home>/.gbrain/brain.pglite"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024 --path <home>/.gbrain/brain.pglite",+ "consent": [+ "credentials",+ "paid"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/search-modes.md",+ "inputs": [+ {+ "how": "Ask the user for an API key for Voyage AI; store it with `gbrain config set voyage_api_key <key>` (every gbrain process reads it), or export VOYAGE_API_KEY in the environment of every gbrain process. Then run the command.",+ "name": "VOYAGE_API_KEY"+ }+ ],+ "next": "tell_user_to_run",+ "requires_exclusive": true,+ "user_message": "Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (VOYAGE_API_KEY), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "embeddings",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain. Once the key is set this turns on voyage:voyage-4 (1024d) for the PGLite brain at <home>/.gbrain/brain.pglite. Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills."+ },+ "message": "Embedding state (exact, column 'embedding'): 0 embedded, 0 pending, 0 keyword-only, 0 quarantined, 0 empty, 0 on deleted pages, 0 chunkless (healable); 0 unsearchable.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","fix": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex c938d62a59..c863259200 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -309,6 +309,10 @@"category": "brain","name": "embeddings"},+ {+ "category": "brain",+ "name": "embedding_state"+ },{"category": "brain","name": "embedding_provider"