Files
gbrain/test/pglite-engine.test.ts
T
52f9581966 v0.22.11 feat: storage tiering — db_tracked vs db_only directories (#494)
* feat: storage tiering — git-tracked vs supabase-only directories

Brain repos scaling to 200K+ files. Bulk data (tweets, articles, transcripts)
bloats git repos and slows operations. New storage config in gbrain.yml lets
users declare git-tracked and supabase-only directories.

Changes:
- New config: storage.git_tracked and storage.supabase_only in gbrain.yml
- gbrain sync auto-manages .gitignore for supabase-only paths
- gbrain export --restore-only restores missing supabase-only files from DB
- New gbrain storage status command shows tier breakdown
- Config validation warns on conflicts
- 8 tests passing, full docs at docs/storage-tiering.md

Backward compatible — systems without gbrain.yml work unchanged.

* feat: add getDefaultSourcePath() typed accessor (step 1/15)

Single source of truth for "what brain repo are we operating against?"
Replaces ad-hoc raw SQL in storage.ts:38 (Issue #3 of eng review). Used by
both gbrain storage status and gbrain export --restore-only.

Returns null on miss, throws on DB error. Composes with the existing
resolveSourceId chain so it honors --source flag / GBRAIN_SOURCE env /
.gbrain-source dotfile / longest-prefix CWD match / brain-level default.

4 new test cases covering happy path, missing local_path, DB error
propagation, and CWD-prefix resolution priority.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: replace gray-matter with dedicated YAML parser (step 2/15)

The original storage-config.ts called gray-matter on a delimiter-less YAML
file. Gray-matter only parses YAML inside `---` frontmatter blocks; without
delimiters, it returns `{data: {}}`. Result: loadStorageConfig() always
returned null, the entire feature was a silent no-op for every user.

Original eng review's P0 confidence-9 finding (Issue #1).

Replaces gray-matter with a small dedicated parser for the gbrain.yml shape
(top-level `storage:` section, two array-valued nested keys). Yaml-lite was
considered first, but its flat key:value design doesn't handle nested
arrays. The dedicated parser is ~50 lines and trades expressiveness for
zero-dep, predictable parsing of a file format we control.

Adds the Issue #1B sanity warning (locked B): when gbrain.yml exists but
has no storage section (or empty arrays), warn once-per-process so the
user sees their config didn't take. The single test that would have caught
the original P0 — write a real gbrain.yml, call loadStorageConfig, assert
non-null — now exists.

Also tightens loadStorageConfig per D36: distinguishes "absent" (silent
null) from "unreadable" (throws). The previous code silently swallowed
read errors, hiding broken installs.

8 new test cases: real-disk happy path, comments + blank lines, quoted
values, missing storage section warning, empty section warning,
once-per-process warning suppression, unreadable file behavior, and the
existing helper tests (validation, tier matching, edge cases) all still
pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: rename storage keys to db_tracked/db_only (step 3/15)

The vendor-specific names "supabase_only" and "git_tracked" hardcoded a
backend (Supabase) into the config schema. gbrain ships two engines —
PGLite and Postgres-via-Supabase. The canonical distinction is "lives in
the brain DB only" vs "lives in the brain DB and on disk under git." Both
work on either engine.

Renamed throughout (Issue #4 of eng review):
  git_tracked    → db_tracked
  supabase_only  → db_only
  isGitTracked() → isDbTracked()
  isSupabaseOnly() → isDbOnly()
  StorageTier 'git_tracked'/'supabase_only' → 'db_tracked'/'db_only'

Backward compatibility (D3 lock):
  loadStorageConfig accepts both shapes. Loader resolution order per the
  eng-review pass-2 finding: parse YAML → if canonical keys present use
  them, else if deprecated keys present map to canonical AND emit
  once-per-process deprecation warning → THEN run validation.
  Validation always sees the canonical shape so error messages reference
  db_tracked/db_only regardless of which keys the user wrote.

  The deprecation warning suggests `gbrain doctor --fix` for an automated
  rename (D72 — fix path lands in step 7).

  When both shapes coexist in one file, canonical wins and a stronger
  warning fires ("deprecated keys ignored — remove them").

Aliases isGitTracked/isSupabaseOnly kept for now to avoid churning the
sync.ts / export.ts / storage.ts call sites in this commit; they'll be
removed in a follow-up step. Storage.ts's tier-bucket initializers and
output strings updated. ASCII output replaces unicode box-drawing per D10.

gbrain.yml example file updated to canonical keys with explanatory
comments.

2 new test cases: deprecated-key fallback (asserts both shapes load
correctly with warning), canonical-wins-over-deprecated (asserts the
"both shapes coexist" path).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: add slugPrefix to PageFilters with engine-side filter (step 4/15)

Issue #13 of the eng review: storage.ts and export.ts loaded every page
in the brain (limit: 1_000_000) to check tier membership. On the 200K-page
brains this feature targets, that's the wall-clock and memory landmine
the feature exists to fix.

Adds an optional `slugPrefix` field to PageFilters. Both engines implement
it as `WHERE slug LIKE prefix || '%' ESCAPE '\'`, with literal escaping of
LIKE metacharacters (%, _, \) so user-supplied prefixes like `media/x/`
are treated as exact string prefixes.

Performance: the (source_id, slug) UNIQUE constraint on the pages table
gives both engines a btree index that supports LIKE-prefix range scans.
An EXPLAIN on Postgres confirms the index range scan rather than a seq
scan. PGLite has the same index shape via pglite-schema.ts.

Consumers updated:
  - export.ts: --slug-prefix flag now goes engine-side (no in-memory
    .filter(...)). The --restore-only path queries each db_only directory
    with slugPrefix in a loop instead of one full-table scan, with seen-set
    deduplication and disk-existence check inline.
  - storage.ts: keeps the full-scan path because storage-status needs the
    "unspecified" bucket count, which can't be computed without enumerating
    every page. Comment notes that step 5 (single-walk filesystem scan)
    will reduce per-page disk syscall cost.

2 new test cases on PGLiteEngine: slugPrefix happy path (3 tier dirs,
asserts only matching slugs return) and metacharacter escape regression
(asserts safe/ doesn't match unrelated slugs).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* perf: single-walk filesystem scan via walkBrainRepo() (step 5/15)

Issue #14 of the eng review: storage.ts called existsSync + statSync
per-page in a synchronous loop. On a 200K-page brain that's 400K syscalls
serialized. Wall-clock landmine.

Adds src/core/disk-walk.ts with walkBrainRepo(repoPath) — one recursive
readdirSync walk, builds a Map<slug, {size, mtimeMs}>. Storage.ts looks
up each DB page in the map (O(1)) instead of stat-checking on demand.
Slug derivation matches the pages-table convention: people/alice.md on
disk becomes people/alice as the map key.

Skipped during walk:
  - dot-directories (.git, .gbrain, .vscode, etc) — not part of the brain
    namespace
  - node_modules — guards against accidentally walking into imported repos
  - non-.md files (sidecar JSON, binaries) — tracked by the brain through
    the files table, not by slug

Reusable: future commands (gbrain doctor's storage_tiering check, the
optional autopilot tier-fix path) get the same walk for free.

9 new test cases: empty dir, nonexistent dir, top-level files, nested
dirs, dot-dir skipping, node_modules skipping, non-.md filtering, size
capture, mtimeMs capture.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: path-segment matching for tier directories (step 6/15)

Issue #5 + D6 of the eng review: tier matching used slug.startsWith(dir),
which falsely matches 'media/xerox/foo' against 'media/x' if a user wrote
the directory without a trailing slash.

The new matcher requires the configured directory to end with `/` and
treats it as a canonical path-segment ancestor:

  media/x/   matches  media/x/tweet-1       ✓
  media/x/   doesn't  media/xerox/foo       ✗
  media/x    refused  media/x/tweet-1       (matcher requires trailing /)

Non-canonical input (no trailing slash) is refused outright. Step 7's
auto-normalizing validator converts user-written 'media/x' → 'media/x/'
on load, so the matcher never sees non-canonical input from real configs.
The behavior tested here is the strict matcher's contract.

Regression test pins the media/xerox collision case explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: auto-normalize trailing-slash, throw on tier overlap (step 7/15)

D7+D8 of the eng review: validation was warnings-only. Users miss warnings.
Now:

  - Cosmetic: missing trailing slash auto-corrected, one-time info note
    showing what changed ("normalized 2 storage paths: 'people' →
    'people/', 'media/x' → 'media/x/'"). Once-per-process to keep noise low.

  - Semantic: same directory in both tiers throws StorageConfigError.
    Ambiguous routing — does media/ win as db_tracked or db_only? — is a
    real bug the user must fix. Caller propagates to the CLI for a clean
    exit-1 with actionable message.

loadStorageConfig now applies normalize+validate after merging deprecated
keys, so the path-segment matcher (step 6) only ever sees canonical
trailing-slash directories.

The pure validateStorageConfig kept for callers who want the warnings list
without the auto-fix side effects (gbrain doctor's reporting path).

2 new test cases: auto-normalize round-trip with warning text assertion,
overlap throws StorageConfigError.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: wire manageGitignore into runSync, only on success (step 8/15)

Issue #2 of the eng review: manageGitignore was defined and never
invoked. Docs claimed "auto-managed by gbrain" — false. Users hit a
.gitignore that never updated and committed db_only directories anyway.

Wire-up: runSync now calls manageGitignore after each successful
performSync return, in both watch and one-shot modes.

Eng review pass-2 finding #1: skip on dry_run AND blocked_by_failures
status. A sync that aborted partway has stale state; mutating .gitignore
based on a partially-loaded config invites drift. Failure-skip test
added (uses .gitignore-as-a-directory to simulate write failure;
asserts warning fired and disk wasn't corrupted).

Hardened manageGitignore itself with three additional behaviors:

  - GBRAIN_NO_GITIGNORE=1 escape hatch (D23) for shared-repo setups
    where a maintainer wants gbrain to leave .gitignore alone.

  - Submodule detection (D49). When repoPath/.git is a regular file
    (gitdir: ... pointer), the repo is a git submodule. Submodule
    .gitignore changes don't survive parent submodule updates, so we
    skip with an actionable warning ("add db_only directories to your
    parent repo's .gitignore manually").

  - Graceful failure (D9). Read errors, write errors, and
    StorageConfigError (overlap from step 7) all log a warning and
    return — sync's primary job (moving data) shouldn't die because of
    a side-effect on .gitignore.

manageGitignore is now exported (previously private) so the
storage-sync test file can hit it directly without spinning up sync.

9 new test cases: no-op without gbrain.yml, no-op with empty db_only,
happy-path append, idempotency (run twice, single entry), preservation
of user-written rules, GBRAIN_NO_GITIGNORE skip, submodule skip,
.git-directory normal path, write-failure graceful warning.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: D5 resolution chain for --restore-only and storage status (step 9/15)

D5 of the eng review: gbrain export --restore-only without --repo
silently fell through to the regular export path, dumping every page in
the database to the wrong directory. Hard regression risk.

Now exits 1 with an actionable message when --restore-only has no
--repo AND no configured default source. Resolution order:
  1. Explicit --repo flag
  2. Typed sources.getDefault() (reuses step 1's accessor)
  3. Hard error — never fall through to cwd

storage.ts:38 also bypassed BrainEngine with raw SQL and a bare
try/catch (Issue #3 + Issue #9). Replaced with the same typed
getDefaultSourcePath() — single source of truth, errors propagate
cleanly to the user, no silent cwd fallback.

Regular export (no --restore-only) keeps its current behavior per D26:
exports include everything, --repo is optional.

4 new test cases on PGLite in-memory:
  - hard-errors with no --repo + no default
  - explicit --repo wins
  - falls back to sources default local_path
  - non-restore export does not require --repo

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: split storage.ts into pure data + JSON + human formatters (step 10/15)

Issue #10 of the eng review: getStorageStatus and runStorageStatus mixed
data gathering, JSON serialization, and human-readable output in one
function. Hard to test, hard to reuse, mismatched the orphans.ts pattern
that CLAUDE.md cites as the precedent.

Now three pure functions + a thin dispatcher:

  getStorageStatus(engine, repoPath) — async, returns StorageStatusResult.
    Side effects: engine.listPages + one walkBrainRepo (Issue #14).
    Exported so MCP exposure (D14) and gbrain doctor (D13) can consume the
    same data without re-running the loop.

  formatStorageStatusJson(result) — pure, returns indented JSON. Stable
    contract on the StorageStatusResult shape, suitable for orchestrators.

  formatStorageStatusHuman(result) — pure, returns ASCII text (D10 — no
    unicode box-drawing). Composable into other commands later.

  runStorageStatus(engine, args) — thin dispatcher: parses --repo /
    --json, calls getStorageStatus, picks a formatter, prints.

8 new test cases on the formatters: JSON parse round-trip, null-config
fallback, missing-files capped at 10 with rollup, ASCII-only assertion
(D10 regression guard), warnings inline, configuration listing, disk-
usage block omitted when zero bytes.

The StorageStatusResult interface is now exported as a public type, so
gbrain doctor's storage_tiering check can build its own findings from
the same shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* types: distinct PageCountsByTier and DiskUsageByTier (step 11/15)

Issue #11 of the eng review: pagesByTier (page counts) and
diskUsageByTier (byte totals) shared the same structural type
(Record<StorageTier, number>). Both are tier-keyed numeric maps but
carry semantically different units. A future bug that swaps them at a
call site (e.g., displaying disk bytes where the count belongs) wouldn't
trip the compiler.

Replaced with distinct nominal types via a brand field. Structurally
identical at runtime (no overhead) but compile-time disjoint —
TypeScript catches accidental cross-assignment.

  PageCountsByTier   { db_tracked, db_only, unspecified } : numbers (count)
  DiskUsageByTier    { db_tracked, db_only, unspecified } : numbers (bytes)

Both initialized in getStorageStatus, both threaded into
StorageStatusResult, both consumed by formatStorageStatusHuman /
formatStorageStatusJson without further changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: PGLite soft-warn + full lifecycle test (step 12/15)

D4: storage tiering on PGLite is a partial feature. The "DB" the pages
live in IS the local file gbrain uses for everything else, so "db_only"
has no real offload effect. The .gitignore management still helps
(keeps bulk content out of git history), so we warn and proceed —
not refuse.

Two warning sites (once-per-process each via module-local flags):
  - storage status: warns at runStorageStatus entry
  - sync: warns inside manageGitignore when engineKind='pglite' and
    config has db_only entries

Both phrased actionably ("To get full tiering, migrate to Postgres
with `gbrain migrate --to supabase`").

manageGitignore signature now takes an optional `engineKind` param.
runSync passes engine.kind. Stand-alone callers (tests, future
gbrain doctor --fix path) can omit it.

New test: test/storage-pglite.test.ts — D8 + D4 lifecycle. 6 cases:
engine.kind assertion, getStorageStatus loading gbrain.yml + reporting
tier counts, manageGitignore PGLite-warn (once per process), Postgres
no-warn, slugPrefix on PGLite, end-to-end (config + putPage + status
+ gitignore).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: add trailing-newline CI guard (step 14/15)

Issue #7 of the eng review: all four new files in the original
storage-tiering branch lacked POSIX trailing newlines. Linters complain,
git diffs phantom-flag every future edit. We've been adding newlines as
each file landed; this commit catches the regression class.

scripts/check-trailing-newline.sh:
  - sibling to check-jsonb-pattern.sh / check-progress-to-stdout.sh per
    CLAUDE.md's CI guard pattern
  - portable to bash 3.2 (macOS default; no mapfile, no associative arrays)
  - covers src/**, test/**, gbrain.yml, top-level *.md
  - reports each missing file by path and exits 1

Wired into `bun run test` between progress-to-stdout and typecheck.

Also fixed docs/storage-tiering.md (pre-existing missing newline from
the original branch — caught by the new guard on first run).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: v0.23.0 — VERSION, CHANGELOG, README, CLAUDE.md, storage-tiering.md (step 15/15)

VERSION → 0.23.0 (minor bump for new feature surface).

CHANGELOG entry in Garry voice with the canonical format:
  - Two-line bold headline ("Storage tiering, finally working...")
  - Lead paragraph naming what was broken before and what users get now
  - "Numbers that matter" before/after table for the 6 things that
    actually changed
  - "What this means for your brain" closer
  - "To take advantage of v0.23.0" self-repair block (per CLAUDE.md
    convention) — 6 numbered steps users can follow
  - Itemized changes split into critical fixes / new+renamed surface /
    architecture cleanup / tests + CI guards

CLAUDE.md "Key files" gains four new entries: storage-config.ts,
disk-walk.ts, the v0.23.0 storage.ts shape, and gbrain.yml itself.

README.md gains a new "Storage tiering" section between Skillify and
Getting Data In with the canonical example + commands + link to the
full guide.

docs/storage-tiering.md rewritten end-to-end with canonical key names
(db_tracked / db_only), v0.23.0 hardening details (idempotency,
submodule detection, GBRAIN_NO_GITIGNORE, dry-run gating), the
resolution chain for --restore-only, the auto-normalize +
throw-on-overlap validator, and the PGLite engine note.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test: e2e Postgres lifecycle for storage tiering (step 16/16)

Per the v0.23.0 plan: full lifecycle E2E against real Postgres.

  - engine.kind === 'postgres' assertion
  - Full lifecycle: write 4 pages (1 db_tracked, 2 db_only, 1 unspecified)
    → getStorageStatus reports correct tier counts → human formatter
    renders → manageGitignore writes managed block → idempotency check
    → getDefaultSourcePath() resolves the configured local_path.
  - Container restart simulation: 2 db_only pages in DB, files missing
    on disk → status.missingFiles.length === 2 → slugPrefix engine
    filter on Postgres returns exactly the tier slugs.
  - slugPrefix index-based range scan regression: 50 media/x/* + 50
    people/p-* pages → slugPrefix='media/x/' returns exactly 50.
  - getDefaultSourcePath returns null when default source has no
    local_path (the hard-error path that replaces the original silent
    cwd fallback).
  - manageGitignore on Postgres engine does NOT emit the PGLite
    soft-warn (cross-engine assertion).

Skips gracefully when DATABASE_URL is unset, per CLAUDE.md E2E pattern.
Run via: DATABASE_URL=... bun test test/e2e/storage-tiering.test.ts

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: rebump version 0.23.0 → 0.22.9

Reverts the minor bump back to a patch-style version on the v0.22 line.
Storage tiering ships within the v0.22.x train alongside the recent
fix waves. Updates VERSION, package.json, CHANGELOG header + body refs,
CLAUDE.md Key files annotations, README.md section heading, and the
docs/storage-tiering.md backward-compat note.

* chore: bump version 0.22.9 → 0.22.11

Sibling workspaces claimed v0.22.10 in the queue. This branch advances
to v0.22.11 to keep the version monotonic on master.

Updates VERSION, package.json, CHANGELOG header + body refs, CLAUDE.md
Key files annotations, README.md section heading, and the
docs/storage-tiering.md backward-compat note.

* fix: address Codex pre-landing review findings (4 fixes)

Codex found 4 real issues during pre-landing review of v0.22.11 diff:

[P0] export --restore-only fell through to full export when
storageConfig was null (no gbrain.yml present). On older or
misconfigured brains, the recovery command would silently dump the
entire database. src/commands/export.ts now refuses with an actionable
error before any page query fires — matches the D5 lock spirit
("never silently fall through").

[P1] manageGitignore wire-up only fired when --repo was passed
explicitly. performSync resolves the repo from sync.repo_path or
sources.local_path, so the common `gbrain sync` path (after
setup, no flag) never updated .gitignore. src/commands/sync.ts now
uses the same source-resolver chain as the rest of /ship: opts.repoPath
→ getDefaultSourcePath → null. Fires in both watch and one-shot modes.

[P2] getDefaultSourcePath only consulted sources.local_path, missing
the legacy global sync.repo_path config key that pre-v0.18 brains use.
Added a fallback to engine.getConfig('sync.repo_path') when the
sources row has NULL local_path. Pre-v0.18 brains now work without
forcing a `gbrain sources add . --path .` migration.

[P2] sync --all multi-source loop never called manageGitignore even
though src.local_path was already known. Each source now gets its own
gitignore update on successful sync.

Tests:
  - test/storage-export.test.ts: replaced the old "falls through to
    full export" test with one that asserts the new refusal path
    (storage-tiering config required for --restore-only).
  - test/source-resolver.test.ts: added a fallback test exercising the
    legacy sync.repo_path code path for pre-v0.18 brains.
  - All 78 storage-tiering tests still pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: regenerate llms.txt + llms-full.txt for v0.22.11

Per CLAUDE.md: "Run `bun run build:llms` after adding a new doc."
The README's new Storage tiering section + the rewritten
docs/storage-tiering.md changed the inlined bundle. test/build-llms.test.ts
catches the drift and was failing on master pre-regen.

* fix: typecheck error in disk-walk.ts (CI #73350475897)

tsc --noEmit failed in CI because ReturnType<typeof readdirSync> with
withFileTypes:true picks an overload union that includes
Dirent<Buffer<ArrayBufferLike>>. Strict tsc treats entry.name as Buffer,
so .startsWith / .endsWith / string comparisons all blew up.

Annotate the variable as Dirent[] (string-based) and cast through unknown,
matching the pattern sync.ts already uses for its own filesystem walk.
Same runtime behavior; clean typecheck.

Tests still 9/9.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EOF

---------

Co-authored-by: root <root@localhost>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 22:21:07 -07:00

1080 lines
46 KiB
TypeScript

/**
* PGLite Engine Tests — validates all 37 BrainEngine methods against PGLite (in-memory).
*
* No Docker, no DATABASE_URL, no external dependencies. Runs instantly in CI.
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import type { PageInput, ChunkInput } from '../src/core/types.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({}); // in-memory
await engine.initSchema();
});
afterAll(async () => {
await engine.disconnect();
});
// Helper to reset data between test groups
async function truncateAll() {
const tables = [
'content_chunks', 'links', 'tags', 'raw_data',
'timeline_entries', 'page_versions', 'ingest_log', 'pages',
];
for (const t of tables) {
await (engine as any).db.exec(`DELETE FROM ${t}`);
}
}
const testPage: PageInput = {
type: 'concept',
title: 'Test Page',
compiled_truth: 'This is a test page about NovaMind AI agents.',
timeline: '2024-01-15: Founded NovaMind',
};
// ─────────────────────────────────────────────────────────────────
// Pages CRUD
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: Pages', () => {
beforeEach(truncateAll);
test('putPage + getPage round trip', async () => {
const page = await engine.putPage('test/hello', testPage);
expect(page.slug).toBe('test/hello');
expect(page.title).toBe('Test Page');
expect(page.type).toBe('concept');
expect(page.compiled_truth).toContain('NovaMind');
const fetched = await engine.getPage('test/hello');
expect(fetched).not.toBeNull();
expect(fetched!.title).toBe('Test Page');
expect(fetched!.content_hash).toBeTruthy();
});
test('putPage upserts on conflict', async () => {
await engine.putPage('test/upsert', testPage);
const updated = await engine.putPage('test/upsert', {
...testPage,
title: 'Updated Title',
});
expect(updated.title).toBe('Updated Title');
const all = await engine.listPages();
const matches = all.filter(p => p.slug === 'test/upsert');
expect(matches.length).toBe(1);
});
test('getPage returns null for missing slug', async () => {
const result = await engine.getPage('nonexistent/slug');
expect(result).toBeNull();
});
test('deletePage removes page', async () => {
await engine.putPage('test/delete-me', testPage);
await engine.deletePage('test/delete-me');
const result = await engine.getPage('test/delete-me');
expect(result).toBeNull();
});
test('listPages with type filter', async () => {
await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' });
await engine.putPage('concepts/rag', { ...testPage, type: 'concept', title: 'RAG' });
const people = await engine.listPages({ type: 'person' });
expect(people.length).toBe(1);
expect(people[0].title).toBe('Alice');
});
test('listPages with tag filter', async () => {
await engine.putPage('test/tagged', testPage);
await engine.addTag('test/tagged', 'special');
const tagged = await engine.listPages({ tag: 'special' });
expect(tagged.length).toBe(1);
expect(tagged[0].slug).toBe('test/tagged');
});
test('listPages with slugPrefix filter (Issue #13)', async () => {
await truncateAll();
await engine.putPage('media/x/tweet-1', { ...testPage, type: 'concept' });
await engine.putPage('media/x/tweet-2', { ...testPage, type: 'concept' });
await engine.putPage('media/articles/post-1', { ...testPage, type: 'concept' });
await engine.putPage('people/alice', { ...testPage, type: 'person' });
const xOnly = await engine.listPages({ slugPrefix: 'media/x/', limit: 100 });
expect(xOnly.map((p) => p.slug).sort()).toEqual(['media/x/tweet-1', 'media/x/tweet-2']);
const allMedia = await engine.listPages({ slugPrefix: 'media/', limit: 100 });
expect(allMedia.length).toBe(3);
// Path-segment risk: 'media/x' (no trailing /) would also match 'media/xerox'.
// The matcher in storage-config.ts is responsible for trailing-/ semantics
// (step 6); the engine treats slugPrefix as a literal string prefix.
expect((await engine.listPages({ slugPrefix: 'media/x', limit: 100 })).length).toBe(2);
});
test('listPages slugPrefix escapes LIKE metacharacters', async () => {
await truncateAll();
await engine.putPage('safe/foo', { ...testPage, type: 'concept' });
// A user prefix containing % or _ would otherwise match unintended slugs
// if not escaped. We can't easily insert a slug with % in it (most slugs
// are url-safe), but we can confirm the escape logic doesn't break the
// happy path.
const result = await engine.listPages({ slugPrefix: 'safe/', limit: 10 });
expect(result.length).toBe(1);
expect(result[0].slug).toBe('safe/foo');
});
test('resolveSlugs exact match', async () => {
await engine.putPage('test/exact', testPage);
const slugs = await engine.resolveSlugs('test/exact');
expect(slugs).toEqual(['test/exact']);
});
test('resolveSlugs fuzzy match via pg_trgm', async () => {
await engine.putPage('people/sarah-chen', { ...testPage, title: 'Sarah Chen' });
const slugs = await engine.resolveSlugs('sarah');
expect(slugs.length).toBeGreaterThan(0);
expect(slugs).toContain('people/sarah-chen');
});
test('updateSlug renames page', async () => {
await engine.putPage('test/old-name', testPage);
await engine.updateSlug('test/old-name', 'test/new-name');
expect(await engine.getPage('test/old-name')).toBeNull();
expect((await engine.getPage('test/new-name'))?.title).toBe('Test Page');
});
test('validateSlug rejects path traversal', async () => {
expect(() => engine.putPage('../etc/passwd', testPage)).toThrow();
});
test('validateSlug rejects leading slash', async () => {
expect(() => engine.putPage('/absolute/path', testPage)).toThrow();
});
test('validateSlug normalizes to lowercase', async () => {
const page = await engine.putPage('Test/UPPER', testPage);
expect(page.slug).toBe('test/upper');
});
});
// ─────────────────────────────────────────────────────────────────
// Search (tsvector triggers + FTS)
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: Search', () => {
beforeAll(async () => {
await truncateAll();
await engine.putPage('companies/novamind', {
type: 'company', title: 'NovaMind',
compiled_truth: 'NovaMind builds AI agents for enterprise automation.',
});
await engine.upsertChunks('companies/novamind', [
{ chunk_index: 0, chunk_text: 'NovaMind builds AI agents for enterprise', chunk_source: 'compiled_truth' },
]);
await engine.putPage('concepts/rag', {
type: 'concept', title: 'Retrieval-Augmented Generation',
compiled_truth: 'RAG combines retrieval with generation for better answers.',
});
await engine.upsertChunks('concepts/rag', [
{ chunk_index: 0, chunk_text: 'RAG combines retrieval with generation', chunk_source: 'compiled_truth' },
]);
});
test('searchKeyword returns results for matching term', async () => {
const results = await engine.searchKeyword('NovaMind');
expect(results.length).toBeGreaterThan(0);
expect(results[0].slug).toBe('companies/novamind');
});
test('searchKeyword returns empty for non-matching term', async () => {
const results = await engine.searchKeyword('xyznonexistent');
expect(results.length).toBe(0);
});
test('tsvector trigger populates search_vector on insert', async () => {
// Verify the PL/pgSQL trigger fires and content_chunks.search_vector is
// populated from chunk_text. v0.20.0 Cathedral II Layer 3 moved FTS from
// pages.search_vector to content_chunks.search_vector — the chunk-grain
// vector is built from chunk_text (+ optional doc_comment + qualified
// symbol name). 'AI agents' is a phrase inside the chunk_text so it
// stresses the chunk-grain tsvector directly.
const results = await engine.searchKeyword('AI agents');
expect(results.length).toBeGreaterThan(0);
});
test('searchVector returns empty when no embeddings', async () => {
const fakeEmbedding = new Float32Array(1536);
const results = await engine.searchVector(fakeEmbedding);
expect(results.length).toBe(0);
});
});
// ─────────────────────────────────────────────────────────────────
// Chunks
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: Chunks', () => {
beforeEach(truncateAll);
test('upsertChunks + getChunks round trip', async () => {
await engine.putPage('test/chunks', testPage);
await engine.upsertChunks('test/chunks', [
{ chunk_index: 0, chunk_text: 'Chunk zero', chunk_source: 'compiled_truth' },
{ chunk_index: 1, chunk_text: 'Chunk one', chunk_source: 'compiled_truth' },
]);
const chunks = await engine.getChunks('test/chunks');
expect(chunks.length).toBe(2);
expect(chunks[0].chunk_text).toBe('Chunk zero');
expect(chunks[1].chunk_text).toBe('Chunk one');
});
test('upsertChunks removes orphan chunks', async () => {
await engine.putPage('test/orphan', testPage);
await engine.upsertChunks('test/orphan', [
{ chunk_index: 0, chunk_text: 'Keep', chunk_source: 'compiled_truth' },
{ chunk_index: 1, chunk_text: 'Remove', chunk_source: 'compiled_truth' },
]);
// Re-upsert with only index 0
await engine.upsertChunks('test/orphan', [
{ chunk_index: 0, chunk_text: 'Updated', chunk_source: 'compiled_truth' },
]);
const chunks = await engine.getChunks('test/orphan');
expect(chunks.length).toBe(1);
expect(chunks[0].chunk_text).toBe('Updated');
});
test('upsertChunks throws for missing page', async () => {
await expect(
engine.upsertChunks('nonexistent/page', [
{ chunk_index: 0, chunk_text: 'test', chunk_source: 'compiled_truth' },
])
).rejects.toThrow('Page not found');
});
test('deleteChunks removes all chunks for page', async () => {
await engine.putPage('test/delete-chunks', testPage);
await engine.upsertChunks('test/delete-chunks', [
{ chunk_index: 0, chunk_text: 'Gone', chunk_source: 'compiled_truth' },
]);
await engine.deleteChunks('test/delete-chunks');
const chunks = await engine.getChunks('test/delete-chunks');
expect(chunks.length).toBe(0);
});
test('getChunksWithEmbeddings returns embedding data', async () => {
await engine.putPage('test/embed', testPage);
const embedding = new Float32Array(1536).fill(0.1);
await engine.upsertChunks('test/embed', [
{ chunk_index: 0, chunk_text: 'With embedding', chunk_source: 'compiled_truth', embedding },
]);
const chunks = await engine.getChunksWithEmbeddings('test/embed');
expect(chunks.length).toBe(1);
expect(chunks[0].embedding).not.toBeNull();
});
});
// ─────────────────────────────────────────────────────────────────
// Links + Graph
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: Links', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' });
await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'ACME' });
await engine.putPage('companies/beta', { ...testPage, type: 'company', title: 'Beta' });
});
test('addLink + getLinks', async () => {
await engine.addLink('people/alice', 'companies/acme', 'works at', 'employment');
const links = await engine.getLinks('people/alice');
expect(links.length).toBe(1);
expect(links[0].to_slug).toBe('companies/acme');
});
test('getBacklinks', async () => {
await engine.addLink('people/alice', 'companies/acme');
const backlinks = await engine.getBacklinks('companies/acme');
expect(backlinks.length).toBe(1);
expect(backlinks[0].from_slug).toBe('people/alice');
});
test('removeLink', async () => {
await engine.addLink('people/alice', 'companies/acme');
await engine.removeLink('people/alice', 'companies/acme');
const links = await engine.getLinks('people/alice');
expect(links.length).toBe(0);
});
test('traverseGraph with depth', async () => {
await engine.addLink('people/alice', 'companies/acme');
await engine.addLink('companies/acme', 'companies/beta');
const graph = await engine.traverseGraph('people/alice', 2);
expect(graph.length).toBeGreaterThanOrEqual(2);
const slugs = graph.map(n => n.slug);
expect(slugs).toContain('people/alice');
expect(slugs).toContain('companies/acme');
});
});
// ─────────────────────────────────────────────────────────────────
// Tags
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: Tags', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('test/tags', testPage);
});
test('addTag + getTags', async () => {
await engine.addTag('test/tags', 'alpha');
await engine.addTag('test/tags', 'beta');
const tags = await engine.getTags('test/tags');
expect(tags).toEqual(['alpha', 'beta']);
});
test('removeTag', async () => {
await engine.addTag('test/tags', 'remove-me');
await engine.removeTag('test/tags', 'remove-me');
const tags = await engine.getTags('test/tags');
expect(tags).not.toContain('remove-me');
});
test('duplicate tag is idempotent', async () => {
await engine.addTag('test/tags', 'dup');
await engine.addTag('test/tags', 'dup');
const tags = await engine.getTags('test/tags');
expect(tags.filter(t => t === 'dup').length).toBe(1);
});
});
// ─────────────────────────────────────────────────────────────────
// Timeline
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: Timeline', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('test/timeline', testPage);
});
test('addTimelineEntry + getTimeline', async () => {
await engine.addTimelineEntry('test/timeline', {
date: '2024-01-15', summary: 'Founded', detail: 'Company founded',
});
const entries = await engine.getTimeline('test/timeline');
expect(entries.length).toBe(1);
expect(entries[0].summary).toBe('Founded');
});
test('getTimeline with date range', async () => {
await engine.addTimelineEntry('test/timeline', { date: '2024-01-01', summary: 'Jan' });
await engine.addTimelineEntry('test/timeline', { date: '2024-06-01', summary: 'Jun' });
await engine.addTimelineEntry('test/timeline', { date: '2024-12-01', summary: 'Dec' });
const filtered = await engine.getTimeline('test/timeline', {
after: '2024-03-01', before: '2024-09-01',
});
expect(filtered.length).toBe(1);
expect(filtered[0].summary).toBe('Jun');
});
});
// ─────────────────────────────────────────────────────────────────
// Batch methods (addLinksBatch / addTimelineEntriesBatch)
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: addLinksBatch', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('a', { type: 'concept', title: 'A', compiled_truth: '', timeline: '' });
await engine.putPage('b', { type: 'concept', title: 'B', compiled_truth: '', timeline: '' });
await engine.putPage('c', { type: 'concept', title: 'C', compiled_truth: '', timeline: '' });
});
test('empty batch returns 0 with no DB call', async () => {
expect(await engine.addLinksBatch([])).toBe(0);
});
test('batch of 1 with missing optional fields inserts row with empty defaults', async () => {
const inserted = await engine.addLinksBatch([{ from_slug: 'a', to_slug: 'b' }]);
expect(inserted).toBe(1);
const links = await engine.getLinks('a');
expect(links.length).toBe(1);
expect(links[0].context).toBe('');
expect(links[0].link_type).toBe('');
});
test('within-batch duplicates are deduped via ON CONFLICT (no 21000 error)', async () => {
const inserted = await engine.addLinksBatch([
{ from_slug: 'a', to_slug: 'b', link_type: 'mention' },
{ from_slug: 'a', to_slug: 'b', link_type: 'mention' },
{ from_slug: 'a', to_slug: 'c', link_type: 'mention' },
]);
expect(inserted).toBe(2);
});
test('rows with missing slug are silently dropped by JOIN', async () => {
const inserted = await engine.addLinksBatch([
{ from_slug: 'doesnt-exist', to_slug: 'b' },
{ from_slug: 'a', to_slug: 'b' },
]);
expect(inserted).toBe(1);
});
test('half-existing batch returns count of new only', async () => {
await engine.addLink('a', 'b', '', 'mention');
const inserted = await engine.addLinksBatch([
{ from_slug: 'a', to_slug: 'b', link_type: 'mention' },
{ from_slug: 'a', to_slug: 'c', link_type: 'mention' },
]);
expect(inserted).toBe(1);
});
test('batch of 100 fresh rows returns 100', async () => {
// Create 100 target pages
for (let i = 0; i < 100; i++) {
await engine.putPage(`target/${i}`, { type: 'concept', title: `T${i}`, compiled_truth: '', timeline: '' });
}
const batch = Array.from({ length: 100 }, (_, i) => ({
from_slug: 'a', to_slug: `target/${i}`, link_type: 'mention',
}));
expect(await engine.addLinksBatch(batch)).toBe(100);
});
});
describe('PGLiteEngine: addTimelineEntriesBatch', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('p1', { type: 'concept', title: 'P1', compiled_truth: '', timeline: '' });
await engine.putPage('p2', { type: 'concept', title: 'P2', compiled_truth: '', timeline: '' });
});
test('empty batch returns 0', async () => {
expect(await engine.addTimelineEntriesBatch([])).toBe(0);
});
test('batch of 1 with missing optionals inserts with empty defaults', async () => {
const inserted = await engine.addTimelineEntriesBatch([
{ slug: 'p1', date: '2024-01-15', summary: 'Founded' },
]);
expect(inserted).toBe(1);
const entries = await engine.getTimeline('p1');
expect(entries.length).toBe(1);
expect(entries[0].source).toBe('');
expect(entries[0].detail).toBe('');
});
test('within-batch duplicates are deduped via ON CONFLICT', async () => {
const inserted = await engine.addTimelineEntriesBatch([
{ slug: 'p1', date: '2024-01-15', summary: 'Founded' },
{ slug: 'p1', date: '2024-01-15', summary: 'Founded' },
{ slug: 'p1', date: '2024-02-01', summary: 'Launched' },
]);
expect(inserted).toBe(2);
});
test('rows with missing slug are silently dropped by JOIN', async () => {
const inserted = await engine.addTimelineEntriesBatch([
{ slug: 'no-such-page', date: '2024-01-15', summary: 'Phantom' },
{ slug: 'p1', date: '2024-01-15', summary: 'Real' },
]);
expect(inserted).toBe(1);
});
test('mix of new + existing returns count of new only', async () => {
await engine.addTimelineEntry('p1', { date: '2024-01-15', summary: 'Founded' });
const inserted = await engine.addTimelineEntriesBatch([
{ slug: 'p1', date: '2024-01-15', summary: 'Founded' },
{ slug: 'p1', date: '2024-02-01', summary: 'Launched' },
{ slug: 'p2', date: '2024-03-01', summary: 'Spun off' },
]);
expect(inserted).toBe(2);
});
});
// v0.18.0: regression guards for the cross-source JOIN fan-out.
// Before the fix, addLinksBatch/addTimelineEntriesBatch JOINed on pages.slug
// only — so a page with the same slug in two sources would fan out and
// silently create duplicate edges / entries. Source-id-qualified JOINs
// eliminate the fan-out.
describe('PGLiteEngine: batch ops source-awareness (v0.18.0)', () => {
beforeEach(async () => {
await truncateAll();
// Register a second source and populate the same slugs in both.
const db = (engine as any).db;
await db.query(
`INSERT INTO sources (id, name) VALUES ('alt', 'alt')
ON CONFLICT (id) DO NOTHING`
);
// default-source rows via putPage (schema DEFAULT 'default').
await engine.putPage('topics/ai', { type: 'concept', title: 'AI (default)', compiled_truth: '', timeline: '' });
await engine.putPage('topics/ml', { type: 'concept', title: 'ML (default)', compiled_truth: '', timeline: '' });
// alt-source rows with the same slugs, inserted via raw SQL.
await db.query(
`INSERT INTO pages (slug, type, title, compiled_truth, timeline, frontmatter, content_hash, source_id, updated_at)
VALUES ('topics/ai', 'concept', 'AI (alt)', '', '', '{}'::jsonb, 'h1', 'alt', now()),
('topics/ml', 'concept', 'ML (alt)', '', '', '{}'::jsonb, 'h2', 'alt', now())`
);
});
test('addLinksBatch default source_id does NOT fan out across sources', async () => {
const inserted = await engine.addLinksBatch([
{ from_slug: 'topics/ai', to_slug: 'topics/ml', link_type: 'mention' },
]);
// Exactly one edge, not two. Before the fix this was 2.
expect(inserted).toBe(1);
const db = (engine as any).db;
const { rows } = await db.query(
`SELECT f.source_id AS from_src, t.source_id AS to_src
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id`
);
expect(rows.length).toBe(1);
expect(rows[0].from_src).toBe('default');
expect(rows[0].to_src).toBe('default');
});
test('addLinksBatch with explicit alt source_id lands in alt only', async () => {
const inserted = await engine.addLinksBatch([
{
from_slug: 'topics/ai', to_slug: 'topics/ml', link_type: 'mention',
from_source_id: 'alt', to_source_id: 'alt',
},
]);
expect(inserted).toBe(1);
const db = (engine as any).db;
const { rows } = await db.query(
`SELECT f.source_id AS from_src, t.source_id AS to_src
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id`
);
expect(rows.length).toBe(1);
expect(rows[0].from_src).toBe('alt');
expect(rows[0].to_src).toBe('alt');
});
test('addLinksBatch supports cross-source edges', async () => {
const inserted = await engine.addLinksBatch([
{
from_slug: 'topics/ai', to_slug: 'topics/ml', link_type: 'mention',
from_source_id: 'default', to_source_id: 'alt',
},
]);
expect(inserted).toBe(1);
const db = (engine as any).db;
const { rows } = await db.query(
`SELECT f.source_id AS from_src, t.source_id AS to_src
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id`
);
expect(rows.length).toBe(1);
expect(rows[0].from_src).toBe('default');
expect(rows[0].to_src).toBe('alt');
});
test('addTimelineEntriesBatch default source_id does NOT fan out across sources', async () => {
const inserted = await engine.addTimelineEntriesBatch([
{ slug: 'topics/ai', date: '2024-01-15', summary: 'Founded' },
]);
// Exactly one entry (default source), not two. Before the fix this was 2.
expect(inserted).toBe(1);
const db = (engine as any).db;
const { rows } = await db.query(
`SELECT p.source_id FROM timeline_entries te
JOIN pages p ON p.id = te.page_id`
);
expect(rows.length).toBe(1);
expect(rows[0].source_id).toBe('default');
});
test('addTimelineEntriesBatch with explicit alt source_id lands in alt only', async () => {
const inserted = await engine.addTimelineEntriesBatch([
{ slug: 'topics/ai', date: '2024-01-15', summary: 'Founded', source_id: 'alt' },
]);
expect(inserted).toBe(1);
const db = (engine as any).db;
const { rows } = await db.query(
`SELECT p.source_id FROM timeline_entries te
JOIN pages p ON p.id = te.page_id`
);
expect(rows.length).toBe(1);
expect(rows[0].source_id).toBe('alt');
});
});
// ─────────────────────────────────────────────────────────────────
// Raw Data, Versions, Config, IngestLog
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: RawData', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('test/raw', testPage);
});
test('putRawData + getRawData', async () => {
await engine.putRawData('test/raw', 'crunchbase', { funding: '$10M' });
const data = await engine.getRawData('test/raw', 'crunchbase');
expect(data.length).toBe(1);
expect((data[0].data as any).funding).toBe('$10M');
});
});
describe('PGLiteEngine: Versions', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('test/version', testPage);
});
test('createVersion + getVersions', async () => {
const v = await engine.createVersion('test/version');
expect(v.compiled_truth).toBe(testPage.compiled_truth);
const versions = await engine.getVersions('test/version');
expect(versions.length).toBe(1);
});
test('revertToVersion restores content', async () => {
await engine.createVersion('test/version');
await engine.putPage('test/version', { ...testPage, compiled_truth: 'Changed' });
const versions = await engine.getVersions('test/version');
await engine.revertToVersion('test/version', versions[0].id);
const page = await engine.getPage('test/version');
expect(page!.compiled_truth).toBe(testPage.compiled_truth);
});
});
describe('PGLiteEngine: Config', () => {
test('getConfig + setConfig', async () => {
await engine.setConfig('test_key', 'test_value');
const val = await engine.getConfig('test_key');
expect(val).toBe('test_value');
});
test('getConfig returns null for missing key', async () => {
const val = await engine.getConfig('nonexistent_key');
expect(val).toBeNull();
});
});
describe('PGLiteEngine: IngestLog', () => {
test('logIngest + getIngestLog', async () => {
await engine.logIngest({
source_type: 'git', source_ref: '/tmp/test-repo',
pages_updated: ['test/a', 'test/b'], summary: 'Imported 2 pages',
});
const log = await engine.getIngestLog({ limit: 10 });
expect(log.length).toBeGreaterThan(0);
expect(log[0].source_type).toBe('git');
});
});
// ─────────────────────────────────────────────────────────────────
// Stats + Health
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: Stats & Health', () => {
beforeAll(async () => {
await truncateAll();
await engine.putPage('test/stats', testPage);
await engine.upsertChunks('test/stats', [
{ chunk_index: 0, chunk_text: 'chunk', chunk_source: 'compiled_truth' },
]);
await engine.addTag('test/stats', 'stat-tag');
});
test('getStats returns correct counts', async () => {
const stats = await engine.getStats();
expect(stats.page_count).toBe(1);
expect(stats.chunk_count).toBe(1);
expect(stats.tag_count).toBe(1);
expect(stats.pages_by_type.concept).toBe(1);
});
test('getHealth returns coverage metrics', async () => {
const health = await engine.getHealth();
expect(health.page_count).toBe(1);
expect(health.missing_embeddings).toBe(1); // chunk has no embedding
expect(health.embed_coverage).toBe(0);
});
});
// ─────────────────────────────────────────────────────────────────
// Transactions
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: Transactions', () => {
beforeEach(truncateAll);
test('transaction commits on success', async () => {
await engine.transaction(async (tx) => {
await tx.putPage('test/tx-ok', testPage);
});
const page = await engine.getPage('test/tx-ok');
expect(page).not.toBeNull();
});
test('transaction rolls back on error', async () => {
try {
await engine.transaction(async (tx) => {
await tx.putPage('test/tx-fail', testPage);
throw new Error('Deliberate rollback');
});
} catch { /* expected */ }
const page = await engine.getPage('test/tx-fail');
expect(page).toBeNull();
});
});
// ─────────────────────────────────────────────────────────────────
// Cascade deletes
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: Cascade deletes', () => {
test('deleting a page cascades to chunks, tags, links', async () => {
await engine.putPage('test/cascade', testPage);
await engine.upsertChunks('test/cascade', [
{ chunk_index: 0, chunk_text: 'cascade chunk', chunk_source: 'compiled_truth' },
]);
await engine.addTag('test/cascade', 'cascade-tag');
await engine.deletePage('test/cascade');
const chunks = await engine.getChunks('test/cascade');
expect(chunks.length).toBe(0);
const tags = await engine.getTags('test/cascade');
expect(tags.length).toBe(0);
});
});
// ─────────────────────────────────────────────────────────────────
// v0.10.1: Knowledge graph layer
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: getAllSlugs', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' });
await engine.putPage('people/bob', { ...testPage, type: 'person', title: 'Bob' });
await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'Acme' });
});
test('returns Set of all page slugs', async () => {
const slugs = await engine.getAllSlugs();
expect(slugs).toBeInstanceOf(Set);
expect(slugs.size).toBe(3);
expect(slugs.has('people/alice')).toBe(true);
expect(slugs.has('companies/acme')).toBe(true);
});
test('empty brain returns empty Set', async () => {
await truncateAll();
const slugs = await engine.getAllSlugs();
expect(slugs.size).toBe(0);
});
});
describe('PGLiteEngine: listPages updated_after filter', () => {
beforeEach(async () => {
await truncateAll();
});
test('filters pages by updated_at > given date', async () => {
await engine.putPage('test/old', testPage);
// Sleep briefly so the second page has a strictly later updated_at.
await new Promise(r => setTimeout(r, 10));
const cutoff = new Date().toISOString();
await new Promise(r => setTimeout(r, 10));
await engine.putPage('test/new', testPage);
const recent = await engine.listPages({ updated_after: cutoff, limit: 100 });
const recentSlugs = recent.map(p => p.slug);
expect(recentSlugs).toContain('test/new');
expect(recentSlugs).not.toContain('test/old');
});
test('without updated_after, returns all pages (regression)', async () => {
await engine.putPage('test/a', testPage);
await engine.putPage('test/b', testPage);
const all = await engine.listPages({ limit: 100 });
expect(all.length).toBe(2);
});
});
describe('PGLiteEngine: Multi-type links (v5 migration)', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' });
await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'Acme' });
});
test('same (from, to) with different link_types both stored', async () => {
await engine.addLink('people/alice', 'companies/acme', 'CEO', 'works_at');
await engine.addLink('people/alice', 'companies/acme', 'on the board', 'advises');
const links = await engine.getLinks('people/alice');
expect(links.length).toBe(2);
const types = links.map(l => l.link_type).sort();
expect(types).toEqual(['advises', 'works_at']);
});
test('upsert on same (from, to, type) updates context', async () => {
await engine.addLink('people/alice', 'companies/acme', 'old context', 'works_at');
await engine.addLink('people/alice', 'companies/acme', 'new context', 'works_at');
const links = await engine.getLinks('people/alice');
expect(links.length).toBe(1);
expect(links[0].context).toBe('new context');
});
test('removeLink without linkType removes ALL types for the pair (regression)', async () => {
await engine.addLink('people/alice', 'companies/acme', 'a', 'works_at');
await engine.addLink('people/alice', 'companies/acme', 'b', 'advises');
await engine.removeLink('people/alice', 'companies/acme');
const links = await engine.getLinks('people/alice');
expect(links.length).toBe(0);
});
test('removeLink with linkType removes only that type', async () => {
await engine.addLink('people/alice', 'companies/acme', 'a', 'works_at');
await engine.addLink('people/alice', 'companies/acme', 'b', 'advises');
await engine.removeLink('people/alice', 'companies/acme', 'works_at');
const links = await engine.getLinks('people/alice');
expect(links.length).toBe(1);
expect(links[0].link_type).toBe('advises');
});
});
describe('PGLiteEngine: Timeline dedup constraint (v6 migration)', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('test/timeline-dedup', testPage);
});
test('inserting same (date, summary) twice is silent no-op (idempotent)', async () => {
await engine.addTimelineEntry('test/timeline-dedup', { date: '2026-01-15', summary: 'Event A' });
await engine.addTimelineEntry('test/timeline-dedup', { date: '2026-01-15', summary: 'Event A' });
const entries = await engine.getTimeline('test/timeline-dedup');
expect(entries.length).toBe(1);
});
test('different summary on same date: both inserted', async () => {
await engine.addTimelineEntry('test/timeline-dedup', { date: '2026-01-15', summary: 'Morning' });
await engine.addTimelineEntry('test/timeline-dedup', { date: '2026-01-15', summary: 'Evening' });
const entries = await engine.getTimeline('test/timeline-dedup');
expect(entries.length).toBe(2);
});
test('throws on missing page (default behavior preserved)', async () => {
await expect(engine.addTimelineEntry('does/not-exist', { date: '2026-01-15', summary: 'X' }))
.rejects.toThrow();
});
test('skipExistenceCheck=true: silent no-op on missing page', async () => {
// No throw, but also nothing inserted (subquery returns no rows).
await engine.addTimelineEntry(
'does/not-exist',
{ date: '2026-01-15', summary: 'X' },
{ skipExistenceCheck: true },
);
// No assertion needed beyond "did not throw".
});
});
describe('PGLiteEngine: getBacklinkCounts', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' });
await engine.putPage('people/bob', { ...testPage, type: 'person', title: 'Bob' });
await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'Acme' });
});
test('returns Map<slug, count> for given slugs', async () => {
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
await engine.addLink('people/bob', 'companies/acme', '', 'invested_in');
const counts = await engine.getBacklinkCounts(['companies/acme', 'people/alice']);
expect(counts.get('companies/acme')).toBe(2);
expect(counts.get('people/alice')).toBe(0);
});
test('empty input -> empty Map', async () => {
const counts = await engine.getBacklinkCounts([]);
expect(counts.size).toBe(0);
});
test('slugs with zero links: present in Map with 0', async () => {
const counts = await engine.getBacklinkCounts(['people/alice']);
expect(counts.get('people/alice')).toBe(0);
});
});
describe('PGLiteEngine: traversePaths (v0.10.1)', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' });
await engine.putPage('people/bob', { ...testPage, type: 'person', title: 'Bob' });
await engine.putPage('people/carol', { ...testPage, type: 'person', title: 'Carol' });
await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'Acme' });
await engine.putPage('meetings/standup', { ...testPage, type: 'meeting', title: 'Standup' });
// Build a small typed graph
await engine.addLink('meetings/standup', 'people/alice', '', 'attended');
await engine.addLink('meetings/standup', 'people/bob', '', 'attended');
await engine.addLink('meetings/standup', 'people/carol', '', 'attended');
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
await engine.addLink('people/bob', 'companies/acme', '', 'invested_in');
});
test('out direction (default): follows from->to edges', async () => {
const paths = await engine.traversePaths('meetings/standup', { depth: 1 });
expect(paths.length).toBe(3);
expect(new Set(paths.map(p => p.to_slug))).toEqual(new Set(['people/alice', 'people/bob', 'people/carol']));
expect(paths.every(p => p.link_type === 'attended')).toBe(true);
});
test('in direction: follows to->from edges', async () => {
const paths = await engine.traversePaths('companies/acme', { depth: 1, direction: 'in' });
expect(paths.length).toBe(2);
expect(new Set(paths.map(p => p.from_slug))).toEqual(new Set(['people/alice', 'people/bob']));
});
test('linkType per-edge filter: only follows matching edges', async () => {
const paths = await engine.traversePaths('companies/acme', {
depth: 1, direction: 'in', linkType: 'works_at',
});
expect(paths.length).toBe(1);
expect(paths[0].from_slug).toBe('people/alice');
});
test('depth 2: multi-hop traversal', async () => {
const paths = await engine.traversePaths('meetings/standup', { depth: 2 });
// alice/bob/carol direct + alice->acme + bob->acme
expect(paths.length).toBeGreaterThanOrEqual(5);
const acmePaths = paths.filter(p => p.to_slug === 'companies/acme');
expect(acmePaths.length).toBe(2);
expect(acmePaths.every(p => p.depth === 2)).toBe(true);
});
test('non-existent slug returns empty', async () => {
const paths = await engine.traversePaths('does/not-exist', { depth: 5 });
expect(paths).toEqual([]);
});
});
describe('PGLiteEngine: traverseGraph cycle prevention', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('people/a', { ...testPage, type: 'person', title: 'A' });
await engine.putPage('people/b', { ...testPage, type: 'person', title: 'B' });
// Create a 2-cycle: A -> B -> A
await engine.addLink('people/a', 'people/b', '', 'mentions');
await engine.addLink('people/b', 'people/a', '', 'mentions');
});
test('does not amplify on cyclic graphs', async () => {
// Without cycle prevention, depth 5 on a 2-cycle would loop indefinitely
// (or at least produce many duplicate nodes). With the visited array, each
// node appears at most once.
const graph = await engine.traverseGraph('people/a', 5);
const slugs = graph.map(n => n.slug);
// Each slug should appear at most twice (once at depth 0, possibly once
// again at a deeper level via the cycle, but bounded by visited check).
const counts = new Map<string, number>();
for (const s of slugs) counts.set(s, (counts.get(s) ?? 0) + 1);
for (const [slug, count] of counts) {
expect(count).toBeLessThanOrEqual(2); // tolerate root + 1 traversal entry
void slug;
}
});
});
describe('PGLiteEngine: getHealth graph metrics', () => {
beforeEach(async () => {
await truncateAll();
await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' });
await engine.putPage('people/bob', { ...testPage, type: 'person', title: 'Bob' });
await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'Acme' });
});
test('link_coverage = 0 when no links exist', async () => {
const h = await engine.getHealth();
expect(h.link_coverage).toBe(0);
});
test('link_coverage = % of entity pages with >= 1 inbound link', async () => {
// Acme gets 1 inbound link (from Alice), Alice/Bob get 0 inbound.
// 1 of 3 entity pages has inbound links -> 33%.
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
const h = await engine.getHealth();
expect(h.link_coverage).toBeCloseTo(1 / 3, 2);
});
test('timeline_coverage = % with >= 1 timeline entry', async () => {
await engine.addTimelineEntry('people/alice', { date: '2026-01-15', summary: 'Joined' });
const h = await engine.getHealth();
expect(h.timeline_coverage).toBeCloseTo(1 / 3, 2);
});
test('most_connected lists top entities by link count', async () => {
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
await engine.addLink('people/bob', 'companies/acme', '', 'invested_in');
const h = await engine.getHealth();
expect(h.most_connected.length).toBeGreaterThan(0);
expect(h.most_connected[0].slug).toBe('companies/acme');
expect(h.most_connected[0].link_count).toBe(2);
});
test('orphan_pages: pages with neither inbound nor outbound links', async () => {
// All 3 pages start with no links. Expect 3 orphans.
const h = await engine.getHealth();
expect(h.orphan_pages).toBe(3);
// Add alice -> acme. Alice has outbound, acme has inbound, only Bob is orphan.
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
const h2 = await engine.getHealth();
expect(h2.orphan_pages).toBe(1);
});
});
// ─────────────────────────────────────────────────────────────────
// v0.13.1 — PGLite.create() error-wrap (structural guard for #223)
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: v0.13.1 error-wrap on connect() (#223)', () => {
test('pglite-engine.ts source contains the wrap with #223 hint and nested original error', async () => {
const { readFileSync } = await import('fs');
const src = readFileSync('src/core/pglite-engine.ts', 'utf-8');
// Structural: the try/catch block must wrap PGlite.create() (the actual
// abort site, NOT engine-factory.ts). The error message must name the
// issue and suggest gbrain doctor. Must NOT suggest "missing migrations"
// as a cause (that was conflating #218 and #223 — migrations run AFTER
// create()).
expect(src).toContain('this._db = await PGlite.create');
expect(src).toContain('https://github.com/garrytan/gbrain/issues/223');
expect(src).toContain('gbrain doctor');
expect(src).toContain('Original error:');
// Regression guard: the user-visible error MESSAGE must not re-introduce
// the misleading "missing migrations" hint. (A source comment explaining
// *why* we removed it is fine — match only inside the wrapped Error body.)
const wrapStart = src.indexOf('const wrapped = new Error(');
expect(wrapStart).toBeGreaterThan(-1);
const wrapEnd = src.indexOf(');', wrapStart);
const errBody = src.slice(wrapStart, wrapEnd);
expect(errBody).not.toContain('missing migrations');
expect(errBody).not.toContain('apply-migrations');
});
});
// ─────────────────────────────────────────────────────────────────
// v0.13.1 — Engine kind discriminator
// ─────────────────────────────────────────────────────────────────
describe('PGLiteEngine: v0.13.1 kind discriminator', () => {
test('exposes readonly kind = pglite', () => {
expect(engine.kind).toBe('pglite');
});
});