Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test: embedding state Postgres E2E arm; Postgres doctor goldens gain embedding_state (#6696 B3)
garrytan2e6e0ee9583c
diff --git a/test/e2e/embedding-state-postgres.test.ts b/test/e2e/embedding-state-postgres.test.tsnew file mode 100644index 0000000000..04f6a783a7--- /dev/null+++ b/test/e2e/embedding-state-postgres.test.ts@@ -0,0 +1,83 @@+/**+ * #6696 B3 embedding state on real Postgres: the classifier and listing run+ * through PostgresEngine's scoped-read transaction, the ops tier's EXPLAIN+ * estimate binds parameters and parses postgres.js's json plan, and a custom+ * active column without a covering partial index is `unknown` on the ops tier+ * (never a scan) until one exists. The PGLite unit suite covers the same SQL;+ * this arm covers the Postgres driver path.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { readEmbeddingState } from '../../src/core/embedding-state.ts';++const d = hasDatabase() ? describe : describe.skip;++beforeAll(async () => {+ if (!hasDatabase()) return;+ await setupDB();+});+afterAll(async () => { if (hasDatabase()) await teardownDB(); });++async function page(slug: string, frontmatter: Record<string, unknown> = {}, deletedHoursAgo: number | null = null, body = `${slug} body`): Promise<number> {+ const engine = getEngine();+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body });+ const [row] = await engine.executeRaw<{ id: number }>(+ `UPDATE pages SET frontmatter = ($2::text)::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(frontmatter), deletedHoursAgo]);+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [row!.id]);+ return row!.id;+}++async function chunk(pageId: number, index: number, vector: boolean): Promise<void> {+ const [{ dims }] = await getEngine().executeRaw<{ dims: number }>(+ `SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'`);+ await getEngine().executeRaw(+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, embedding, embedding_pending_since)+ VALUES ($1, $2, 'text', ${vector ? `array_fill(0.1::real, ARRAY[${Number(dims)}])::vector` : 'NULL'}, ${vector ? 'NULL' : 'now()'})`, [pageId, index]);+}++d('embedding state (Postgres)', () => {+ test('full and ops counts, listing and the custom-column unknown arm', async () => {+ const engine = getEngine();+ const embedded = await page('notes/alice-example');+ await chunk(embedded, 0, true);+ const pending = await page('notes/acme-example');+ await chunk(pending, 0, false);+ await chunk(pending, 1, false);+ await chunk(await page('notes/fund-a-oversized', { embed_skip: { reason: 'oversized', bytes: 600_000, assessed_at: '2026-01-01T00:00:00Z' } }), 0, false);+ await page('notes/junk-hidden', { quarantine: { reason: 'junk_pattern', detail: 'captcha', assessed_at: '2026-01-01T00:00:00Z' } });+ await page('notes/empty-stub', {}, null, '');+ await page('notes/stub-with-body');+ await chunk(await page('notes/deleted-old', {}, 100), 0, true);++ const full = await readEmbeddingState(engine, { mode: 'full', sourceIds: ['default'] });+ expect(full.counts).toEqual({ embedded: 1, pending: 2, keyword_only: 1, quarantined: 1, empty: 1, deleted_page_chunks: 1, chunkless_healable: 1 });+ expect(full.deleted_page_chunks).toMatchObject({ past_window: 1, within_window: 0 });++ const ops = await readEmbeddingState(engine, { mode: 'ops', sourceIds: ['default'] });+ expect(ops).toMatchObject({ status: 'known', basis: 'estimated', covering_index: 'content_chunks_stale_idx' });+ expect(ops.counts).toMatchObject({ pending: 2, keyword_only: 1, quarantined: 1, deleted_page_chunks: 1 });+ expect(typeof ops.counts.embedded).toBe('number');++ const rows = await engine.listEmbeddingStateRows({ sourceIds: ['default'], states: ['pending', 'deleted_page_chunks'], limit: 10, purgeWindowHours: 72 });+ expect(rows.map(r => [r.state, r.slug, r.chunks, r.overdue])).toEqual([+ ['deleted_page_chunks', 'notes/deleted-old', 1, true],+ ['pending', 'notes/acme-example', 2, false],+ ]);++ await engine.executeRaw('ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_e2e8 vector(8)');+ await engine.setConfig('embedding_columns', JSON.stringify({ embedding_e2e8: { provider: 'openai:text-embedding-3-small', dimensions: 8, type: 'vector' } }));+ await engine.setConfig('search_embedding_column', 'embedding_e2e8');+ try {+ expect(await readEmbeddingState(engine, { mode: 'ops' })).toMatchObject({ status: 'unknown', reason: 'no_covering_index', active_column: 'embedding_e2e8', unsearchable: null });+ expect((await readEmbeddingState(engine, { mode: 'full' })).counts).toMatchObject({ embedded: 0, pending: 3 });+ await engine.executeRaw('CREATE INDEX content_chunks_e2e8_stale_idx ON content_chunks(page_id, chunk_index) WHERE embedding_e2e8 IS NULL');+ expect(await readEmbeddingState(engine, { mode: 'ops' })).toMatchObject({ status: 'known', covering_index: 'content_chunks_e2e8_stale_idx', counts: { pending: 3 } });+ } finally {+ await engine.unsetConfig('search_embedding_column');+ await engine.unsetConfig('embedding_columns');+ await engine.executeRaw('DROP INDEX IF EXISTS content_chunks_e2e8_stale_idx');+ await engine.executeRaw('ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_e2e8');+ }+ });+});diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex e5979480ab..db5702764e 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -604,6 +604,98 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 1,+ "keyword_only": 0,+ "pending": 23,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 23,+ "embedded": 0,+ "ratio": 0+ },+ "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": 1,+ "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"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024",+ "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 this Postgres brain. 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, 23 pending, 0 keyword-only, 0 quarantined, 1 empty, 0 on deleted pages, 0 chunkless (healable); 1 unsearchable. Embeddings are disabled by choice: keyword search reads the pending chunks.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","fix": {@@ -3781,6 +3873,98 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "active_column": "embedding",+ "basis": "exact",+ "counts": {+ "chunkless_healable": 0,+ "deleted_page_chunks": 0,+ "embedded": 0,+ "empty": 1,+ "keyword_only": 0,+ "pending": 23,+ "quarantined": 0+ },+ "coverage": {+ "basis": "exact",+ "eligible": 23,+ "embedded": 0,+ "ratio": 0+ },+ "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": 1,+ "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"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024",+ "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 this Postgres brain. 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, 23 pending, 0 keyword-only, 0 quarantined, 1 empty, 0 on deleted pages, 0 chunkless (healable); 1 unsearchable. Embeddings are disabled by choice: keyword search reads the pending chunks.",+ "name": "embedding_state",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","fix": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 366c25fbe2..fb93bd40f3 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -588,6 +588,98 @@"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"+ ],+ "command": "gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024",+ "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 this Postgres brain. 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": {