mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* feat(core): Levenshtein helper + preflight schema-dim resolvers Foundation for v0.37.10.0 env-detection wave. Two pure modules: - src/core/levenshtein.ts: editDistance(a,b) + suggestNearest(input, candidates, maxDistance). Used by config-set "did you mean" suggestions and env-var typo detection at init. - src/core/embedding-dim-check.ts: resolveSchemaEmbeddingDim() + resolveSchemaMultimodalDim() pure functions. Validate resolved dim against recipe default_dims + per-provider Matryoshka allow-lists (OpenAI text-3, Voyage flexible-dim, ZeroEntropy zembed-1) BEFORE any DB write. Plus EmbeddingDisabledError + assertEmbeddingEnabled() runtime guard for the deferred-setup path (D9). New PGVECTOR_COLUMN_MAX_DIMS=16000 exported. Tests: 41 unit cases across both modules. * feat(providers): extract formatRecipeTable + add init provider picker Two changes prepping the env-detection wave: - providers.ts: extract formatRecipeTable() helper from runList(). Picker reuses it so UI can't drift from \`gbrain providers list\`. Also adds the codex finding #10 warn-line to \`providers test\` when the tested model differs from the configured default ("Note: tested X in isolation; gbrain's configured embedding is Y — this test does NOT verify your brain's active path."). envReady() takes an explicit env arg for testing. - init-provider-picker.ts (NEW): interactive picker mirroring init-mode-picker.ts. Filters candidate recipes to env-ready ones (codex finding #3), prompts via readLineSafe, exports printSubagentAnthropicCaveat() for shared use from initPGLite/initPostgres. Tests: 17 unit cases (10 providers + 7 picker). * feat(config): embedding_disabled sentinel + strict unknown-key rejection Two changes for the v0.37.10.0 wave: - src/core/config.ts: add embedding_disabled?:boolean to GBrainConfig (D9 deferred-setup sentinel, mutually exclusive with embedding_model). Export KNOWN_CONFIG_KEYS (60+ canonical keys, file-plane + DB-plane) and KNOWN_CONFIG_KEY_PREFIXES (search., models., dream., cycle., etc.) for validation use. - src/commands/config.ts: D6 strict-default unknown-key rejection. Unknown key + no --force → exit 1 with Levenshtein suggestion against KNOWN_CONFIG_KEYS. Prefix matches accepted without --force. --force escape hatch accepts arbitrary keys with stderr WARN. Closes the silent-no-op class the bug reporter hit (embedding.provider, embedding.model, embedding.dimensions all exit 1 with right suggestion). Tests: 19 unit cases pinning the bug-reporter regression + gate logic. * feat(init): env-detection auto-pick + preflight + atomic persist + --no-embedding Core of the v0.37.10.0 wave (D1-D7, D9-D11). Closes the bug where a fresh \`gbrain init --pglite\` silently produced a broken brain when no provider key matched the v0.36 default. resolveAIOptions rewritten with per-touchpoint env detection: - Explicit flag → shorthand → env auto-pick (group by provider id, codex #2) - Picker fires when multiple providers env-ready (D1+D2 hybrid) - Non-TTY zero-key exits 1 with paste-ready setup hint (D3) + Levenshtein typo detection for OPENAPI_API_KEY → OPENAI_API_KEY (D13) - All three touchpoints covered (embedding + expansion + chat, D4) - Local-only providers (Ollama/llama-server) excluded from auto-pick; picking Ollama silently when user has OPENAI_API_KEY set was wrong UX initPGLite + initPostgres: - Drop conditional configureGateway gate → always call before initSchema - Preflight resolveSchemaEmbeddingDim() BEFORE engine.initSchema() (D11) — invalid dim refuses with paste-ready hint, no disk write - Atomic embedding-config persistence (codex #13): either resolved tuple or embedding_disabled:true sentinel, never partial state - Post-initSchema invariant assertion stays as regression guardrail - --no-embedding opt-in flag (D9) for deferred-setup mode - Subagent-Anthropic caveat (D7) fires post-init when chat_model is non-Anthropic AND ANTHROPIC_API_KEY missing Exported groupReadyByProvider() + findEnvKeyTypos() for unit testing. Tests: 21 unit cases covering provider grouping + typo detection edge cases. * feat(embed,import): refuse cleanly when --no-embedding deferred-setup is active T7 of the v0.37.10.0 wave. Both runEmbedCore and runImport now call assertEmbeddingEnabled(loadConfig()) at entry. When the brain was init'd with --no-embedding (config has embedding_disabled:true), they exit 1 with a paste-ready hint: gbrain config set embedding_model <provider>:<model> gbrain config set embedding_dimensions <N> gbrain init --force --embedding-model <provider>:<model> \`gbrain import --no-embed\` flag still works (chunks land without vectors), so users can still ingest in deferred-setup mode and backfill embeddings later with \`gbrain embed --stale\`. * feat(doctor): empty-config drift detection + subagent-Anthropic caveat extension Two doctor check extensions for v0.37.10.0: T9 — embedding_provider check extended for the v0.36 silent-default repair case. When config is empty AND schema column dim differs from the gateway-resolved default, surface the mismatch with empty-brain vs non-empty-brain repair branching (codex finding #7 nuance): - Empty brain (0 embedded chunks) → \`gbrain init --force --pglite --embedding-model <id> --embedding-dimensions <N>\` (drop and re-init) - Non-empty brain → \`gbrain retrieval-upgrade --to <id> --reindex\` Gated on totalChunks > 0 so pristine empty brains aren't pre-warned. Never recommend rm -rf ~/.gbrain. T10 — subagent_provider check (v0.31.12) extended per D7. When chat_model is non-Anthropic AND ANTHROPIC_API_KEY is missing, warn that subagent features (gbrain dream, gbrain agent run, gbrain autopilot) will fail at job submission. Chat alone (gbrain think) still works. * feat(reindex,test): multimodal preflight + E2E suite for fresh PGLite init T11 — reindex-multimodal.ts: hook resolveSchemaMultimodalDim() preflight BEFORE the reindex sweep. Mirrors the text-side contract from initPGLite — if the configured multimodal model can't produce a dim matching the schema column, fail loud here with a \`gbrain config set\` hint rather than mid-reindex with a vector(N) INSERT error. T12 — test/e2e/init-fresh-pglite.test.ts (NEW, 14 cases): subprocess-driven E2E verification of the bug-reporter's repro scenarios: - Happy path: OPENAI_API_KEY set → auto-pick OpenAI, persists config - D3 non-TTY fail-loud (with and without env-key typos) - D6 regression: bug-reporter's three no-op config keys all exit 1 with Levenshtein suggestions - D9 deferred-setup mode + gbrain import refusal (and --no-embed bypass) - D11 preflight refuses BEFORE any disk write - Explicit --embedding-model wins over env detection Each test uses its own throw-away GBRAIN_HOME for hermetic runs. * docs: env-detection + headless-install + close v0.32 picker TODO T13/T14 docs sync for v0.37.10.0: - docs/integrations/embedding-providers.md: TL;DR table refreshed to reflect ZE as v0.36 default; added "Init resolves your provider from env keys" section explaining the auto-pick → picker → fail-loud chain; added "If first import fails" troubleshooting block pointing at gbrain doctor instead of \`rm -rf ~/.gbrain\`. - docs/operations/headless-install.md (NEW): Docker/CI sequencing guide. Two acceptable patterns — provider key at build time (Pattern 1) or --no-embedding opt-in + runtime config (Pattern 2). Codex finding #11. - README.md: Troubleshooting section with one-paragraph repair hint and links to embedding-providers.md + headless-install.md. - TODOS.md: closed v0.32.x "interactive provider chooser" entry as SUPERSEDED by this wave. Added four follow-up entries (dedicated v0.36 broken-install migration, namespaced ext fields, runtime config-key audit, value-level Levenshtein on config set). * chore: bump version and changelog (v0.37.10.0) Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(doctor): empty brain scores 100/100 + hermetic doctor-report-remote test Two fixes coupled because the test couldn't pass without the formula fix: src/core/pglite-engine.ts + src/core/postgres-engine.ts — empty brain (pageCount === 0) now gets FULL marks (100/100), not 0/100. Semantically an empty brain has no coverage problem to penalize — there's nothing to embed, nothing to link, nothing to orphan. Vacuous truth applies. The pre-fix "empty = 0" caused fresh-init brains to score as critically unhealthy on \`gbrain doctor\`, which was a structural surprise to users who'd just run init successfully. Same fix on both engines. test/brain-score-breakdown.test.ts — updated the "empty brain" assertion to match the new contract (was: 0/0/0/0/0/0; is: 100/35/25/15/15/10). test/doctor-report-remote.test.ts → renamed to .serial.test.ts and made hermetic. The pre-fix test pulled audit data from the host ~/.gbrain (reranker_health, sync_failures, etc.), which made the assertion non-deterministic depending on whoever ran the suite. Now isolates GBRAIN_HOME to a tempdir via beforeAll/afterAll; env mutation requires serial-quarantine per scripts/check-test-isolation.sh R1. Closes the master-state flake that was failing on every \`bun run test\` run regardless of my branch contents. * docs: update CLAUDE.md and TODOS.md for v0.37.10.0 empty-brain fix - CLAUDE.md: annotate src/core/pglite-engine.ts + src/core/postgres-engine.ts entries with v0.37.10.0 empty-brain 100/100 contract. Vacuous truth: an empty brain has no coverage to penalize, so getBrainScore returns full marks (35/25/15/15/10 breakdown) when pageCount === 0. Pre-fix 0/100 was structurally surprising on fresh init and caused the v0.37.8.0 doctor-report-remote.test.ts flake. - TODOS.md: mark P0 doctor-report-remote.test.ts:65 TODO completed (resolved by commit 9aa571f3's empty-brain-100/100 fix; test renamed to .serial.test.ts and made hermetic per scripts/check-test-isolation.sh R1). - llms-full.txt: regenerated from updated CLAUDE.md per CLAUDE.md "Auto-derived files" rule. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(init): D5 persisted-config-wins on re-init + CI mechanical E2E Two coupled fixes for the v0.37.10.0 wave's interaction with CI's Tier-1 mechanical E2E suite (which runs without any embedding-provider env var). src/commands/init.ts — Honor D5 properly at resolveAIOptions entry. Pre-fix the env-detection branch fired on EVERY init regardless of persisted config. A non-TTY re-init with no env keys exited 1 (D3 fail-loud) even when ~/.gbrain/config.json already had embedding_model set from a prior successful init. Now resolveAIOptions reads loadConfig() first and seeds out.embedding_model / embedding_dimensions / expansion_model / chat_model from the file plane BEFORE running env detection. Also honors embedding_disabled (D9 sentinel) on re-init so deferred-setup brains don't re-trigger fail-loud. test/e2e/mechanical.test.ts:722 — Setup Journey's first init runs against a fresh DB with no persisted config. Pass --embedding-model explicitly (openai:text-embedding-3-large) so the preflight resolves offline. After this init writes config, subsequent inits in the file (RLS self-heal v24, RLS event-trigger probes, etc.) honor the persisted config via the D5 fix above. Verified locally: full test/e2e/mechanical.test.ts → 78 pass / 0 fail. --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
146 lines
6.4 KiB
TypeScript
146 lines
6.4 KiB
TypeScript
/**
|
|
* Bug 11 — brain_score needs a breakdown + orphan_pages metric is wrong.
|
|
*
|
|
* Assertions:
|
|
* 1. getHealth() returns the new *_score breakdown fields.
|
|
* 2. Breakdown fields sum to brain_score by construction.
|
|
* 3. orphan_pages counts pages with zero INBOUND links, regardless of
|
|
* whether they have outbound links (was: required both).
|
|
* 4. BrainHealth type now carries dead_links.
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
|
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
|
|
|
let engine: PGLiteEngine;
|
|
|
|
beforeAll(async () => {
|
|
engine = new PGLiteEngine();
|
|
await engine.connect({});
|
|
await engine.initSchema();
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await engine.disconnect();
|
|
});
|
|
|
|
beforeEach(async () => {
|
|
for (const t of ['links', 'content_chunks', 'timeline_entries', 'raw_data', 'tags', 'page_versions', 'ingest_log', 'pages']) {
|
|
await (engine as any).db.exec(`DELETE FROM ${t}`);
|
|
}
|
|
});
|
|
|
|
describe('Bug 11 — brain_score breakdown sums to total', () => {
|
|
test('empty brain returns full score (vacuous truth) with all breakdown fields present', async () => {
|
|
// v0.37.10.0: empty brain = no coverage problems = full marks. Pre-fix
|
|
// this returned 0/100, which surprised users running `gbrain doctor`
|
|
// immediately after `gbrain init --pglite`. Each component returns its
|
|
// max weight when pageCount === 0; the sum equals brain_score=100 by
|
|
// construction (same invariant as the non-empty path, see next test).
|
|
const h = await engine.getHealth();
|
|
expect(h.brain_score).toBe(100);
|
|
expect(h.embed_coverage_score).toBe(35);
|
|
expect(h.link_density_score).toBe(25);
|
|
expect(h.timeline_coverage_score).toBe(15);
|
|
expect(h.no_orphans_score).toBe(15);
|
|
expect(h.no_dead_links_score).toBe(10);
|
|
// dead_links is now on the type.
|
|
expect(h.dead_links).toBe(0);
|
|
});
|
|
|
|
test('breakdown fields always sum to brain_score', async () => {
|
|
// Seed a small graph — some pages, some links, some embeds.
|
|
for (const slug of ['a', 'b', 'c']) {
|
|
await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `content of ${slug}`, frontmatter: {} });
|
|
}
|
|
const h = await engine.getHealth();
|
|
const sum =
|
|
h.embed_coverage_score +
|
|
h.link_density_score +
|
|
h.timeline_coverage_score +
|
|
h.no_orphans_score +
|
|
h.no_dead_links_score;
|
|
expect(sum).toBe(h.brain_score);
|
|
});
|
|
|
|
test('brain_score caps at 100', async () => {
|
|
const h = await engine.getHealth();
|
|
expect(h.brain_score).toBeGreaterThanOrEqual(0);
|
|
expect(h.brain_score).toBeLessThanOrEqual(100);
|
|
});
|
|
});
|
|
|
|
describe('Bug 11 — orphan_pages is "no inbound links"', () => {
|
|
test('a page with outbound-only links is NOT an orphan', async () => {
|
|
// Hub page: links out to three others, but nothing links back to it.
|
|
// Previous (buggy) behavior: hub counted as orphan because it had no
|
|
// inbound links (correct) AND the old query also required no outbound.
|
|
await engine.putPage('hub', { type: 'note', title: 'Hub', compiled_truth: 'index', frontmatter: {} });
|
|
await engine.putPage('leaf1', { type: 'note', title: 'L1', compiled_truth: 'x', frontmatter: {} });
|
|
await engine.putPage('leaf2', { type: 'note', title: 'L2', compiled_truth: 'y', frontmatter: {} });
|
|
await engine.putPage('leaf3', { type: 'note', title: 'L3', compiled_truth: 'z', frontmatter: {} });
|
|
|
|
const hubId = (await (engine as any).db.query(`SELECT id FROM pages WHERE slug='hub'`)).rows[0].id;
|
|
for (const target of ['leaf1', 'leaf2', 'leaf3']) {
|
|
const tid = (await (engine as any).db.query(`SELECT id FROM pages WHERE slug=$1`, [target])).rows[0].id;
|
|
await (engine as any).db.query(
|
|
`INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'mentions')`,
|
|
[hubId, tid],
|
|
);
|
|
}
|
|
|
|
const h = await engine.getHealth();
|
|
// hub has outbound, no inbound → NOT orphan (under the fixed definition).
|
|
// leaf1/2/3 have inbound from hub → NOT orphan.
|
|
// So orphan_pages should be 0.
|
|
expect(h.orphan_pages).toBe(0);
|
|
});
|
|
|
|
test('a page with no links at all IS an orphan', async () => {
|
|
await engine.putPage('loner', { type: 'note', title: 'Loner', compiled_truth: 'alone', frontmatter: {} });
|
|
const h = await engine.getHealth();
|
|
expect(h.orphan_pages).toBe(1);
|
|
});
|
|
|
|
test('a page with inbound links only is NOT an orphan', async () => {
|
|
await engine.putPage('sink', { type: 'note', title: 'Sink', compiled_truth: 'target', frontmatter: {} });
|
|
await engine.putPage('source', { type: 'note', title: 'Source', compiled_truth: 'origin', frontmatter: {} });
|
|
const sinkId = (await (engine as any).db.query(`SELECT id FROM pages WHERE slug='sink'`)).rows[0].id;
|
|
const srcId = (await (engine as any).db.query(`SELECT id FROM pages WHERE slug='source'`)).rows[0].id;
|
|
await (engine as any).db.query(
|
|
`INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'mentions')`,
|
|
[srcId, sinkId],
|
|
);
|
|
|
|
const h = await engine.getHealth();
|
|
// sink has 1 inbound (from source) → not orphan.
|
|
// source has no inbound (but has outbound) → not orphan under new definition.
|
|
expect(h.orphan_pages).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe('Bug 11 — doctor renders brain_score breakdown', () => {
|
|
test('doctor source contains brain_score breakdown rendering', async () => {
|
|
const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
|
|
expect(source).toContain('brain_score');
|
|
expect(source).toContain('embed_coverage_score');
|
|
expect(source).toContain('link_density_score');
|
|
expect(source).toContain('no_orphans_score');
|
|
expect(source).toContain('no_dead_links_score');
|
|
});
|
|
});
|
|
|
|
describe('Bug 11 — BrainHealth type shape', () => {
|
|
test('type includes dead_links + breakdown scores', async () => {
|
|
const typesSource = await Bun.file(new URL('../src/core/types.ts', import.meta.url)).text();
|
|
expect(typesSource).toContain('dead_links: number');
|
|
expect(typesSource).toContain('embed_coverage_score: number');
|
|
expect(typesSource).toContain('link_density_score: number');
|
|
expect(typesSource).toContain('timeline_coverage_score: number');
|
|
expect(typesSource).toContain('no_orphans_score: number');
|
|
expect(typesSource).toContain('no_dead_links_score: number');
|
|
// The stale "(0-10)" comment must be corrected to 0-100.
|
|
expect(typesSource).toContain('0-100');
|
|
});
|
|
});
|