mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* feat(v0.34 pre-w0): add code-retrieval eval harness for v0.34 ship gate Captures pre-v0.34 retrieval quality on the gbrain self-corpus before any code-intel work lands, so the v0.34 ship gate (precision@5 +10pp OR answered_rate +15pp on >=15/30 questions) measures real improvement rather than an after-the-fact retuned baseline. * src/eval/code-retrieval/harness.ts -- pure-function metrics (precision@k, recall@k, top-1 stability, gate evaluator) + EvalRunReport types stable across schema_version 1 * src/eval/code-retrieval/questions.json -- 30 questions across callers / callees / definition / references / blast_radius / execution_flow / cluster_membership kinds, expected_files captured against current gbrain layout * src/eval/code-retrieval/strategies.ts -- BaselineStrategy (hybridSearch) + WithCodeIntelStrategy stub (post-W3 fills in code_blast/code_flow/etc.) * src/commands/eval-code-retrieval.ts -- gbrain eval code-retrieval CLI with --baseline / --with-code-intel / --compare subcommands * test/code-retrieval-harness.test.ts -- 26 unit tests across metrics, loader, gate logic; no engine dependency PRE-V0.34 BASELINE WORKFLOW: gbrain eval code-retrieval --baseline --save /tmp/baseline-1.json (run 3x for noise floor) V0.34 SHIP GATE (after W3 lands): gbrain eval code-retrieval --with-code-intel --save /tmp/v034.json gbrain eval code-retrieval --compare /tmp/baseline-1.json /tmp/v034.json Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(v0.34 W0a): source-routing leak across query + two-pass Codex outside-voice review on the v0.34 plan caught two load-bearing sites where sourceId was advertised but never applied — multi-source brains silently cross-contaminated structural retrieval: * operations.ts ~323 — `query` op handler called hybridSearch without threading ctx.sourceId. Multi-source agents querying with a --source flag got cross-source results. * two-pass.ts:81 (nearSymbol lookup) and two-pass.ts:131 (unresolved edge resolution) — TwoPassOpts.sourceId was declared and threaded through hybridSearch's expandAnchors call, but the actual SQL ignored it. The walk window crossed source boundaries every time. Fix: * `query` op now reads ctx.sourceId AND accepts a new `source_id` param (with '__all__' as the explicit force-cross-source escape hatch). Per-call param wins over ctx context. * two-pass.ts both lookups join through pages.source_id when opts.sourceId is set; omitted opts.sourceId preserves the legacy cross-source contract for callers who want it. Regression test: test/e2e/source-routing.test.ts seeds two sources with the same `parseMarkdown` symbol + a cross-source caller edge. Pins: - nearSymbol + sourceId='source-a' returns ONLY source-a chunks - nearSymbol + sourceId='source-b' returns ONLY source-b chunks - nearSymbol with no sourceId still crosses sources (contract preserved) - walk_depth=1 unresolved-edge resolution stays in source-a PGLite in-memory, no DATABASE_URL needed. The fix proves out under realistic structural retrieval not just a contrived unit test. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(v0.34 W0b): flip CLI source-scoping default to truly source-scoped Codex outside-voice review (finding #7) caught that the v0.20.0 docstring claim "by default we only match the caller's source_id" contradicted the implementation in code-callers.ts:54 + code-callees.ts:43: allSources: allSources || !sourceId The right side made `allSources` TRUE whenever `--source` was omitted, INVERTING the documented default. Multi-source brains silently cross- contaminated structural retrieval; `gbrain code-callers parseMarkdown` on a brain with two repos returned callers from both even though the docstring promised per-source scoping. Fix: * New canonical helper `resolveDefaultSource(engine)` in sources-ops.ts. Contract per eng review D7: - exactly 1 source registered → return its id (single-source brains, the 80% case; --source flag is unnecessary friction there) - 2+ sources → throw SourceResolutionError(multiple_sources_ambiguous) with the list of valid ids - 0 sources → throw SourceResolutionError(no_sources) * code-callers.ts + code-callees.ts now resolve to the default source when both --source AND --all-sources are absent. To get the pre-v0.34 cross-source behavior, callers must pass --all-sources explicitly. * Same hint text on both commands. Pinned by test/e2e/cli-source-scoping-pglite.test.ts. IRON RULE regression R2: docstring promise now holds. Multi-source brain running `gbrain code-callers <symbol>` without --source gets a clear error listing valid source ids instead of silent cross-resolution. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W0c): within-file two-pass symbol resolver + edges_backfilled_at watermark Codex's outside-voice review caught that the v0.20.0 graph stores BARE callee tokens (`render`, `find`, `execute`) — not qualified names. Pre-v0.34 recursive blast/flow would alias every same-named function across classes. W0c is the foundation that fixes this: resolve `code_edges_symbol` rows by matching `to_symbol_qualified` against the SAME-FILE chunks' `symbol_name_qualified`, then write the outcome to `edge_metadata`. This commit is the resolver primitive + schema. The cycle-phase wiring that calls it on every quick-cycle tick lands in the next commit. Schema (v51 migration `edges_backfilled_at_v0_34`): * `content_chunks.edges_backfilled_at TIMESTAMPTZ` — resume watermark. Chunks where the column is NULL OR older than EDGE_EXTRACTOR_VERSION_TS get re-walked next tick. SIGINT/OOM/sleep mid-backfill loses at most one batch. * Indexes per D11 from eng review: - `idx_code_edges_symbol_resolver(source_id, to_symbol_qualified)` — composite for the resolver's per-source lookup. - `idx_content_chunks_symbol_lookup(page_id, symbol_name_qualified)` WHERE `symbol_name_qualified IS NOT NULL` — file-batched candidate fetch; also reused by W4-5 cluster recompute. - `idx_content_chunks_edges_backfill(edges_backfilled_at)` WHERE `edges_backfilled_at IS NULL` — fast unresumed-row scan. Module (`src/core/chunkers/symbol-resolver.ts`): * `resolveSymbolEdgesIncremental(engine, {sourceId, maxChunks?, onProgress?})` walks stale chunks in 200-chunk batches. For each chunk, loads its unresolved edges, finds same-page candidates by symbol_name_qualified, and writes outcome to `edge_metadata`: - exactly 1 candidate → `{resolved_chunk_id: <id>}` - 2+ candidates → `{ambiguous: true, candidates: [...]}` - 0 candidates → unchanged (cross-file; two-pass.ts handles those) Each batch bumps `edges_backfilled_at = NOW()` for the chunks. * `readEdgeResolution(metadata)` — public helper for downstream code (two-pass.ts, code_blast op, eval-capture) to consume the resolver's output without parsing JSON directly. Returns a tagged union. * `EDGE_EXTRACTOR_VERSION_TS` exported constant — bump when extractor shape changes and the next cycle re-walks all chunks. Tests (5 E2E in test/e2e/symbol-resolver-pglite.test.ts, all PGLite, no DATABASE_URL): unambiguous match, ambiguous multi-match, no match, watermark advance + idempotency, source isolation (no cross-source candidate leak). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W0c): wire resolve_symbol_edges as a new cycle phase W0c's symbol resolver lands as a 12th cycle phase between extract and patterns. The autopilot's quick-cycle path (60s watchdog interval per D2 from eng review) now resolves stale chunks incrementally so agents see resolved edges within ~60s of writes rather than waiting on the slow full-walk path. * CyclePhase + ALL_PHASES + NEEDS_LOCK_PHASES extended with 'resolve_symbol_edges'. Position: between extract (which emits new bare-token edges from sync diffs) and patterns (which reads the graph). Acquires the cycle lock because it writes edge_metadata. * CycleReport.totals adds edges_resolved + edges_ambiguous so doctor and autopilot summaries surface the numbers. * runPhaseResolveSymbolEdges walks every registered source via listSources() + resolveSymbolEdgesIncremental(). Per-call cap is BATCH_SIZE*10 = 2000 chunks so a single watchdog tick stays bounded even on a 100K-chunk brain. Subsequent ticks pick up the leftovers via the edges_backfilled_at watermark. * Test count bumped from 11 → 12 phases in cycle.serial.test.ts and cycle.test.ts (both pinned by the regression guards). Existing 28 cycle tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W3): MCP-expose code_callers / code_callees / code_def / code_refs Pre-v0.34 these four code-intelligence commands lived in CLI_ONLY at cli.ts:30 — agents calling gbrain via MCP couldn't reach them and fell through to text search. This commit ships the agent-facing MCP surface for v0.34 against the existing v0.20+ tree-sitter call graph; recursive blast/flow and clusters land in subsequent commits. * `code_callers(symbol, [limit, source_id, all_sources])` — wraps engine.getCallersOf. Reverse view of the A1 call graph. * `code_callees(symbol, [limit, source_id, all_sources])` — wraps engine.getCalleesOf. Forward view. * `code_def(symbol, [limit, lang])` — wraps findCodeDef. Returns definition sites with file/line/snippet. * `code_refs(symbol, [limit, lang])` — wraps findCodeRefs. Returns every reference (comments, strings, imports, call sites). All four are scope:'read', source-scoped by default via ctx.sourceId (W0a contract). Per-call source_id param wins over ctx; pass '__all__' or all_sources=true to force cross-source. * operations-descriptions.ts: 4 new constants per the eng review D10 finding — every description carries an inline example response so agents don't burn first-call context discovering shape. Resolver-grade wording ("BEFORE editing any function, run code_callers...") routes plan-mode questions straight to the right op. * SEARCH_DESCRIPTION gains a cross-link clause pointing at the four new ops so agents stop falling through to text search for code-symbol questions. Tests (11 E2E in test/e2e/code-intel-mcp-ops-pglite.test.ts): - All four ops registered + scope:read + description pinned by constant - All four ops have required symbol param - code_callers / code_callees return the documented envelope shape - Source scoping honors ctx.sourceId - all_sources=true / source_id='__all__' force cross-source - code_def returns the def-site snippet Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(v0.33.0): agent-readable migration doc for the code-intel foundation skills/migrations/v0.33.0.md gives existing-user upgrade guidance for the v0.33.0 foundation pre-release (this branch's accumulated work toward v0.34 Cathedral III): * Source-routing fix (Codex #2) — query / two-pass now honor sourceId * CLI source-scoping default flipped (Codex #7) — gbrain code-callers defaults to source-scoped, --all-sources is the explicit opt-out * MCP exposure of code-callers / code-callees / code-def / code-refs with resolver-grade descriptions agents auto-route to * Within-file symbol resolver runs as a new `resolve_symbol_edges` cycle phase between extract and patterns * Schema migration v51: edges_backfilled_at watermark + 3 composite/ partial indexes for the resolver hot path * Verification commands the agent runs after `gbrain upgrade` Bumps the existing-user migration ladder so the auto-update agent (SKILLPACK Section 17) discovers + runs the v0.33.0 migration steps. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(v0.33.0): bump VERSION + package.json + CHANGELOG v0.33.0 ships the v0.34 Cathedral III foundation: MCP exposure of code_callers / code_callees / code_def / code_refs with resolver-grade tool descriptions, plus the source-routing fix + within-file symbol resolver + cycle-phase wiring that v0.34's recursive blast/flow and Leiden clusters will build on. Full release notes in CHANGELOG.md. Trio in lockstep: VERSION: 0.33.0 package.json: 0.33.0 CHANGELOG.md: ## [0.33.0] - 2026-05-11 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(v0.33.0): update dream-cycle phase-order assertions for resolve_symbol_edges E2E test pinned the canonical phase sequence as a regression guard. The v0.33.0 resolve_symbol_edges phase (added between extract and patterns) correctly bumps the count to 12 — caught by the canonical-order test on fresh-Postgres run, fixed by adding the new phase to EXPECTED_PHASES and bumping the version history comment. Both cycle.serial.test.ts and cycle.test.ts were already updated in the W0c cycle-phase commit (6f7dbe1d); this third pin lives in test/e2e/dream-cycle-phase-order-pglite.test.ts and was missed. Full E2E suite now: 550 passed / 0 failed / 81 files (real Postgres on port 5435 via Docker pgvector/pgvector:pg16). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 STEP 0): promote OperationContext.sourceId to REQUIRED (D4) Flip src/core/operations.ts:350 `sourceId?: string` → `sourceId: string`. Mirrors v0.26.9 `remote` REQUIRED pattern that closed the HTTP RCE class — the compiler is the first defense against any v0.34 code-intel op forgetting to thread sourceId and silently cross-contaminating retrieval across sources. - src/mcp/dispatch.ts: buildOperationContext auto-fills 'default' when opts.sourceId is undefined. Single-source brains (~80% of installs) keep working with no caller change; multi-source brains pass sourceId explicitly via dispatch opts. - src/cli.ts:makeContext: always populates sourceId via the existing resolveSourceId() 6-tier chain, falling back to 'default' on fresh/pre-init brains where the sources table doesn't exist yet. - src/commands/book-mirror.ts, src/core/minions/tools/brain-allowlist.ts: Two production context-builders that previously omitted sourceId. Both now pass sourceId: 'default' (operator-trust path, single-source by design). - 10 test/* files: every OperationContext literal now passes sourceId. test/operation-context-sourceid-required.test.ts: paired contract test (6 cases) pinning the type contract. @ts-expect-error directives on omitted-sourceId / undefined-sourceId guard against future regression; runtime tests verify buildOperationContext's auto-fill safety net. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W1): receiver-type resolution at edge-extraction time The edge-extractor emits qualified callee names (Class::method, module::method) for the 3 MUST-resolve patterns from the design doc when running against JS/TS/TSX + Python source: 1. `import { x } from 'y'; x.method()` → emit `y::method` 2. `class C { m() { this.m() } }` → emit `C::m` 3. `const c = new C(); c.m()` → emit `C::m` When the receiver can't be resolved within WALK_DEPTH_CAP (32) ancestor hops of the call site, falls back to bare-token emit (pre-W1 behavior). Ambiguous-but-named-correctly beats wrong-but-confident; the symbol resolver's second pass still gets a chance to disambiguate via same-page symbol_name_qualified lookups. Per D18 from eng review — only JS/TS/TSX + Python get receiver resolution. Ruby/Go/Rust/Java keep pre-W1 bare-token emit semantics. RECEIVER_RESOLUTION_LANGS pins the eligible set. Per D12 from eng review — WALK_DEPTH_CAP=32 covers any realistic code shape; JSX-in-JSX or closure chains rarely exceed depth-20. The cap prevents one pathological file from multiplying cycle cost across the whole brain on every dream run. - src/core/chunkers/edge-extractor.ts: new `resolveReceiverType` helper + WALK_DEPTH_CAP export + RECEIVER_RESOLUTION_LANGS set. extractCallEdges attempts resolution on every member-call emit; falls back on miss. - src/core/chunkers/symbol-resolver.ts: EDGE_EXTRACTOR_VERSION_TS bumped to 2026-05-14 so the next dream cycle re-walks every chunk and lets the resolver pick up qualified-name matches. test/code-intel/scope-walker-resolution.test.ts: 10 hermetic snapshot tests covering all 3 MUST patterns + bare-call fallback + unresolvable member call. Tests load tree-sitter WASMs on demand and short-circuit when grammars are unavailable in the test runtime. Scope reduction from the original plan: the .scm pattern-file architecture envisioned by the design doc is deferred to v0.34.1. The codebase doesn't use tree-sitter's Query API anywhere today; introducing it across chunkers/scope/patterns/* is a multi-day investment that duplicates the manual-AST-walker idiom edge-extractor.ts already uses. This commit ships the same functional outcome (qualified names for the 3 MUST patterns + depth cap + honest language scope) via the existing idiom; v0.34.1 can refactor to .scm files if/when query-API benefits materialize. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W2): edge densification — imports + references edge types Edge extractor now emits three edge kinds: - calls (v0.20 baseline; v0.34 W1 added qualified-name receiver resolution for JS/TS/TSX + Python) - imports (NEW in v0.34 W2; JS/TS/TSX + Python at depth) - references (NEW in v0.34 W2; TS-only) Why this matters: Leiden clusters on a calls-only graph produce overfit garbage (GitNexus showed 0.052 cluster/node on calls-only — useless). Adding imports + references densifies the graph so W4-5's clusters can land meaningful communities. Per design doc Constraint #1. - src/core/chunkers/edge-extractor.ts: new extractImportEdges and extractReferenceEdges functions + combined extractAllEdges wrapper. ExtractedEdge.edgeType widened to 'calls' | 'imports' | 'references'. - src/core/chunkers/code.ts: switched the chunker's edge-extraction call site from extractCallEdges to extractAllEdges so imports + references flow into code_edges_symbol alongside calls. - src/core/chunkers/symbol-resolver.ts: EDGE_EXTRACTOR_VERSION_TS bumped to 2026-05-14T01:00:00Z so the next dream cycle re-walks every chunk. Language scope per D18 from eng review: - JS/TS/TSX: imports + references emitted - Python: imports emitted, references skipped (Python type hints too sparse for v0.34; v0.35 may revisit) - Ruby/Go/Rust/Java: calls only — no imports, no references. Honest coverage matrix; code_blast/code_flow return 'unsupported_language' response for these langs (W2 commit 4 wires this). Edge schema reused: code_edges_symbol.edge_type is the existing TEXT column populated by the unique constraint (from_chunk_id, to_symbol_qualified, edge_type). Adding new types doesn't conflict with existing calls edges. test/code-intel/edge-densification.test.ts: 13 hermetic tests covering named/default/namespace/aliased/side-effect imports for JS/TS, from-x- import-y + import-pkg for Python, function parameter + return type references for TS, and unsupported-language returns-empty contract. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W3b): code_traversal_cache table, module, and clear admin op Schema migration v56 (code_traversal_cache_v0_34): - new table: code_traversal_cache (id, symbol_qualified, depth, source_id, response_json JSONB, max_chunk_updated_at, xmin_max, cluster_generation, computed_at) - unique index on (symbol_qualified, depth, source_id) - secondary index on source_id for cheap source-scoped clears D3 — generation-counter cache invalidation. cluster_generation is a BIGINT column on every cache row; bumped once per recompute_code_clusters phase via bumpClusterGeneration(). Cache rows referencing stale generations naturally miss on read. Eliminates the bug class where cluster recompute leaves stale cache entries that reference dropped or renamed clusters. D8 — destructive-guard parity. clearTraversalCache requires either source_id OR all_sources=true. Without either it throws. Mirrors v0.26.5 destructive-guard pattern; the MCP op (code_traversal_cache_clear, scope: admin, localOnly: true) inherits the gate. - src/core/code-intel/traversal-cache.ts: cache module with public API - getClusterGeneration / bumpClusterGeneration (config-backed counter) - getCachedTraversal / putCachedTraversal (low-level read/write) - getCachedOrCompute (try-cache-then-compute wrapper for W3 ops) - clearTraversalCache (admin clear with source-scope gate) - src/core/operations.ts: code_traversal_cache_clear op registered with scope: 'admin' + localOnly: true. Dry-run aware; resolves source_id from params or ctx. v0.34.0.0 scope: cache writes use xmin_max=0 sentinel (no snapshot isolation). REPEATABLE READ + xmin_max snapshot isolation + PGLite serialization_failure retry is wired in the module but disabled by default; v0.34.1 enables it once W3 ops produce enough load to justify the correctness gain. Under low-write workloads (the common case for an agent's plan-mode session, 5-15 blast calls without concurrent sync), the cache stays correctness-safe via the cluster_generation invalidation + the natural UPSERT on conflict. test/code-intel/traversal-cache.test.ts: 13 hermetic PGLite tests covering cache hit/miss, D3 generation-counter invalidation, UPSERT replacement, source-scoped + all-sources clear paths, and getCachedOrCompute try-cache-then-compute happy path. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W3): code_blast + code_flow recursive ops + sinks Recursive caller (code_blast) + recursive callee (code_flow) walks land as first-class MCP ops. The user-facing payoff for v0.34: v0.33.3 shipped flat callers/callees; v0.34 ships depth-grouped recursive walks with cycle detection, truncation flags, freshness reporting, sink tagging on terminal nodes, and bare-name disambiguation with did_you_mean suggestions. - src/core/code-intel/recursive-walk.ts: BFS over existing engine single-hop methods (getCallersOf, getCalleesOf). Depth-grouped output; confidence = clamp(1 / (1 + 0.3 * depth), 0.05, 1.0). Cycle detection via visited-set; truncation enum captures both depth_cap and max_nodes exhaustion. Source-scoped per D4 sourceId REQUIRED. - src/core/code-intel/sinks/{ts,py,index}.ts: per-language sink patterns as TypeScript constants (D9 — auditable literal-string + glob; NOT regex). Pattern cache hits warm after first match per process. TS_SINKS covers fetch, axios.*, fs.*, Bun.*, execSync, spawnSync; PY_SINKS covers requests.*, urllib.*, subprocess.*, open, pathlib.*. - src/core/operations.ts: code_blast + code_flow registered with scope: 'read'. Both wrap their walks through getCachedOrCompute (W3b) so repeat blasts in a plan-mode session hit cache. depth + max_nodes hard-capped at handler entry per design doc Constraints. exact: true skips bare-name disambiguation. Response envelope (shared): { result: 'ok' | 'not_found' | 'ambiguous' | 'unsupported_language', depth_groups?, cycles_detected?, truncation?, freshness?, did_you_mean?, candidates?, supported? } code_flow adds: terminal_nodes: [{symbol, sink_kind}] where sink_kind ∈ 'db_call' | 'http_call' | 'file_io' | 'process_exec' | 'unknown' Per D18 from eng review — only JS/TS/TSX + Python get walks. Other languages return {result: 'unsupported_language', supported: ['ts', 'tsx','js','py']} cleanly rather than aliasing same-named callees. test/code-intel/recursive-walk.test.ts: 11 hermetic PGLite tests: - 7 sinks classifier cases (http_call, file_io, db_call, process_exec for TS + Python, unknown for made-up symbol, unknown for ruby lang) - not_found returns did_you_mean - happy-path: caller chain emerges in depth_groups; confidence ~0.77 at depth 1 - truncation: depth_cap fires when walk exceeds depth - sink-tagging: fetch lands in terminal_nodes with http_call kind v0.34.0.0 scope reductions: stdio rate limiter at dispatch.ts and CLI wrappers (gbrain blast / gbrain flow) deferred — the ops are MCP- reachable today and the W8 release packaging step adds CLI thin-shims. The eng-review's stdio limiter at dispatch.ts (D10) is queued behind the eval gate run; concurrent code-intel load needed to justify it hasn't materialized at v0.34.0.0 ship time. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W6): gbrain edges-backfill CLI Operator escape hatch for the symbol-resolution backfill chain. Thin wrapper over resolveSymbolEdgesIncremental that takes explicit --source / --all-sources / --max-chunks flags. Resumable via the edges_backfilled_at watermark (W0c). Per-batch transactions commit, so Ctrl-C leaves a clean resumable state. A re-run picks up where the prior invocation stopped. Usage: gbrain edges-backfill # default source gbrain edges-backfill --source <id> # specific source gbrain edges-backfill --all-sources # every registered source gbrain edges-backfill --json # machine-readable output Wired into src/cli.ts CLI_ONLY + dispatch table. Scope reduction from the original plan: gbrain wiki (the zero-LLM cluster aggregator) is deferred to v0.34.1 alongside W4-5 clusters — without clusters, the wiki aggregator has nothing to aggregate. gbrain upgrade backfill prompt is also deferred to v0.34.1; v0.34.0.0's upgrade chain runs apply-migrations only, and users who want to materialize the new W1/W2 edge shapes invoke gbrain edges-backfill manually. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W7): per-op graph-traversal metrics module src/core/eval-capture-graph.ts — pure-function metrics module for comparing code_blast / code_flow / code_cluster_get result shapes across two runs (eval-replay's regression check). Per Codex finding #3 from the plan-review: page-slug Jaccard is the wrong metric for graph traversal. v0.34 W7 ships proper per-op metrics: - nodeSetJaccard(a, b): set Jaccard over (file, line, symbol) tuples. Right metric for code_blast/code_flow node sets. - depthGroupStability(a, b): 1 - (displaced / |union|). Catches the case where node membership is identical but nodes moved between depth buckets between runs. - truncationMatch(a, b): boolean match on the truncation enum. Discrete signal that pairs with Jaccard. - adjustedRandIndex(a, b): cluster-membership stability via ARI for code_cluster_get. v0.34.1 consumer; lands in W7 alongside the rest so the cluster-replay path is ready when clusters ship. - compareCodeWalk(a, b): convenience wrapper returning {jaccard, depth_stability, truncation_match} in one call. Hermetic — no engine, no DB, fully unit-testable. 20 test cases covering identical / disjoint / partial-overlap / empty / dedup / file+line-distinguished, depth-bucket reshuffles, truncation-enum matching, ARI identical-clustering recognition through label-rename, ARI singleton-vs-all-one expected-zero, equal-length contract, and combined compareCodeWalk envelope. Scope reduction from the original plan: extending src/core/eval-capture.ts capture wrapper with `tool` field + `result_shape` payload, and extending src/commands/eval-replay.ts to dispatch on tool — both deferred to v0.34.1. The metric MODULE is the load-bearing piece (Codex finding #3's primary fix); wiring it through the existing capture/replay surface is a follow-up that doesn't change production behavior until clusters ship. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(v0.34.0.0): VERSION + package.json + CHANGELOG + migration doc Final release packaging for v0.34.0.0. Three-line audit will show: VERSION: 0.34.0.0 package.json: 0.34.0.0 CHANGELOG: ## [0.34.0.0] - 2026-05-14 CHANGELOG entry follows CLAUDE.md voice rules: - Bold headline + lead paragraph - "What ships in v0.34.0.0" itemized list - "Slip handling — deferred to v0.34.1" honest scope note - Numbers-that-matter table comparing v0.33.3 → v0.34.0.0 - Mandatory "## To take advantage of v0.34.0.0" block with verify commands (gbrain edges-backfill, gbrain doctor, code_blast/flow, eval gate run) skills/migrations/v0.34.0.0.md — agent-readable upgrade doc. Lists the mechanical migration chain (apply-migrations adds v56), the manual `gbrain edges-backfill --all-sources` step for re-walking existing chunks with the new W1/W2 emission shape, and the slipped v0.34.1 scope. v0.34.0.0 ships: STEP 0 (sourceId REQUIRED), W1 (receiver-type resolution), W2 (imports + references), W3b (traversal cache), W3 (code_blast + code_flow + sinks), W6 (gbrain edges-backfill CLI), W7 (eval-capture-graph metrics module). v0.34.1 backlog: W4-5 Leiden clusters, W6 wiki, W7 capture wiring, W1 .scm rewrite, W3 stdio limiter, W3 CLI shims, D2 autopilot sub-loop. All deferred per the plan's explicit slip-handling clause because the cluster ship gate (≤0.03 clusters/node) and the eval gate (+10pp precision@5) both require real brain data unavailable at ship time. Test surface in v0.34.0.0 (73 hermetic pass across 6 new files): - test/operation-context-sourceid-required.test.ts (6 cases) - test/code-intel/scope-walker-resolution.test.ts (10 cases) - test/code-intel/edge-densification.test.ts (13 cases) - test/code-intel/traversal-cache.test.ts (13 cases) - test/code-intel/recursive-walk.test.ts (11 cases) - test/code-intel/eval-capture-graph.test.ts (20 cases) Migration v56 (code_traversal_cache_v0_34) verified applying clean on PGLite via the test suite. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(v0.34 D7): snapshotIndexes helper for cross-engine index parity Extends test/helpers/schema-diff.ts with snapshotIndexes() + diffIndexSnapshots() + isCleanIndexDiff() + formatIndexDiffForFailure(). Why this matters: the existing snapshotSchema() captures information_schema.columns only, so a missing INDEX (not column) between Postgres and PGLite silently passes the schema-drift test while the symbol resolver degrades from index-only-scan to Cartesian on 96K-chunk brains. The v0.34 D7 finding from the eng review called this out specifically for the W4-5 hot-path indexes (code_edges_symbol_unresolved_idx partial composite + content_chunks_symbol_lookup_idx composite). Implementation: queries pg_index + pg_class via pg_catalog views (supported by both Postgres and PGLite). Captures index name, owning table, full pg_get_indexdef() shape, uniqueness, partial-predicate. The diff compares definitions after normalizing whitespace + lowercasing — engine-specific formatting differences are filtered out so only real shape drift surfaces. Reused by future test/e2e/schema-drift.test.ts wiring (sibling test that spins up real Postgres + PGLite, snapshots both, diffs). test/helpers/schema-diff-indexes.test.ts: 7 hermetic cases on synthetic snapshots — matching, pg-only, pglite-only, uniqueness mismatch, partial-predicate mismatch, allowlist suppression, and the formatter producing a readable failure message naming the missing side. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(v0.34): update 4 pre-existing tests for new emit shapes + sourceId contract Three test files updated to match the v0.34 contract changes: - test/edge-extractor.test.ts: two assertions on `toSymbol` exact-match were brittle to the W1 receiver-type resolution. `this.go()` / `self.go()` now resolve to `Foo::go` instead of bare `go`. Tests accept either form for back-compat with brains still on pre-W1 extracted edges. - test/source-id-tx-regression.test.ts: the D16 "back-compat cross-source view preserved" test was asserting that ctx.sourceId undefined → cross-source view. v0.34 STEP 0 (D4) closes that path by design — it's the exact cross-source-bleed bug class STEP 0 fixed. Test renamed + assertion updated to reflect: makeCtx() with no override now falls back to 'default' (per the dispatch + cli auto-fill), and cross-source visibility is an explicit caller decision, not an implicit consequence of ctx omission. - test/chunker-timeout.test.ts: the GBRAIN_CHUNKER_TIMEOUT_MS=1 fallback case asserted edges=[] under the calls-only extractor. W2's extractAllEdges emits imports/references from top-level statements even on a partial parse, so the timeout-fallback path can return non-empty edges. Assertion relaxed to "edges is an array" — the contract that matters is "returns cleanly without hanging," not the edges-array shape. Full unit suite (parallel + serial): 6132 pass / 0 fail. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(migrate): remove duplicate edges_backfilled_at migration at v58 CI surfaced a duplicate migration version in test/migrate.test.ts:371 ("runMigrations sorts by version ascending" — uniq.size === versions.length). Root cause: the second master merge (PR #934 v0.33.3.0 foundation, commit3fc0ca5e) brought in master's `edges_backfilled_at` migration alongside the one already in my branch. Both functionally identical (ALTER TABLE content_chunks ADD COLUMN edges_backfilled_at + 3 indexes), both renumbered to v58 (mine via thef25b674fmerge that pushed past master's v55 search-lite migrations; master's PR #934 originally claimed v55 which would have collided). Auto-merge kept both, named `_v0_33_2` and `_v0_33_3`. Tests caught it. Fix: deleted the `_v0_33_3` duplicate. The remaining `_v0_33_2` entry at v58 is unchanged; SQL idempotency (ALTER TABLE IF NOT EXISTS + CREATE INDEX IF NOT EXISTS) means brains that already applied either label pass through cleanly. Verification: - 55 migrations total, all unique versions - `bun run typecheck` clean - `bun test test/migrate.test.ts`: 109 pass / 0 fail / 321 expect calls --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1438 lines
61 KiB
TypeScript
1438 lines
61 KiB
TypeScript
/**
|
|
* E2E Mechanical Tests — Tier 1 (no API keys required)
|
|
*
|
|
* Tests all operations against a real Postgres+pgvector database.
|
|
* Requires DATABASE_URL env var or .env.testing file.
|
|
*
|
|
* Run: DATABASE_URL=... bun test test/e2e/mechanical.test.ts
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
|
import { readFileSync, writeFileSync, mkdtempSync, rmSync } from 'fs';
|
|
import { join } from 'path';
|
|
import { execSync } from 'child_process';
|
|
import { tmpdir } from 'os';
|
|
import {
|
|
hasDatabase, setupDB, teardownDB, getEngine, getConn,
|
|
importFixtures, importFixture, time, dumpDBState, FIXTURES_PATH,
|
|
} from './helpers.ts';
|
|
import { operationsByName, operations } from '../../src/core/operations.ts';
|
|
import type { OperationContext } from '../../src/core/operations.ts';
|
|
import { importFromContent } from '../../src/core/import-file.ts';
|
|
|
|
// Skip all E2E tests if no database is configured
|
|
const skip = !hasDatabase();
|
|
const describeE2E = skip ? describe.skip : describe;
|
|
|
|
function makeCtx(opts: { remote?: boolean } = {}): OperationContext {
|
|
return {
|
|
engine: getEngine(),
|
|
config: { engine: 'postgres', database_url: process.env.DATABASE_URL! },
|
|
logger: { info: () => {}, warn: () => {}, error: () => {} },
|
|
dryRun: false,
|
|
// Default: trusted local invocation (matches `gbrain call` semantics).
|
|
remote: opts.remote ?? false,
|
|
sourceId: 'default',
|
|
};
|
|
}
|
|
|
|
async function callOp(name: string, params: Record<string, unknown> = {}) {
|
|
const op = operationsByName[name];
|
|
if (!op) throw new Error(`Unknown operation: ${name}`);
|
|
return op.handler(makeCtx(), params);
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Page CRUD
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Page CRUD', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('fixture import creates correct page count', async () => {
|
|
const stats = await callOp('get_stats') as any;
|
|
expect(stats.page_count).toBe(16);
|
|
}, 30_000);
|
|
|
|
test('get_page returns correct data for person', async () => {
|
|
const page = await callOp('get_page', { slug: 'people/sarah-chen' }) as any;
|
|
expect(page.title).toBe('Sarah Chen');
|
|
expect(page.type).toBe('person');
|
|
expect(page.compiled_truth).toContain('NovaMind');
|
|
expect(page.tags).toContain('founder');
|
|
expect(page.tags).toContain('yc-w25');
|
|
});
|
|
|
|
test('get_page returns correct data for concept', async () => {
|
|
const page = await callOp('get_page', { slug: 'concepts/retrieval-augmented-generation' }) as any;
|
|
expect(page.title).toBe('Retrieval-Augmented Generation');
|
|
expect(page.type).toBe('concept');
|
|
expect(page.compiled_truth).toContain('検索拡張生成');
|
|
});
|
|
|
|
test('get_page for company includes key details', async () => {
|
|
const page = await callOp('get_page', { slug: 'companies/novamind' }) as any;
|
|
expect(page.type).toBe('company');
|
|
expect(page.compiled_truth).toContain('Sarah Chen');
|
|
});
|
|
|
|
test('list_pages type filter returns correct count', async () => {
|
|
const people = await callOp('list_pages', { type: 'person' }) as any[];
|
|
expect(people.length).toBe(3);
|
|
|
|
const companies = await callOp('list_pages', { type: 'company' }) as any[];
|
|
expect(companies.length).toBe(3); // novamind, threshold-ventures, ohmygreen
|
|
|
|
const concepts = await callOp('list_pages', { type: 'concept' }) as any[];
|
|
expect(concepts.length).toBe(5); // compiled-truth, hybrid-search, RAG, notes-march-2024, big-file
|
|
});
|
|
|
|
test('list_pages tag filter works', async () => {
|
|
const ycPages = await callOp('list_pages', { tag: 'yc-w25' }) as any[];
|
|
expect(ycPages.length).toBeGreaterThanOrEqual(2);
|
|
expect(ycPages.some((p: any) => p.slug === 'people/sarah-chen')).toBe(true);
|
|
});
|
|
|
|
test('put_page updates existing page', async () => {
|
|
const updated = readFileSync(join(FIXTURES_PATH, 'people/sarah-chen.md'), 'utf-8')
|
|
.replace('Stanford CS', 'MIT CS');
|
|
// Use importFromContent directly with noEmbed to avoid OpenAI timeout
|
|
const engine = getEngine();
|
|
const result = await importFromContent(engine, 'people/sarah-chen', updated, { noEmbed: true });
|
|
expect(result.status).toBe('imported');
|
|
const page = await callOp('get_page', { slug: 'people/sarah-chen' }) as any;
|
|
expect(page.compiled_truth).toContain('MIT CS');
|
|
});
|
|
|
|
test('delete_page removes page and others survive', async () => {
|
|
await callOp('delete_page', { slug: 'sources/crustdata-sarah-chen' });
|
|
const stats = await callOp('get_stats') as any;
|
|
expect(stats.page_count).toBe(15);
|
|
|
|
// Other pages still exist
|
|
const sarah = await callOp('get_page', { slug: 'people/sarah-chen' }) as any;
|
|
expect(sarah.title).toBe('Sarah Chen');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Search
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Search', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('keyword search for "NovaMind" returns multiple hits', async () => {
|
|
const results = await callOp('search', { query: 'NovaMind' }) as any[];
|
|
expect(results.length).toBeGreaterThanOrEqual(3);
|
|
const slugs = results.map((r: any) => r.slug);
|
|
expect(slugs).toContain('companies/novamind');
|
|
}, 30_000);
|
|
|
|
test('keyword search for "Threshold Ventures" finds investor', async () => {
|
|
const results = await callOp('search', { query: 'Threshold Ventures' }) as any[];
|
|
expect(results.length).toBeGreaterThanOrEqual(1);
|
|
const slugs = results.map((r: any) => r.slug);
|
|
expect(slugs).toContain('companies/threshold-ventures');
|
|
});
|
|
|
|
test('keyword search for "Stanford" finds Priya', async () => {
|
|
const results = await callOp('search', { query: 'Stanford' }) as any[];
|
|
expect(results.length).toBeGreaterThanOrEqual(1);
|
|
const slugs = results.map((r: any) => r.slug);
|
|
expect(slugs).toContain('people/priya-patel');
|
|
});
|
|
|
|
test('keyword search for nonexistent term returns empty', async () => {
|
|
const results = await callOp('search', { query: 'xyznonexistent123' }) as any[];
|
|
expect(results.length).toBe(0);
|
|
});
|
|
|
|
test('search quality: precision@5 for known queries', async () => {
|
|
const groundTruth: Record<string, string[]> = {
|
|
'NovaMind': ['people/sarah-chen', 'companies/novamind', 'deals/novamind-seed'],
|
|
'hybrid search': ['concepts/hybrid-search', 'concepts/retrieval-augmented-generation'],
|
|
'compiled truth': ['concepts/compiled-truth'],
|
|
};
|
|
|
|
const scores: Record<string, number> = {};
|
|
for (const [query, expected] of Object.entries(groundTruth)) {
|
|
const results = await callOp('search', { query, limit: 5 }) as any[];
|
|
const topSlugs = results.slice(0, 5).map((r: any) => r.slug);
|
|
const hits = expected.filter(e => topSlugs.includes(e));
|
|
scores[query] = hits.length / Math.min(expected.length, 5);
|
|
}
|
|
|
|
console.log('\n Search Quality (precision@5, keyword-only):');
|
|
for (const [query, score] of Object.entries(scores)) {
|
|
console.log(` "${query}": ${(score * 100).toFixed(0)}%`);
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Links
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Links', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('add_link + get_links + get_backlinks round trip', async () => {
|
|
await callOp('add_link', {
|
|
from: 'people/sarah-chen',
|
|
to: 'companies/novamind',
|
|
link_type: 'founded',
|
|
context: 'CEO and founder since 2024',
|
|
});
|
|
|
|
const links = await callOp('get_links', { slug: 'people/sarah-chen' }) as any[];
|
|
expect(links.some((l: any) => l.to_slug === 'companies/novamind' || l.to_page_slug === 'companies/novamind')).toBe(true);
|
|
|
|
const backlinks = await callOp('get_backlinks', { slug: 'companies/novamind' }) as any[];
|
|
expect(backlinks.some((l: any) => l.from_slug === 'people/sarah-chen' || l.from_page_slug === 'people/sarah-chen')).toBe(true);
|
|
}, 30_000);
|
|
|
|
test('traverse_graph finds connected pages', async () => {
|
|
// Links should already be added from prior test in this describe block
|
|
const graph = await callOp('traverse_graph', { slug: 'people/sarah-chen', depth: 2 }) as any;
|
|
expect(Array.isArray(graph)).toBe(true);
|
|
expect(graph.length).toBeGreaterThanOrEqual(1);
|
|
});
|
|
|
|
test('remove_link removes the link', async () => {
|
|
await callOp('add_link', { from: 'people/marcus-reid', to: 'companies/threshold-ventures' });
|
|
await callOp('remove_link', { from: 'people/marcus-reid', to: 'companies/threshold-ventures' });
|
|
|
|
const links = await callOp('get_links', { slug: 'people/marcus-reid' }) as any[];
|
|
const hasLink = links.some((l: any) =>
|
|
(l.to_slug || l.to_page_slug) === 'companies/threshold-ventures'
|
|
);
|
|
expect(hasLink).toBe(false);
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Tags
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Tags', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('get_tags returns imported tags', async () => {
|
|
const tags = await callOp('get_tags', { slug: 'people/sarah-chen' }) as string[];
|
|
expect(tags).toContain('founder');
|
|
expect(tags).toContain('yc-w25');
|
|
expect(tags).toContain('ai-agents');
|
|
}, 30_000);
|
|
|
|
test('add_tag + remove_tag round trip', async () => {
|
|
await callOp('add_tag', { slug: 'people/marcus-reid', tag: 'test-tag' });
|
|
let tags = await callOp('get_tags', { slug: 'people/marcus-reid' }) as string[];
|
|
expect(tags).toContain('test-tag');
|
|
|
|
await callOp('remove_tag', { slug: 'people/marcus-reid', tag: 'test-tag' });
|
|
tags = await callOp('get_tags', { slug: 'people/marcus-reid' }) as string[];
|
|
expect(tags).not.toContain('test-tag');
|
|
});
|
|
|
|
test('list_pages with tag filter finds tagged pages', async () => {
|
|
await callOp('add_tag', { slug: 'people/priya-patel', tag: 'test-search-tag' });
|
|
const pages = await callOp('list_pages', { tag: 'test-search-tag' }) as any[];
|
|
expect(pages.length).toBe(1);
|
|
expect(pages[0].slug).toBe('people/priya-patel');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Timeline
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Timeline', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('add_timeline_entry + get_timeline round trip', async () => {
|
|
await callOp('add_timeline_entry', {
|
|
slug: 'people/sarah-chen',
|
|
date: '2025-04-01',
|
|
summary: 'Test timeline entry',
|
|
detail: 'Added via E2E test',
|
|
source: 'e2e-test',
|
|
});
|
|
|
|
const timeline = await callOp('get_timeline', { slug: 'people/sarah-chen' }) as any[];
|
|
expect(timeline.length).toBeGreaterThanOrEqual(1);
|
|
const entry = timeline.find((e: any) => e.summary === 'Test timeline entry');
|
|
expect(entry).toBeDefined();
|
|
}, 30_000);
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Batch methods (addLinksBatch / addTimelineEntriesBatch)
|
|
// ─────────────────────────────────────────────────────────────────
|
|
//
|
|
// Postgres-engine batch methods use postgres-js's sql(rows, 'col1', ...) helper,
|
|
// which is structurally different from PGLite's manual $N placeholder construction
|
|
// (covered in test/pglite-engine.test.ts). These tests verify the postgres-js code
|
|
// path against a real Postgres against the same invariants.
|
|
|
|
describeE2E('E2E: addLinksBatch (postgres-engine)', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('empty batch returns 0 with no DB call', async () => {
|
|
const engine = getEngine();
|
|
expect(await engine.addLinksBatch([])).toBe(0);
|
|
}, 30_000);
|
|
|
|
test('within-batch duplicates dedup via ON CONFLICT (no 21000 cardinality error)', async () => {
|
|
const engine = getEngine();
|
|
const conn = getConn();
|
|
// Deterministic cleanup so re-runs aren't perturbed by prior fixture state.
|
|
await conn`DELETE FROM links WHERE link_type = 'e2e-batch-dup'`;
|
|
const inserted = await engine.addLinksBatch([
|
|
{ from_slug: 'people/sarah-chen', to_slug: 'companies/novamind', link_type: 'e2e-batch-dup' },
|
|
{ from_slug: 'people/sarah-chen', to_slug: 'companies/novamind', link_type: 'e2e-batch-dup' },
|
|
]);
|
|
expect(inserted).toBe(1);
|
|
await conn`DELETE FROM links WHERE link_type = 'e2e-batch-dup'`;
|
|
});
|
|
|
|
test('rows with missing slug silently dropped by JOIN', async () => {
|
|
const engine = getEngine();
|
|
const conn = getConn();
|
|
await conn`DELETE FROM links WHERE link_type = 'e2e-batch-missing'`;
|
|
const inserted = await engine.addLinksBatch([
|
|
{ from_slug: 'people/does-not-exist', to_slug: 'companies/novamind', link_type: 'e2e-batch-missing' },
|
|
{ from_slug: 'people/sarah-chen', to_slug: 'companies/novamind', link_type: 'e2e-batch-missing' },
|
|
]);
|
|
expect(inserted).toBe(1);
|
|
await conn`DELETE FROM links WHERE link_type = 'e2e-batch-missing'`;
|
|
});
|
|
|
|
test('half-existing batch returns count of new only', async () => {
|
|
const engine = getEngine();
|
|
const conn = getConn();
|
|
await conn`DELETE FROM links WHERE link_type = 'e2e-batch-half'`;
|
|
await engine.addLink('people/sarah-chen', 'companies/novamind', 'pre-existing', 'e2e-batch-half');
|
|
const inserted = await engine.addLinksBatch([
|
|
{ from_slug: 'people/sarah-chen', to_slug: 'companies/novamind', link_type: 'e2e-batch-half' },
|
|
{ from_slug: 'people/sarah-chen', to_slug: 'people/marcus-reid', link_type: 'e2e-batch-half' },
|
|
]);
|
|
expect(inserted).toBe(1);
|
|
await conn`DELETE FROM links WHERE link_type = 'e2e-batch-half'`;
|
|
});
|
|
|
|
test('missing optional fields normalize to empty strings (NOT NULL safety)', async () => {
|
|
const engine = getEngine();
|
|
const conn = getConn();
|
|
await conn`DELETE FROM links WHERE link_type = ''`;
|
|
// No link_type, no context — must default to '' to satisfy NOT NULL.
|
|
const inserted = await engine.addLinksBatch([
|
|
{ from_slug: 'people/sarah-chen', to_slug: 'companies/novamind' },
|
|
]);
|
|
expect(inserted).toBe(1);
|
|
const rows = await conn`
|
|
SELECT link_type, context FROM links
|
|
WHERE from_page_id = (SELECT id FROM pages WHERE slug = 'people/sarah-chen')
|
|
AND to_page_id = (SELECT id FROM pages WHERE slug = 'companies/novamind')
|
|
AND link_type = ''
|
|
`;
|
|
expect(rows.length).toBe(1);
|
|
expect(rows[0].context).toBe('');
|
|
await conn`DELETE FROM links WHERE link_type = ''`;
|
|
});
|
|
});
|
|
|
|
describeE2E('E2E: addTimelineEntriesBatch (postgres-engine)', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('empty batch returns 0', async () => {
|
|
const engine = getEngine();
|
|
expect(await engine.addTimelineEntriesBatch([])).toBe(0);
|
|
}, 30_000);
|
|
|
|
test('within-batch duplicates dedup via ON CONFLICT', async () => {
|
|
const engine = getEngine();
|
|
const conn = getConn();
|
|
await conn`DELETE FROM timeline_entries WHERE summary = 'e2e-batch-tl-dup'`;
|
|
const inserted = await engine.addTimelineEntriesBatch([
|
|
{ slug: 'people/sarah-chen', date: '2025-05-01', summary: 'e2e-batch-tl-dup' },
|
|
{ slug: 'people/sarah-chen', date: '2025-05-01', summary: 'e2e-batch-tl-dup' },
|
|
]);
|
|
expect(inserted).toBe(1);
|
|
await conn`DELETE FROM timeline_entries WHERE summary = 'e2e-batch-tl-dup'`;
|
|
});
|
|
|
|
test('rows with missing slug silently dropped by JOIN', async () => {
|
|
const engine = getEngine();
|
|
const conn = getConn();
|
|
await conn`DELETE FROM timeline_entries WHERE summary = 'e2e-batch-tl-missing'`;
|
|
const inserted = await engine.addTimelineEntriesBatch([
|
|
{ slug: 'people/no-such-page', date: '2025-05-02', summary: 'e2e-batch-tl-missing' },
|
|
{ slug: 'people/sarah-chen', date: '2025-05-02', summary: 'e2e-batch-tl-missing' },
|
|
]);
|
|
expect(inserted).toBe(1);
|
|
await conn`DELETE FROM timeline_entries WHERE summary = 'e2e-batch-tl-missing'`;
|
|
});
|
|
|
|
test('mix of new + existing returns count of new only', async () => {
|
|
const engine = getEngine();
|
|
const conn = getConn();
|
|
await conn`DELETE FROM timeline_entries WHERE summary IN ('e2e-batch-tl-half-1', 'e2e-batch-tl-half-2')`;
|
|
await engine.addTimelineEntry('people/sarah-chen', { date: '2025-05-03', summary: 'e2e-batch-tl-half-1' });
|
|
const inserted = await engine.addTimelineEntriesBatch([
|
|
{ slug: 'people/sarah-chen', date: '2025-05-03', summary: 'e2e-batch-tl-half-1' },
|
|
{ slug: 'people/sarah-chen', date: '2025-05-04', summary: 'e2e-batch-tl-half-2' },
|
|
]);
|
|
expect(inserted).toBe(1);
|
|
await conn`DELETE FROM timeline_entries WHERE summary IN ('e2e-batch-tl-half-1', 'e2e-batch-tl-half-2')`;
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Versions
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Versions', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('put_page creates version, revert restores', async () => {
|
|
const original = await callOp('get_page', { slug: 'people/sarah-chen' }) as any;
|
|
|
|
// Modify page using importFromContent with noEmbed
|
|
const modified = readFileSync(join(FIXTURES_PATH, 'people/sarah-chen.md'), 'utf-8')
|
|
.replace('Sarah Chen', 'Sarah Chen (Modified)');
|
|
const engine = getEngine();
|
|
await importFromContent(engine, 'people/sarah-chen', modified, { noEmbed: true });
|
|
|
|
// Check versions exist
|
|
const versions = await callOp('get_versions', { slug: 'people/sarah-chen' }) as any[];
|
|
expect(versions.length).toBeGreaterThanOrEqual(1);
|
|
|
|
// Revert to first version
|
|
const firstVersion = versions[versions.length - 1];
|
|
await callOp('revert_version', { slug: 'people/sarah-chen', version_id: firstVersion.id });
|
|
|
|
const reverted = await callOp('get_page', { slug: 'people/sarah-chen' }) as any;
|
|
expect(reverted.compiled_truth).not.toContain('(Modified)');
|
|
}, 30_000);
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Admin
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Admin', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('get_stats returns valid structure', async () => {
|
|
const stats = await callOp('get_stats') as any;
|
|
expect(stats.page_count).toBe(16);
|
|
expect(typeof stats.chunk_count).toBe('number');
|
|
}, 30_000);
|
|
|
|
test('get_health returns valid structure', async () => {
|
|
const health = await callOp('get_health') as any;
|
|
expect(health).toBeDefined();
|
|
expect(typeof health.page_count).toBe('number');
|
|
expect(typeof health.embed_coverage).toBe('number');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Chunks & Resolution
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Chunks & Resolution', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('get_chunks returns chunks for imported page', async () => {
|
|
const chunks = await callOp('get_chunks', { slug: 'people/sarah-chen' }) as any[];
|
|
expect(chunks.length).toBeGreaterThan(0);
|
|
expect(chunks[0].chunk_text).toBeTruthy();
|
|
}, 30_000);
|
|
|
|
test('resolve_slugs finds partial match', async () => {
|
|
const matches = await callOp('resolve_slugs', { partial: 'sarah' }) as string[];
|
|
expect(matches).toContain('people/sarah-chen');
|
|
});
|
|
|
|
test('resolve_slugs finds exact match', async () => {
|
|
const matches = await callOp('resolve_slugs', { partial: 'people/sarah-chen' }) as string[];
|
|
expect(matches).toContain('people/sarah-chen');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Ingest Log & Raw Data
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Ingest Log & Raw Data', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('log_ingest + get_ingest_log round trip', async () => {
|
|
await callOp('log_ingest', {
|
|
source_type: 'e2e-test',
|
|
source_ref: 'test-run-1',
|
|
pages_updated: ['people/sarah-chen', 'companies/novamind'],
|
|
summary: 'E2E test ingest',
|
|
});
|
|
|
|
const log = await callOp('get_ingest_log', { limit: 5 }) as any[];
|
|
expect(log.length).toBeGreaterThanOrEqual(1);
|
|
const entry = log.find((e: any) => e.source_ref === 'test-run-1');
|
|
expect(entry).toBeDefined();
|
|
expect(entry.source_type).toBe('e2e-test');
|
|
}, 30_000);
|
|
|
|
test('put_raw_data + get_raw_data round trip', async () => {
|
|
const testData = { education: 'Stanford CS 2020', title: 'CEO' };
|
|
await callOp('put_raw_data', {
|
|
slug: 'people/sarah-chen',
|
|
source: 'crustdata',
|
|
data: testData,
|
|
});
|
|
|
|
const raw = await callOp('get_raw_data', {
|
|
slug: 'people/sarah-chen',
|
|
source: 'crustdata',
|
|
}) as any[];
|
|
expect(raw.length).toBeGreaterThanOrEqual(1);
|
|
// JSONB may come back as string or parsed object
|
|
const data = typeof raw[0].data === 'string' ? JSON.parse(raw[0].data) : raw[0].data;
|
|
expect(data.education).toBe('Stanford CS 2020');
|
|
expect(data.title).toBe('CEO');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Files (stub verification)
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Files', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('file_list returns empty initially', async () => {
|
|
const files = await callOp('file_list', {}) as any[];
|
|
expect(files.length).toBe(0);
|
|
}, 30_000);
|
|
|
|
test('file_upload stores metadata + file_list shows it', async () => {
|
|
// Create a temp file
|
|
const tmpDir = mkdtempSync(join(tmpdir(), 'gbrain-e2e-'));
|
|
const tmpFile = join(tmpDir, 'test-doc.pdf');
|
|
writeFileSync(tmpFile, 'fake pdf content');
|
|
|
|
try {
|
|
const result = await callOp('file_upload', {
|
|
path: tmpFile,
|
|
page_slug: 'people/sarah-chen',
|
|
}) as any;
|
|
expect(result.status).toBe('uploaded');
|
|
expect(result.storage_path).toContain('sarah-chen');
|
|
|
|
// Verify file_list
|
|
const files = await callOp('file_list', {}) as any[];
|
|
expect(files.length).toBe(1);
|
|
|
|
// Verify file_url returns URI format
|
|
const url = await callOp('file_url', { storage_path: result.storage_path }) as any;
|
|
expect(url.url).toContain('gbrain:files/');
|
|
} finally {
|
|
rmSync(tmpDir, { recursive: true });
|
|
}
|
|
});
|
|
|
|
// Security-wave-3 regression: MCP/remote callers MUST be confined to cwd
|
|
// (Issue #139). Local CLI callers are unrestricted — different trust model.
|
|
test('file_upload rejects outside-cwd paths for remote (MCP) callers', async () => {
|
|
const tmpDir = mkdtempSync(join(tmpdir(), 'gbrain-e2e-ssrf-'));
|
|
const tmpFile = join(tmpDir, 'stealable.txt');
|
|
writeFileSync(tmpFile, 'sensitive');
|
|
|
|
try {
|
|
const op = operationsByName['file_upload'];
|
|
let threw = false;
|
|
try {
|
|
await op.handler(makeCtx({ remote: true }), {
|
|
path: tmpFile,
|
|
page_slug: 'people/sarah-chen',
|
|
});
|
|
} catch (e: any) {
|
|
threw = true;
|
|
expect(String(e.message || e)).toMatch(/within the working directory/i);
|
|
}
|
|
expect(threw).toBe(true);
|
|
} finally {
|
|
rmSync(tmpDir, { recursive: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Security: Query Bounds
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: file_list LIMIT enforcement', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('file_list with slug filter respects LIMIT 100', async () => {
|
|
const sql = getConn();
|
|
const testSlug = 'test-limit-slug';
|
|
|
|
// Create the parent page first (FK constraint on files.page_slug)
|
|
await sql`
|
|
INSERT INTO pages (slug, title, type, compiled_truth, frontmatter)
|
|
VALUES (${testSlug}, ${'Test Limit Page'}, ${'note'}, ${'body'}, ${'{}'}::jsonb)
|
|
ON CONFLICT (source_id, slug) DO NOTHING
|
|
`;
|
|
|
|
// Insert 150 file rows for the same slug
|
|
for (let i = 0; i < 150; i++) {
|
|
await sql`
|
|
INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
|
|
VALUES (${testSlug}, ${'file-' + String(i).padStart(3, '0') + '.txt'}, ${testSlug + '/file-' + i + '.txt'}, ${'text/plain'}, ${100}, ${'hash-' + i}, ${'{}'}::jsonb)
|
|
ON CONFLICT (storage_path) DO NOTHING
|
|
`;
|
|
}
|
|
|
|
// Verify we inserted 150
|
|
const count = await sql`SELECT count(*) as cnt FROM files WHERE page_slug = ${testSlug}`;
|
|
expect(Number(count[0].cnt)).toBe(150);
|
|
|
|
// Call file_list with slug — should return at most 100
|
|
const files = await callOp('file_list', { slug: testSlug }) as any[];
|
|
expect(files.length).toBeLessThanOrEqual(100);
|
|
expect(files.length).toBe(100);
|
|
}, 30_000);
|
|
|
|
test('file_list without slug also respects LIMIT 100', async () => {
|
|
// The 150 rows from the previous test are still in the DB
|
|
const files = await callOp('file_list', {}) as any[];
|
|
expect(files.length).toBeLessThanOrEqual(100);
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Idempotency Stress
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Idempotency', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('double import produces no duplicates', async () => {
|
|
// First import
|
|
await importFixtures();
|
|
const stats1 = await callOp('get_stats') as any;
|
|
|
|
// Second import (identical content)
|
|
await importFixtures();
|
|
const stats2 = await callOp('get_stats') as any;
|
|
|
|
expect(stats2.page_count).toBe(stats1.page_count);
|
|
expect(stats2.chunk_count).toBe(stats1.chunk_count);
|
|
}, 30_000);
|
|
|
|
test('modify one fixture, reimport, only that page updates', async () => {
|
|
await importFixtures();
|
|
const engine = getEngine();
|
|
|
|
// Modify sarah-chen content
|
|
const modified = readFileSync(join(FIXTURES_PATH, 'people/sarah-chen.md'), 'utf-8')
|
|
.replace('Stanford CS', 'MIT CS');
|
|
|
|
const result = await importFromContent(engine, 'people/sarah-chen', modified, { noEmbed: true });
|
|
expect(result.status).toBe('imported');
|
|
|
|
// Other pages should have been skipped if reimported
|
|
const content = readFileSync(join(FIXTURES_PATH, 'people/marcus-reid.md'), 'utf-8');
|
|
const { parseMarkdown } = await import('../../src/core/markdown.ts');
|
|
const parsed = parseMarkdown(content, 'people/marcus-reid.md');
|
|
const result2 = await importFromContent(engine, parsed.slug, content, { noEmbed: true });
|
|
expect(result2.status).toBe('skipped');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Setup Journey (CLI subprocess tests)
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Setup Journey', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
const cliCwd = join(import.meta.dir, '../..');
|
|
const cliEnv = () => ({ ...process.env, DATABASE_URL: process.env.DATABASE_URL! });
|
|
|
|
test('gbrain init --non-interactive connects and initializes', () => {
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 15_000,
|
|
});
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(stdout).toContain('Brain ready');
|
|
}, 30_000);
|
|
|
|
test('gbrain import imports fixtures via CLI', () => {
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'import', '--no-embed', FIXTURES_PATH],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 30_000,
|
|
});
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(stdout).toContain('imported');
|
|
}, 60_000);
|
|
|
|
test('gbrain search returns results via CLI', () => {
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'search', 'NovaMind'],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 15_000,
|
|
});
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(stdout.length).toBeGreaterThan(0);
|
|
}, 30_000);
|
|
|
|
test('gbrain stats shows page count via CLI', () => {
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'stats'],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 15_000,
|
|
});
|
|
expect(result.exitCode).toBe(0);
|
|
}, 30_000);
|
|
|
|
test('gbrain health runs via CLI', () => {
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'health'],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 15_000,
|
|
});
|
|
expect(result.exitCode).toBe(0);
|
|
}, 30_000);
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Init Edge Cases
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Init Edge Cases', () => {
|
|
afterAll(teardownDB);
|
|
|
|
test('init --non-interactive without URL fails gracefully', () => {
|
|
const env = { ...process.env };
|
|
delete env.DATABASE_URL;
|
|
delete env.GBRAIN_DATABASE_URL;
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive'],
|
|
cwd: join(import.meta.dir, '../..'),
|
|
env,
|
|
timeout: 10_000,
|
|
});
|
|
expect(result.exitCode).not.toBe(0);
|
|
}, 30_000);
|
|
|
|
test('double init is idempotent', async () => {
|
|
await setupDB();
|
|
const conn = getConn();
|
|
const before = await conn.unsafe(`SELECT count(*) as n FROM information_schema.tables WHERE table_schema = 'public'`);
|
|
|
|
// Re-init
|
|
const { initSchema } = await import('../../src/core/db.ts');
|
|
await initSchema();
|
|
|
|
const after = await conn.unsafe(`SELECT count(*) as n FROM information_schema.tables WHERE table_schema = 'public'`);
|
|
expect(after[0].n).toBe(before[0].n);
|
|
});
|
|
|
|
test('init then import then re-init preserves pages', async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
const before = await callOp('get_stats') as any;
|
|
|
|
const { initSchema } = await import('../../src/core/db.ts');
|
|
await initSchema();
|
|
|
|
const after = await callOp('get_stats') as any;
|
|
expect(after.page_count).toBe(before.page_count);
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Schema Idempotency
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Schema Idempotency', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('initSchema twice produces no errors and same object count', async () => {
|
|
const conn = getConn();
|
|
const tables1 = await conn.unsafe(`SELECT count(*) as n FROM information_schema.tables WHERE table_schema = 'public'`);
|
|
const indexes1 = await conn.unsafe(`SELECT count(*) as n FROM pg_indexes WHERE schemaname = 'public'`);
|
|
|
|
const { initSchema } = await import('../../src/core/db.ts');
|
|
await initSchema();
|
|
|
|
const tables2 = await conn.unsafe(`SELECT count(*) as n FROM information_schema.tables WHERE table_schema = 'public'`);
|
|
const indexes2 = await conn.unsafe(`SELECT count(*) as n FROM pg_indexes WHERE schemaname = 'public'`);
|
|
|
|
expect(tables2[0].n).toBe(tables1[0].n);
|
|
expect(indexes2[0].n).toBe(indexes1[0].n);
|
|
}, 30_000);
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Schema Diff Guard
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Schema Diff Guard', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('all expected tables exist', async () => {
|
|
const conn = getConn();
|
|
const tables = await conn.unsafe(`
|
|
SELECT table_name FROM information_schema.tables
|
|
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
|
|
ORDER BY table_name
|
|
`);
|
|
const tableNames = tables.map((t: any) => t.table_name);
|
|
|
|
const expected = [
|
|
'config', 'content_chunks', 'files', 'ingest_log',
|
|
'links', 'page_versions', 'pages', 'raw_data',
|
|
'tags', 'timeline_entries',
|
|
];
|
|
for (const table of expected) {
|
|
expect(tableNames).toContain(table);
|
|
}
|
|
}, 30_000);
|
|
|
|
test('pgvector extension is installed', async () => {
|
|
const conn = getConn();
|
|
const ext = await conn.unsafe(`SELECT extname FROM pg_extension WHERE extname = 'vector'`);
|
|
expect(ext.length).toBe(1);
|
|
});
|
|
|
|
test('pg_trgm extension is installed', async () => {
|
|
const conn = getConn();
|
|
const ext = await conn.unsafe(`SELECT extname FROM pg_extension WHERE extname = 'pg_trgm'`);
|
|
expect(ext.length).toBe(1);
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Slug with Special Characters (Apple Notes fix)
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Slug with Special Characters', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('imports files with spaces in filename', async () => {
|
|
const page = await callOp('get_page', { slug: 'apple-notes/2017-05-03-ohmygreen' }) as any;
|
|
expect(page).not.toBeNull();
|
|
expect(page.title).toBe('OhMyGreen');
|
|
expect(page.type).toBe('company');
|
|
}, 30_000);
|
|
|
|
test('imports files with parens in filename', async () => {
|
|
const page = await callOp('get_page', { slug: 'apple-notes/notes-march-2024' }) as any;
|
|
expect(page).not.toBeNull();
|
|
expect(page.title).toBe('March 2024 Notes');
|
|
});
|
|
|
|
test('search finds content from special-char files', async () => {
|
|
const results = await callOp('search', { query: 'OhMyGreen' }) as any[];
|
|
expect(results.length).toBeGreaterThanOrEqual(1);
|
|
const slugs = results.map((r: any) => r.slug);
|
|
expect(slugs).toContain('apple-notes/2017-05-03-ohmygreen');
|
|
});
|
|
|
|
test('re-import of special-char files is idempotent', async () => {
|
|
const before = await callOp('get_stats') as any;
|
|
await importFixtures(); // second import
|
|
const after = await callOp('get_stats') as any;
|
|
expect(after.page_count).toBe(before.page_count);
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// RLS Verification
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: RLS Verification', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
const cliCwd = join(import.meta.dir, '../..');
|
|
const cliEnv = () => ({ ...process.env, DATABASE_URL: process.env.DATABASE_URL!, GBRAIN_DATABASE_URL: process.env.DATABASE_URL! });
|
|
|
|
// Seed a unique suffix per run so concurrent test DBs / crashed prior
|
|
// runs don't collide. All helper tables follow `gbrain_rls_regression_<suffix>`.
|
|
const suffix = `${process.pid}_${Date.now()}`;
|
|
|
|
test('RLS is enabled on every public table (no hardcoded allowlist)', async () => {
|
|
const conn = getConn();
|
|
const tables = await conn.unsafe(`
|
|
SELECT tablename, rowsecurity FROM pg_tables
|
|
WHERE schemaname = 'public'
|
|
`);
|
|
const noRls = tables.filter((t: any) => !t.rowsecurity);
|
|
// Some test DBs may not have BYPASSRLS privilege, so RLS might be skipped.
|
|
// If RLS was enabled at all (the common case against Docker postgres), EVERY
|
|
// public table must have it — no hardcoded IN-list exceptions.
|
|
if (tables.some((t: any) => t.rowsecurity)) {
|
|
expect(noRls.map((t: any) => t.tablename)).toEqual([]);
|
|
}
|
|
}, 30_000);
|
|
|
|
test('current user role has BYPASSRLS', async () => {
|
|
const conn = getConn();
|
|
const rows = await conn.unsafe(`SELECT rolbypassrls FROM pg_roles WHERE rolname = current_user`);
|
|
if (rows.length > 0) {
|
|
expect(rows[0].rolbypassrls).toBe(true);
|
|
}
|
|
});
|
|
|
|
test('gbrain doctor fails with exit 1 when a public table is missing RLS', async () => {
|
|
const conn = getConn();
|
|
const tbl = `gbrain_rls_regression_${suffix}`;
|
|
try {
|
|
// Init first so all migrations (including v35's auto-RLS event trigger
|
|
// and one-time backfill) are applied. AFTER migrations run, simulate
|
|
// the post-v35 escape route: operator drops the auto-RLS trigger
|
|
// (e.g. while debugging) and creates a public table without RLS.
|
|
// doctor's existing rls check must still flag it. The new
|
|
// rls_event_trigger check warns separately about the missing trigger.
|
|
Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 15_000,
|
|
});
|
|
|
|
// Drop the trigger so CREATE TABLE doesn't auto-enable RLS, then create
|
|
// the test table without RLS. ALTER TABLE … DISABLE is a belt-and-
|
|
// suspenders no-op in this path but matches what an operator would do
|
|
// if they had toggled RLS off manually after the trigger ran.
|
|
await conn.unsafe(`DROP EVENT TRIGGER IF EXISTS auto_rls_on_create_table`);
|
|
await conn.unsafe(`CREATE TABLE public.${tbl} (id int)`);
|
|
await conn.unsafe(`ALTER TABLE public.${tbl} DISABLE ROW LEVEL SECURITY`);
|
|
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'doctor', '--json'],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 20_000,
|
|
});
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
const parsed = JSON.parse(stdout);
|
|
const rls = parsed.checks.find((c: any) => c.name === 'rls');
|
|
expect(rls).toBeDefined();
|
|
expect(rls.status).toBe('fail');
|
|
expect(rls.message).toContain(tbl);
|
|
expect(rls.message).toContain('ALTER TABLE');
|
|
expect(result.exitCode).toBe(1);
|
|
} finally {
|
|
await conn.unsafe(`DROP TABLE IF EXISTS public.${tbl}`);
|
|
// Restore the trigger via a no-op v35 replay so subsequent tests in
|
|
// this file (which expect the post-init steady state) don't see drift.
|
|
const { MIGRATIONS } = await import('../../src/core/migrate.ts');
|
|
const v35sql = (MIGRATIONS.find(m => m.version === 35)?.sqlFor as any)?.postgres;
|
|
if (v35sql) await conn.unsafe(v35sql);
|
|
}
|
|
}, 60_000);
|
|
|
|
test('GBRAIN:RLS_EXEMPT comment with valid reason exempts a non-RLS public table', async () => {
|
|
const conn = getConn();
|
|
const tbl = `gbrain_rls_exempt_ok_${suffix}`;
|
|
try {
|
|
await conn.unsafe(`CREATE TABLE public.${tbl} (id int)`);
|
|
await conn.unsafe(`ALTER TABLE public.${tbl} DISABLE ROW LEVEL SECURITY`);
|
|
await conn.unsafe(`COMMENT ON TABLE public.${tbl} IS 'GBRAIN:RLS_EXEMPT reason=e2e test fixture, anon-readable ok'`);
|
|
|
|
Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 15_000,
|
|
});
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'doctor', '--json'],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 20_000,
|
|
});
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
const parsed = JSON.parse(stdout);
|
|
const rls = parsed.checks.find((c: any) => c.name === 'rls');
|
|
expect(rls.status).toBe('ok');
|
|
expect(rls.message).toContain('explicitly exempt');
|
|
expect(rls.message).toContain(tbl);
|
|
} finally {
|
|
await conn.unsafe(`DROP TABLE IF EXISTS public.${tbl}`);
|
|
}
|
|
}, 60_000);
|
|
|
|
test('GBRAIN:RLS_EXEMPT comment WITHOUT reason= still fails doctor', async () => {
|
|
const conn = getConn();
|
|
const tbl = `gbrain_rls_exempt_bad_${suffix}`;
|
|
try {
|
|
await conn.unsafe(`CREATE TABLE public.${tbl} (id int)`);
|
|
await conn.unsafe(`ALTER TABLE public.${tbl} DISABLE ROW LEVEL SECURITY`);
|
|
// Missing the `reason=<...>` segment — prefix alone is not enough.
|
|
await conn.unsafe(`COMMENT ON TABLE public.${tbl} IS 'GBRAIN:RLS_EXEMPT'`);
|
|
|
|
Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 15_000,
|
|
});
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'doctor', '--json'],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 20_000,
|
|
});
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
const parsed = JSON.parse(stdout);
|
|
const rls = parsed.checks.find((c: any) => c.name === 'rls');
|
|
expect(rls.status).toBe('fail');
|
|
expect(rls.message).toContain(tbl);
|
|
expect(result.exitCode).toBe(1);
|
|
} finally {
|
|
await conn.unsafe(`DROP TABLE IF EXISTS public.${tbl}`);
|
|
}
|
|
}, 60_000);
|
|
|
|
test('Non-exempt unrelated COMMENT on a no-RLS table still fails doctor', async () => {
|
|
const conn = getConn();
|
|
const tbl = `gbrain_rls_comment_${suffix}`;
|
|
try {
|
|
await conn.unsafe(`CREATE TABLE public.${tbl} (id int)`);
|
|
await conn.unsafe(`ALTER TABLE public.${tbl} DISABLE ROW LEVEL SECURITY`);
|
|
await conn.unsafe(`COMMENT ON TABLE public.${tbl} IS 'Regular docs comment, not an exemption'`);
|
|
|
|
Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 15_000,
|
|
});
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'doctor', '--json'],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 20_000,
|
|
});
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
const parsed = JSON.parse(stdout);
|
|
const rls = parsed.checks.find((c: any) => c.name === 'rls');
|
|
expect(rls.status).toBe('fail');
|
|
expect(result.exitCode).toBe(1);
|
|
} finally {
|
|
await conn.unsafe(`DROP TABLE IF EXISTS public.${tbl}`);
|
|
}
|
|
}, 60_000);
|
|
|
|
// Regression test for the v24 self-healing guard. If an operator manually
|
|
// drops budget_ledger and/or budget_reservations (they are migration-only
|
|
// per v12, not in schema.sql, and the data is regenerable from resolver
|
|
// logs — so dropping them is a reasonable cleanup), v24 must NOT fail
|
|
// with 42P01. The information_schema.tables IF EXISTS guards around those
|
|
// two ALTERs let the migration skip them and continue.
|
|
//
|
|
// Without the guard, a brain with dropped budget_* tables would get stuck
|
|
// in an infinite retry loop: v24 fails → transaction rolls back →
|
|
// schema_version stays at prior value → next initSchema re-runs v24 →
|
|
// same failure forever.
|
|
test('v24 self-heals when budget_ledger + budget_reservations are missing', async () => {
|
|
const conn = getConn();
|
|
let priorVersion: string | null = null;
|
|
try {
|
|
// Capture current version so we can restore after the test.
|
|
const verRows = await conn.unsafe(`SELECT value FROM config WHERE key = 'version'`);
|
|
priorVersion = (verRows[0] as any)?.value ?? null;
|
|
|
|
// Simulate an operator who dropped the budget_* tables for any reason
|
|
// (cleanup, migration from an older gbrain, etc).
|
|
await conn.unsafe(`DROP TABLE IF EXISTS public.budget_ledger CASCADE`);
|
|
await conn.unsafe(`DROP TABLE IF EXISTS public.budget_reservations CASCADE`);
|
|
|
|
// Roll the version back to 23 so v24 re-runs on the next initSchema.
|
|
// UPSERT so this works whether the key exists or not.
|
|
await conn.unsafe(`
|
|
INSERT INTO config (key, value) VALUES ('version', '23')
|
|
ON CONFLICT (key) DO UPDATE SET value = '23'
|
|
`);
|
|
|
|
// Re-trigger initSchema via the CLI. With the guard, this should
|
|
// apply v24 cleanly and advance version to 24. Without the guard,
|
|
// this would error out with 42P01 and leave version at 23.
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 30_000,
|
|
});
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
const stderr = new TextDecoder().decode(result.stderr);
|
|
|
|
// Must succeed — no 42P01, no transaction rollback.
|
|
expect(result.exitCode).toBe(0);
|
|
expect(stderr + stdout).not.toMatch(/42P01|does not exist.*budget/i);
|
|
|
|
// Version must have advanced PAST 24. Since v0.18.1, v25-v29 (v0.19.0
|
|
// + v0.21.0 Cathedral II) and v30 (OAuth) have shipped. init runs every
|
|
// pending migration, so after rolling back to 23 the version advances
|
|
// to LATEST_VERSION. The test's intent is to prove v24 didn't crash on
|
|
// missing budget_* tables — assert version >= 24.
|
|
const afterRows = await conn.unsafe(`SELECT value FROM config WHERE key = 'version'`);
|
|
const finalVersion = parseInt((afterRows[0] as any).value, 10);
|
|
expect(finalVersion).toBeGreaterThanOrEqual(24);
|
|
|
|
// The tables stayed dropped (v12 didn't re-run because current=23 > 12
|
|
// was already true before this test ran). That's intentional — we're
|
|
// proving v24 doesn't require those tables to exist.
|
|
const tblRows = await conn.unsafe(`
|
|
SELECT tablename FROM pg_tables
|
|
WHERE schemaname = 'public'
|
|
AND tablename IN ('budget_ledger', 'budget_reservations')
|
|
`);
|
|
expect(tblRows.length).toBe(0);
|
|
} finally {
|
|
// Restore: recreate the budget_* tables (minimal schema — just enough
|
|
// to keep the rest of the test suite happy) and reset version.
|
|
// Mirror migration v12's CREATE TABLE IF NOT EXISTS exactly so any
|
|
// downstream test that touches these tables sees the original shape.
|
|
await conn.unsafe(`
|
|
CREATE TABLE IF NOT EXISTS budget_ledger (
|
|
scope TEXT NOT NULL,
|
|
resolver_id TEXT NOT NULL,
|
|
local_date DATE NOT NULL,
|
|
reserved_usd NUMERIC(12,4) NOT NULL DEFAULT 0,
|
|
committed_usd NUMERIC(12,4) NOT NULL DEFAULT 0,
|
|
cap_usd NUMERIC(12,4),
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
PRIMARY KEY (scope, resolver_id, local_date)
|
|
)
|
|
`);
|
|
await conn.unsafe(`
|
|
CREATE TABLE IF NOT EXISTS budget_reservations (
|
|
reservation_id TEXT PRIMARY KEY,
|
|
scope TEXT NOT NULL,
|
|
resolver_id TEXT NOT NULL,
|
|
local_date DATE NOT NULL,
|
|
estimate_usd NUMERIC(12,4) NOT NULL,
|
|
reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
status TEXT NOT NULL DEFAULT 'held'
|
|
)
|
|
`);
|
|
// Enable RLS on the recreated tables so the "every public table has
|
|
// RLS" assertion earlier in this block stays green if re-run.
|
|
await conn.unsafe(`ALTER TABLE budget_ledger ENABLE ROW LEVEL SECURITY`);
|
|
await conn.unsafe(`ALTER TABLE budget_reservations ENABLE ROW LEVEL SECURITY`);
|
|
// Restore version so we don't leave the DB at a weird state for
|
|
// subsequent test blocks.
|
|
if (priorVersion !== null) {
|
|
await conn.unsafe(
|
|
`UPDATE config SET value = $1 WHERE key = 'version'`,
|
|
[priorVersion],
|
|
);
|
|
}
|
|
}
|
|
}, 60_000);
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Doctor Command
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Doctor Command', () => {
|
|
// Scope GBRAIN_HOME to a hermetic tmpdir so `gbrain doctor` doesn't read
|
|
// the developer's local ~/.gbrain/migrations/completed.jsonl. Stale partial
|
|
// entries from in-flight workspaces (e.g. v0.31.x santiago) would make the
|
|
// minions_migration check fail and exit 1, masking real DB-health failures.
|
|
let gbrainHome: string;
|
|
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
await importFixtures();
|
|
// Isolate GBRAIN_HOME to a per-block tempdir so the developer's
|
|
// ~/.gbrain/migrations/completed.jsonl ledger doesn't leak in. Without
|
|
// this, doctor reads the dev machine state — partial v0.21/v0.22.4/v0.28.0
|
|
// migration entries from in-flight workspaces — and surfaces them as the
|
|
// 'minions_migration' [FAIL] check, exiting with code 1.
|
|
gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-doctor-e2e-'));
|
|
}, 30_000);
|
|
afterAll(async () => {
|
|
await teardownDB();
|
|
if (gbrainHome) rmSync(gbrainHome, { recursive: true, force: true });
|
|
});
|
|
|
|
const cliCwd = join(import.meta.dir, '../..');
|
|
const cliEnv = () => ({
|
|
...process.env,
|
|
DATABASE_URL: process.env.DATABASE_URL!,
|
|
GBRAIN_DATABASE_URL: process.env.DATABASE_URL!,
|
|
GBRAIN_HOME: gbrainHome,
|
|
});
|
|
|
|
test('gbrain doctor exits 0 on healthy DB', () => {
|
|
// Init first so config exists for CLI
|
|
Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 15_000,
|
|
});
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'doctor'],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 15_000,
|
|
});
|
|
if (result.exitCode !== 0) {
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
const stderr = new TextDecoder().decode(result.stderr);
|
|
console.error('doctor stdout:', stdout.slice(-2000));
|
|
console.error('doctor stderr:', stderr.slice(-1000));
|
|
}
|
|
expect(result.exitCode).toBe(0);
|
|
}, 60_000);
|
|
|
|
test('gbrain doctor --json produces valid JSON', () => {
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'doctor', '--json'],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 15_000,
|
|
});
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
const parsed = JSON.parse(stdout);
|
|
expect(parsed.status).toBeDefined();
|
|
expect(Array.isArray(parsed.checks)).toBe(true);
|
|
expect(parsed.checks.length).toBeGreaterThan(0);
|
|
for (const check of parsed.checks) {
|
|
expect(['ok', 'warn', 'fail']).toContain(check.status);
|
|
expect(typeof check.name).toBe('string');
|
|
expect(typeof check.message).toBe('string');
|
|
}
|
|
}, 30_000);
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Parallel Import
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Parallel Import', () => {
|
|
afterAll(teardownDB);
|
|
|
|
const cliCwd = join(import.meta.dir, '../..');
|
|
const cliEnv = () => ({ ...process.env, DATABASE_URL: process.env.DATABASE_URL!, GBRAIN_DATABASE_URL: process.env.DATABASE_URL! });
|
|
|
|
function initCli() {
|
|
Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
|
|
cwd: cliCwd, env: cliEnv(), timeout: 15_000,
|
|
});
|
|
}
|
|
|
|
// Store sequential baseline for comparison
|
|
let seqPageCount: number;
|
|
let seqChunkCount: number;
|
|
let seqPageSlugs: string[];
|
|
|
|
test('sequential baseline: import all fixtures', async () => {
|
|
await setupDB();
|
|
initCli();
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'import', '--no-embed', FIXTURES_PATH],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 30_000,
|
|
});
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const stats = await callOp('get_stats') as any;
|
|
seqPageCount = stats.page_count;
|
|
seqChunkCount = stats.chunk_count;
|
|
|
|
const pages = await callOp('list_pages', { limit: 200 }) as any[];
|
|
seqPageSlugs = pages.map((p: any) => p.slug).sort();
|
|
|
|
expect(seqPageCount).toBeGreaterThan(0);
|
|
expect(seqChunkCount).toBeGreaterThan(0);
|
|
}, 60_000);
|
|
|
|
test('parallel import with --workers 2 matches sequential page count', async () => {
|
|
await setupDB();
|
|
initCli();
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'import', '--no-embed', '--workers', '2', FIXTURES_PATH],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 30_000,
|
|
});
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const stats = await callOp('get_stats') as any;
|
|
expect(stats.page_count).toBe(seqPageCount);
|
|
}, 60_000);
|
|
|
|
test('parallel import has same chunk count (no duplicates)', async () => {
|
|
const stats = await callOp('get_stats') as any;
|
|
expect(stats.chunk_count).toBe(seqChunkCount);
|
|
});
|
|
|
|
test('parallel import has same page slugs', async () => {
|
|
const pages = await callOp('list_pages', { limit: 200 }) as any[];
|
|
const parSlugs = pages.map((p: any) => p.slug).sort();
|
|
expect(parSlugs).toEqual(seqPageSlugs);
|
|
});
|
|
|
|
test('no duplicate pages from concurrent writes', async () => {
|
|
const conn = getConn();
|
|
const dupes = await conn.unsafe(`
|
|
SELECT slug, count(*) as n FROM pages GROUP BY slug HAVING count(*) > 1
|
|
`);
|
|
expect(dupes.length).toBe(0);
|
|
});
|
|
|
|
test('no duplicate chunks from concurrent writes', async () => {
|
|
const conn = getConn();
|
|
const dupes = await conn.unsafe(`
|
|
SELECT page_id, chunk_index, count(*) as n
|
|
FROM content_chunks
|
|
GROUP BY page_id, chunk_index
|
|
HAVING count(*) > 1
|
|
`);
|
|
expect(dupes.length).toBe(0);
|
|
});
|
|
|
|
test('parallel import with --workers 4 also works', async () => {
|
|
await setupDB();
|
|
initCli();
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'import', '--no-embed', '--workers', '4', FIXTURES_PATH],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 30_000,
|
|
});
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const stats = await callOp('get_stats') as any;
|
|
expect(stats.page_count).toBe(seqPageCount);
|
|
expect(stats.chunk_count).toBe(seqChunkCount);
|
|
}, 60_000);
|
|
|
|
test('re-import with workers is idempotent', async () => {
|
|
// Import again on top of existing data
|
|
const result = Bun.spawnSync({
|
|
cmd: ['bun', 'run', 'src/cli.ts', 'import', '--no-embed', '--workers', '2', FIXTURES_PATH],
|
|
cwd: cliCwd,
|
|
env: cliEnv(),
|
|
timeout: 30_000,
|
|
});
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const stats = await callOp('get_stats') as any;
|
|
expect(stats.page_count).toBe(seqPageCount);
|
|
expect(stats.chunk_count).toBe(seqChunkCount);
|
|
}, 60_000);
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────
|
|
// Performance Baselines
|
|
// ─────────────────────────────────────────────────────────────────
|
|
|
|
describeE2E('E2E: Performance Baselines', () => {
|
|
beforeAll(async () => {
|
|
await setupDB();
|
|
}, 30_000);
|
|
afterAll(teardownDB);
|
|
|
|
test('import + search + link performance', async () => {
|
|
const [_, importMs] = await time(importFixtures);
|
|
|
|
const searchTimes: number[] = [];
|
|
for (const q of ['NovaMind', 'hybrid search', 'Stanford', 'investor', 'compiled truth']) {
|
|
const [__, ms] = await time(() => callOp('search', { query: q }));
|
|
searchTimes.push(ms);
|
|
}
|
|
|
|
const [___, linkMs] = await time(async () => {
|
|
await callOp('add_link', { from: 'people/sarah-chen', to: 'companies/novamind' });
|
|
await callOp('get_backlinks', { slug: 'companies/novamind' });
|
|
});
|
|
|
|
searchTimes.sort((a, b) => a - b);
|
|
const p50 = searchTimes[Math.floor(searchTimes.length * 0.5)];
|
|
const p99 = searchTimes[searchTimes.length - 1];
|
|
|
|
console.log('\n Performance Baselines:');
|
|
console.log(` Import 13 fixtures: ${importMs.toFixed(0)}ms`);
|
|
console.log(` Search p50: ${p50.toFixed(0)}ms`);
|
|
console.log(` Search p99: ${p99.toFixed(0)}ms`);
|
|
console.log(` Link + backlink: ${linkMs.toFixed(0)}ms`);
|
|
}, 30_000);
|
|
});
|