mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
+10








ff53a4c9bc
* fix: bootstrap forward-references for v39-v41 schema replay
Three column-with-index forward references in the embedded schema blob were
missing from applyForwardReferenceBootstrap, so any brain at config.version
< 39 (Postgres) or < 41 (PGLite) wedges before the migration runner can
advance. Reproduced end-to-end on a PlanetScale Postgres brain stuck at
config.version=34 trying to upgrade to v0.30.0:
ERROR: column "effective_date" does not exist
ERROR: column cc.modality does not exist
(After upgrading, gbrain search and gbrain reindex-frontmatter both fail.)
The schema-blob references that crash before migrations run:
- v39 (multimodal_dual_column_v0_27_1):
CREATE INDEX idx_chunks_embedding_image
ON content_chunks USING hnsw (embedding_image vector_cosine_ops)
WHERE embedding_image IS NOT NULL;
- v41 (pages_recency_columns):
CREATE INDEX pages_coalesce_date_idx
ON pages ((COALESCE(effective_date, updated_at)));
PGLite already covered v39 (lines 273+, 308+, 382-392). Postgres and PGLite
both lacked v40+v41 coverage. This commit adds:
- Postgres engine probe + branch for v39 (modality, embedding_image) — was
entirely missing on Postgres, so Postgres brains < v39 hit the wedge that
PGLite already protected against.
- Both engines: probe + branch for v40+v41. Bootstraps all five additive
pages columns (emotional_weight, effective_date, effective_date_source,
import_filename, salience_touched_at) gated on `effective_date_exists`
as the proxy.
- test/schema-bootstrap-coverage.test.ts: extends REQUIRED_BOOTSTRAP_COVERAGE
with the six new columns AND the pre-test DROP block so both the per-target
assertion test and the end-to-end "bootstrap + SCHEMA_SQL replay" test
exercise the new coverage.
All 5 tests in schema-bootstrap-coverage pass. typecheck clean.
Bootstrap stays additive-columns-only. Indexes are left to schema replay /
migrations as before.
* fix(deps): declare @jsquash/png and heic-decode
Both packages are direct imports in src/core/import-file.ts (decodeIfNeeded
for HEIC/AVIF → PNG) but only @jsquash/avif was declared. bun --compile
fails on a fresh install:
error: Could not resolve: "@jsquash/png/encode.js"
error: Could not resolve: "heic-decode"
Adds the missing declarations so npm install / bun install bring them in.
Versions chosen as latest at time of fix:
@jsquash/png ^3.1.1
heic-decode ^2.1.0
* fix(backfill-effective-date): replace bare BEGIN/COMMIT with engine.transaction()
postgres.js refuses bare BEGIN/COMMIT on pooled connections with
UNSAFE_TRANSACTION. The migration runner and other call sites already
use engine.transaction() (which routes through sql.begin() with a
reserved backend) — backfill-effective-date.ts was the holdout.
Reproduces on PlanetScale Postgres (us-east-4.pg.psdb.cloud) running
the v0.29.1 orchestrator's Phase B against a brain that has any rows
needing backfill:
Reindex ok ... UNSAFE_TRANSACTION: Only use sql.begin, sql.reserved or max: 1
Switches the per-batch transaction to engine.transaction(async tx => …).
The SET LOCAL statement_timeout still scopes to the transaction; UPDATE
runs through the tx-scoped engine. ROLLBACK on error happens
automatically via sql.begin's contract.
Equivalent fix shape to existing usages in src/core/postgres-engine.ts
(lines 703, 806, 925) and the migration runner in src/core/migrate.ts
(line 2147).
* fix(v0_29_1): connect engine before use in Phase B and Phase C
phaseBBackfill() and phaseCVerify() build their own engine via
createEngine(toEngineConfig(cfg)) but never call engine.connect().
This worked accidentally before because executeRaw lazily falls back
to db.getConnection(), but engine.transaction() (added in the
companion backfill fix) requires a connected backend and surfaces
the missing-connect with:
No database connection: connect() has not been called.
Fix: Run gbrain init --supabase or gbrain init --url <connection_string>
Other orchestrators in the same directory get this right —
v0_28_0.ts:181 already does `await engine.connect(engineConfig)`
right after createEngine. Aligning v0_29_1 with that pattern.
After this + the backfill fix, v0.29.1 orchestrator runs to
'complete' on a fresh upgrade with backfill-needed rows, instead
of wedging at 'partial' status.
Note: anyone hitting the wedged state after the prior failures will
need `gbrain apply-migrations --force-retry 0.29.1` once before the
next apply-migrations --yes succeeds (the 3-consecutive-partials
guard in apply-migrations.ts is still active).
* fix: connect engine in v0.29.1 migration
* fix(upgrade): detectBunLink fails because bun resolves symlinks in argv[1]
bun resolves the entire symlink chain before setting process.argv[1],
so lstatSync(argv1).isSymbolicLink() always returns false for bun-link
installs, short-circuiting the git-config walk that would correctly
identify the repo. Remove the symlink gate — argv[1] is already the
real path inside the checkout, which is what the walk needs.
Also: return { repoRoot } so the upgrade path can auto-execute
git pull + bun install via execFileSync (no shell injection surface).
Fixes #368, supersedes incomplete v0.28.5 fix for #656.
* fix(oauth): clamp authorize() requested scopes against client.scope (RFC 6749 §3.3)
The MCP SDK's authorize handler (`@modelcontextprotocol/sdk/.../auth/handlers/authorize.js`)
splits `?scope=...` verbatim and forwards the parsed list to the provider, so the
provider has to clamp against the client's registered grant. v0.28.11
`authorize()` (src/core/oauth-provider.ts:235-259) inserted `params.scopes || []`
raw into `oauth_codes`, so a `read`-registered client requesting
`?scope=admin` had `['admin']` stored and `exchangeAuthorizationCode` issued
a fully-admin access token at /token exchange.
The asymmetry is the bug: the other two grant entry points already clamp.
`exchangeClientCredentials` (line 513-515) filters requested scopes through
`hasScope(allowedScopes, s)`, and `exchangeRefreshToken`'s F3 (line 372-380)
enforces RFC 6749 §6 subset against the original grant. authorize() lined up
with neither.
Fix mirrors the client_credentials filter shape so all three grant entry
points clamp consistently:
const allowedScopes = parseScopeString(client.scope);
const grantedScopes = (params.scopes || []).filter(s => hasScope(allowedScopes, s));
Empty/omitted requested scope keeps storing `[]` (existing shape, not a
security boundary). The clamped subset is what the client sees in the
`scope` field of the token response, which is the spec-compliant signal
that the grant was reduced.
Test coverage:
- New: authorize clamps requested scopes against client.scope (RFC 6749 §3.3)
— read-only client requests ['read','write','admin'] and the issued token
carries only ['read'].
- New: authorize subset request returns subset — 'read write' client
requesting ['read'] gets ['read'] (regression guard against over-clamping).
The existing v0.26.9 oauth.test.ts pins F3 (refresh clamp) but had no
authorize-side coverage, which is why the regression survived.
* fix(sync): handle detached HEAD by skipping pull and ingesting local working tree
* fix(sync): --skip-failed acks pre-existing unacked failures up-front
The recovery flow that doctor + printSyncResult both advertise was broken:
1. User has files with bad YAML → they hit the failure log + sync stays
blocked at last_commit.
2. User fixes the YAML.
3. User re-runs `gbrain sync` — sync succeeds, advances last_commit.
4. `gbrain doctor` still reports N unacked failures from step 1 because
sync-failures.jsonl is append-only history, never auto-cleared.
5. doctor message says: "use 'gbrain sync --skip-failed' to acknowledge".
6. User runs `gbrain sync --skip-failed` → "Already up to date." → log
unchanged.
The bug: --skip-failed only acknowledges failures from the CURRENT run.
performSync's ack path is gated on `failedFiles.length > 0` after sync —
it never fires when the diff is empty (because the user already fixed
the bad files) or when the sync is up to date. So the documented recovery
sequence is a no-op exactly when the user needs it.
The fix: at the top of runSync, when --skip-failed is set, eagerly ack
any pre-existing unacked failures before any sync work runs. Now the flag
means "acknowledge whatever is currently flagged and move on" regardless
of whether the current run produces new failures or finds nothing to do.
The inner per-run ack path stays — it still handles new failures from
the CURRENT run, which is the (a) syncing now produces failures + (b)
caller wants to ack them path. The two paths compose: `gbrain sync
--skip-failed` clears stale + advances past anything new, all in one
command, matching what the doctor message promises.
Tests: 2 added in test/sync-failures.test.ts. One source-string pin on
the new gate (the file's existing pattern for CLI-flag tests). One
behavioral test on the underlying acknowledgeSyncFailures path.
Repro:
$ gbrain doctor
[WARN] sync_failures: 27 unacknowledged sync failure(s)...
Fix the file(s) and re-run 'gbrain sync', or use
'gbrain sync --skip-failed' to acknowledge.
$ # ... fix the YAML ...
$ gbrain sync
Already up to date.
$ gbrain sync --skip-failed
Already up to date. # before this PR
$ gbrain doctor
[WARN] sync_failures: 27 unacknowledged sync failure(s)... # still!
After:
$ gbrain sync --skip-failed
Acknowledged 27 pre-existing failure(s).
Already up to date.
$ gbrain doctor
[OK] sync_failures: N historical sync failure(s), all acknowledged
* fix(extract): default --dir to configured brain dir, not cwd
`gbrain extract links` (and timeline / all) defaulted --dir to '.' when
not explicitly passed (src/commands/extract.ts:357). Combined with a
walker that skips dotfiles but NOT node_modules/dist/build/vendor, this
turned a no-arg invocation into a footgun.
Repro:
$ cd ~/Documents/some-project # has a node_modules/ tree
$ gbrain extract links
[extract.links_fs] 28989/28989 (100%) done
Links: created 0 from 28989 pages
Done: 0 links, 0 timeline entries from 28989 pages
The "28989 pages" is `walkMarkdownFiles('.')` recursively eating package
READMEs, dependency docs, fixture content. Their from_slug doesn't match
any row in the pages table, so addLinksBatch rejects every insert and
returns 0. Output looks like a healthy idempotent no-op; was actually a
wasteful junk walk that wrote nothing.
Fix: when --dir is not passed AND source is fs, resolve from
sources(local_path) via getDefaultSourcePath — same helper sync uses
(src/commands/sync.ts:1089). The default behavior now matches `sync`:
"work on the configured brain". Falls back to a clear error when no
source is configured, telling the user to either pass --dir, register
a source, or use --source db.
Behavior matrix:
--dir explicit → use that path (unchanged)
--dir absent + cfg → resolve from sources(local_path)
--dir absent + no → error with actionable hint (was: walk cwd silently)
--dir . → cwd (user opted in explicitly — unchanged)
Tests: three added in test/extract-fs.test.ts:
1. configured source → no-arg invocation extracts from that path
2. no source configured → exit 1 + actionable error message
3. explicit --dir wins over a configured (decoy) source path
* fix(extract): normalize slugs to lowercase via pathToSlug() (T-OBS-1)
The extractor was generating from_slug and the allSlugs lookup set from
`relPath.replace('.md', '')` in 5 places, producing CAPS slugs for files
named ETHOS.md, AGENTS.md, ROADMAP.md, etc.
Pages persist in the DB with lowercase slug (core/sync.ts pathToSlug()
applies .toLowerCase()). The CAPS extractor output mismatched the DB rows,
so INSERT ... JOIN pages ON pages.slug = v.from_slug silently dropped
links from CAPS-named source files. The link batch returned 'inserted'
counts that were lower than the wikilinks actually present, with no error.
Reproduction (in a brain with CAPS-named canonical docs):
1. echo 'See [agents](agents.md).' > ETHOS.md
2. gbrain put ethos < ETHOS.md # page row: slug='ethos'
3. gbrain extract links --source fs
4. gbrain backlinks agents → [] (expected: contains 'ethos')
Fix: import pathToSlug from core/sync.ts and use it in all 5 sites:
- extractLinksFromFile (line 200): from_slug derivation
- runIncrementalExtractInternal (line 456): allSlugs set
- extractLinksFromDir (line 552): allSlugs set
- timeline loop (line 643): from_slug for timeline entries
- extractLinksForSlugs (line 673): allSlugs set used by sync hook
This single-line-per-site change keeps the extractor consistent with the
sync layer's slug normalization and doesn't introduce any new behavior
for already-lowercase paths (idempotent).
Tests: added 'extractLinksFromFile — slug normalization (T-OBS-1
regression)' suite with 4 cases covering CAPS, mixed-case, idempotent
lowercase, and nested path. Full extract suite (54 → 58 tests) passes.
Reported by Claude Code (Opus 4.7) during Obsidian PKM integration on
the gstack-plan Living Repo, where ~111 wikilinks pointing to ETHOS,
AGENTS, ROADMAP, etc. failed to count toward brain_score (54/100 vs
expected 75+/100). Documented as T-OBS-1 in the consumer's blocked.md.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(cli): CLI_ONLY commands should short-circuit on --help instead of executing
* fix(doctor): correct command syntax in graph_coverage warn message
graph_coverage warn directs users to run `gbrain link-extract &&
gbrain timeline-extract`, but no commands by those names are
registered in cli.ts. The actual commands are `gbrain extract links`
and `gbrain extract timeline` (registered as the 'extract'
subcommand at src/cli.ts:525, with the kind argument 'links' /
'timeline' / 'all' parsed inside src/commands/extract.ts).
A user who runs the suggested command gets:
$ gbrain link-extract
Unknown command: link-extract
This is the only place in src/ with the wrong syntax — the rest of
the docs (init.ts:221, init.ts:331, features.ts:120,
v0_13_0.ts:67, sync.ts:752 comment) all already say 'extract links'.
This patch just brings doctor.ts in line.
* fix(doctor): use autoDetectSkillsDir so OpenClaw workspaces are reachable
`gbrain doctor` was the only consumer of `findRepoRoot` from
`core/repo-root.ts`. Every other consumer (check-resolvable.ts:145,
skillify.ts, etc.) uses `autoDetectSkillsDir`, which has the full
detection chain:
1. \$OPENCLAW_WORKSPACE
2. ~/.openclaw/workspace
3. findRepoRoot() walk from cwd
4. ./skills
`findRepoRoot` only does step 3. Result: when the user runs `gbrain
doctor` from any directory outside the gbrain repo or the OpenClaw
workspace tree (e.g., a project's checkout), `resolver_health` reports
"Could not find skills directory" even though the dispatcher exists at
~/.openclaw/workspace/skills/RESOLVER.md.
Reproduces in any directory other than ~/gbrain or its descendants on
a system with ~/.openclaw/workspace/skills/RESOLVER.md present:
\$ cd ~/Documents
\$ gbrain doctor
[WARN] resolver_health: Could not find skills directory # before
[WARN] resolver_health: 5 issue(s): 0 error(s), 5 warning(s) # after
Switching doctor to `autoDetectSkillsDir` brings it inline with the rest
of the codebase. The detected dir is also passed to
`checkSkillConformance` (step 2 of the resolver_health block), which
previously rebuilt the path from `repoRoot` — now uses the same
detected path for consistency.
All 15 existing tests in test/doctor.test.ts continue to pass.
* fix(mcp): exit serve process on stdin-close/SIGTERM
MCP stdio server was keeping the bun process alive indefinitely after
the client disconnected. Over days this accumulated 20+ orphaned
gbrain serve processes, all holding the PGLite directory open.
Since PGLite is single-writer, this caused write-lock contention that
made email-sync fail its 15s per-put timeout: 114 puts x 15s = 28.5min
runs with 0 emails written.
Now listens for stdin end/close, transport close, and SIGTERM/SIGINT/
SIGHUP; calls engine.disconnect() and exits cleanly.
Root cause for the no-gbrain-run-in-50h alert.
* fix(skills): broaden RESOLVER triggers + 1 ambiguity flag (37 misses → 0, 100% top-1 accuracy)
`bun run src/cli.ts routing-eval` was reporting 37 ROUTING_MISS entries
across 10 skills whose RESOLVER.md trigger phrases didn't match any of
their own routing-eval.jsonl fixture intents. Two distinct causes:
1. Single-phrase triggers in 9 skills under '## Uncategorized' didn't
cover the paraphrased fixture variations they're supposed to route.
Broadened each trigger cell to a quoted-phrase list that covers the
fixtures (5 fixtures per skill on average).
2. The media-ingest row used unquoted prose
('Video, audio, PDF, book, YouTube, screenshot') which
extractTriggerPhrases() collapses into one impossible long phrase
('video audio pdf book youtube screenshot') under normalizeText —
no fixture intent will ever contain that exact substring. Converted
to a quoted phrase list.
3. One fixture ('web research pass on this person') legitimately
matches both `perplexity-research` and `data-research`
(data-research's trigger row contains "Research"). Marked the
fixture `ambiguous_with: ["data-research"]` since the overlap
on the keyword 'research' is inherent and expected.
Skills with broadened triggers:
- voice-note-ingest, article-enrichment, book-mirror,
archive-crawler, brain-pdf, academic-verify, concept-synthesis,
perplexity-research, strategic-reading, media-ingest
Before: 58 cases, 37 misses, ~36% top-1 accuracy
After: 58 cases, 0 misses, 100% top-1 accuracy
This also clears `gbrain doctor`'s `resolver_health: 37 issue(s)` warning.
* fix(multi-source): thread source_id through per-page tx surface
Multi-source brains crashed mid-import with Postgres 21000 ("more than one
row returned by a subquery used as an expression"). Root cause: putPage's
INSERT column list omitted source_id, so writes intended for a non-default
source (e.g. 'jarvis-memory') silently fabricated a duplicate row at
(default, slug). The schema has UNIQUE(source_id, slug) but DEFAULT 'default'
for source_id; calling putPage(slug, page) without source_id landed at
(default, slug) and ON CONFLICT updated the wrong row, leaving the intended
source row stale. Subsequent bare-slug subqueries inside the same tx —
(SELECT id FROM pages WHERE slug = $1) in getTags / removeTag / deleteChunks
/ removeLink / addLink (cross-product) — then matched 2 rows and crashed
with 21000, rolling back the entire import. Observed: 18 sync failures
against a 'jarvis-memory'-sourced brain.
Fix:
- putPage adds source_id to the INSERT column list (defaults 'default' for
back-compat).
- Every bare-slug page-id subquery becomes source-qualified
(AND source_id = $X) in both engines: createVersion, upsertChunks,
getChunks, addTag, removeTag, getTags, deleteChunks, removeLink,
addTimelineEntry, deletePage, updateSlug.
- addLink rewritten away from FROM pages f, pages t cross-product into a
VALUES + JOIN-on-(slug, source_id) shape mirroring addLinksBatch.
- engine.ts interface: 11 method signatures gain optional opts.sourceId
(or opts.{from,to,origin}SourceId for addLink/removeLink). All optional;
existing callers default to source='default' and behave identically.
- import-file.ts: importFromContent / importFromFile / importCodeFile take
opts.sourceId and thread txOpts = { sourceId } through every per-page tx
call. engine.getPage callsite source-scoped for accurate idempotency.
- commands/sync.ts: thread opts.sourceId at importFile (line 581 + 641),
un-syncable cleanup (487-498), delete phase (557), rename phase (574),
and post-sync extract phase (815-816).
- commands/reindex-code.ts: thread opts.sourceId at importCodeFile call.
- commands/extract.ts: extractLinksForSlugs / extractTimelineForSlugs accept
opts.sourceId and propagate via linkOpts / entryOpts.
- commands/reconcile-links.ts: ReconcileLinksOpts.sourceId was declared but
ignored end-to-end; now wired through getPage + addLink calls.
- commands/migrate-engine.ts: --force wipe switched to executeRaw('DELETE
FROM pages') to preserve the pre-PR all-sources semantic after deletePage
became default-source-scoped.
Regression test: test/source-id-tx-regression.test.ts (19 tests). Validates
two sources × same slug coexist; getTags/addTag/removeTag/deleteChunks/
upsertChunks/createVersion/addLink/addTimelineEntry/deletePage/updateSlug
source-scoped writes don't 21000; back-compat without opts targets
source='default'; addLink fail-fast on missing source-qualified endpoint;
importFromContent end-to-end tx thread without fabricating duplicate.
Adversarial review: Codex (gpt-5.5 reviewer) + Grok (xAI flagship reviewer)
3-round crew loop. Round 1: 2 HIGH (addTimelineEntry + extract.ts thread)
+ 2 MED. Round 2: 1 CRITICAL + 1 HIGH (deletePage + updateSlug bare-slug)
+ 2 MED. Round 3: 2 HIGH (getChunks + migrate-engine semantic regression
introduced by R2 fix). Round 4: both reviewers CLEAR.
Deferred to follow-up PRs (noted as TODO):
- src/commands/embed.ts source-aware threading (auto-embed at sync.ts:823
has a TODO; try/catch swallows the failure as best-effort).
- src/core/postgres-engine.ts:1511 / pglite-engine.ts:1446 putRawData
bare-slug (lower-impact metadata path).
- Read-surface bare-slug consistency cleanup (getLinks/getBacklinks/
getTimeline/getRawData/getVersions): non-mutating, won't 21000.
- reconcile-links.ts CLI --source flag exposure (internal opt is wired;
CLI parser is a UX feature for later).
Existing rows in production written under (default, slug) by the old
putPage when caller meant another source remain misrouted. Backfill
heuristics need install-specific knowledge of intended source and are
outside this PR's scope; surface as a deployment-side cleanup task.
bun run typecheck clean, bun run build clean, 19/19 regression tests pass,
4082 unit pass / 1 pre-existing fail (BrainRegistry test depending on
test-env ~/.gbrain/ absence — fails on untouched main, unrelated).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(multi-source): plumb sourceId through performFullSync (PR #707 gap)
PR #707 fixed source_id routing for sync's incremental loop (lines 581/641)
but performFullSync (line 922) calls runImport without threading sourceId.
Result: full syncs route pages to default even with --source <id>. Verified
on v0.30.1 by direct PGLite probe after `gbrain sync --source X --full`:
all pages landed in default, not the named source.
Fix:
- runImport accepts sourceId in opts (programmatic only — no CLI flag,
preserving PR #707's design intent of `gbrain import` being default-only).
- runImport threads sourceId to importFile + importImageFile.
- performFullSync passes opts.sourceId to runImport.
- ImportImageOptions type accepts sourceId for runImport branch (importImageFile
body wiring deferred — image imports out of scope for current use case;
TS error fix only).
Verified: real sync test against /tmp/test-sync routes 1 page to "testsync"
source, 0 to default (post-fix). 19/19 source-id regression tests still pass.
Typecheck clean.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* test: regression test for performFullSync sourceId threading
PR #707's existing 19-test suite at test/source-id-tx-regression.test.ts
covers the engine-layer transaction surface (putPage / addTag / etc.)
but does NOT exercise commands/sync.ts:performFullSync. Verified via
`grep -c 'performFullSync' test/source-id-tx-regression.test.ts → 0`.
This means the +18/-4 fix at sync.ts:892 (performFullSync passing
sourceId to runImport) had no automated coverage.
Adds 2 PGLite-only regression tests:
1. `performFullSync with --source routes pages to named source (not default)`
— fixture: temp git repo with 2 markdown files. Calls performSync with
{ full: true, sourceId: 'testsrc-pfs', noPull: true, noEmbed: true }.
Asserts pages.source_id = 'testsrc-pfs', not 'default'. Pre-fix: FAILS
(verified by checking out 46cd197 — rebased PR #707 only, without my
gap-fix — and running this test). Post-fix: PASSES.
2. `performFullSync WITHOUT --source still targets default (back-compat)`
— same fixture, no sourceId opt. Asserts pages.source_id = 'default'.
Both pre-fix and post-fix: PASSES (back-compat preserved by the fix).
Verified: 21/21 tests pass on this branch (19 from PR #707 + 2 new).
`bun run typecheck` clean. `bun run verify` clean (8 guard checks pass).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(privacy): strip takes fence from get_page / get_versions when token carries an allow-list
v0.28.6 (#563) introduced the per-token takes-holder allow-list: an OAuth token
carries `permissions.takes_holders` and `takes_list` / `takes_search` /
`think.gather` filter take rows server-side via `WHERE t.holder = ANY($allowList)`
in both engines.
But take rows are stored in two places per the explicit contract in
`extract-takes.ts:5-13` ("markdown is canonical, the takes table is a derived
index"): the structured `takes` table AND inline in `pages.compiled_truth`
between `<!--- gbrain:takes:begin -->` markers as a markdown table whose `who`
column IS the holder. A read-only token whose `takes_holders` is `["world"]`
(the documented default-deny posture from migrate.ts:1221) can call
`get_page <slug>` and recover every non-`world` claim verbatim from the body —
private hunches, founder bets, non-public sourcing notes. `get_versions` has
the same shape: snapshots persist historical compiled_truth verbatim, so a
caller blocked at `get_page` falls through to /history.
The team already shipped a complementary fix in `chunkers/recursive.ts:49`
(stripTakesFence applied before the body is chunked, so `query` results don't
leak fence content). Migration v38 documents this as a "complementary fix" —
the page-CRUD surface was missed.
Fix strips the fence at the op layer when `ctx.takesHoldersAllowList` is set
(i.e. the remote MCP path). Local CLI callers leave the field unset and keep
seeing the full fence.
const visibleBody = ctx.takesHoldersAllowList
? { ...page, compiled_truth: stripTakesFence(page.compiled_truth) }
: page;
Same shape on `get_versions` over every snapshot in the array. Re-rendering
the fence with allow-list-filtered rows would require joining the takes table
per version_id and inverts the markdown-canonical contract; whole-fence strip
is the conservative posture that closes the leak. A future allow-list-aware
re-render is an additive change that won't break the contract pinned by these
tests.
Test coverage in `test/takes-mcp-allowlist.serial.test.ts`:
- get_page with allow-list strips fence; surrounding body kept.
- get_page without allow-list (local CLI) keeps fence (back-compat).
- get_page fuzzy resolution path also strips for remote tokens.
- get_versions with allow-list strips fence on every snapshot.
- get_versions without allow-list returns historical content intact.
The pre-fix R12 PoC reported `LEAKED garry hidden take? YES` and
`LEAKED brain hidden take? YES`; post-fix the same PoC reports `no` for both
holders and "bypass did not reproduce".
* Fix double-encoded jsonb in subagent_tool_executions breaking slug lookup
persistToolExecPending/Failed/Complete called JSON.stringify(input) before
passing to a $N::jsonb parameter. When input is already an object, this
produces a JSON string which ::jsonb stores as a jsonb scalar -- not a
jsonb object. Downstream queries like input->>slug then return NULL
because the operator does not traverse scalar strings.
Root cause fix: skip JSON.stringify when input is already a string.
Query fix: use COALESCE with (input #>> '{}')::jsonb->>slug fallback
to handle both old double-encoded rows and new properly-encoded rows.
Affects: dream cycle synthesize phase (pages_written always 0) and
patterns phase (same slug collection query).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(adapter/voyage): translate request/response between OpenAI-compat SDK and Voyage's actual contract
The @ai-sdk/openai-compatible package treats Voyage as if it were
OpenAI-shaped, but Voyage's /v1/embeddings endpoint diverges in three places
that combine into a hard-blocking incompatibility:
OUTBOUND request:
- 'encoding_format=float' (SDK default) is rejected; Voyage only accepts 'base64'
- 'dimensions' parameter (OpenAI name) is rejected; Voyage uses 'output_dimension'
INBOUND response:
- With encoding_format=base64, 'embedding' is returned as a base64 string,
but the SDK's Zod schema (openaiTextEmbeddingResponseSchema) expects an
'array of number'. The schema fails with 'Invalid JSON response' even
though the JSON is well-formed.
- 'usage' lacks 'prompt_tokens'; the schema requires it when usage is present.
Without this patch, ALL embedding requests to Voyage fail. Reproducible by
running 'gbrain put <slug> < text' with embedding_model=voyage:voyage-* and
any current voyage model (voyage-3-large, voyage-3, voyage-4-large).
Solution: pass a custom 'fetch' to createOpenAICompatible only when
recipe.id === 'voyage'. The fetch wrapper:
1. Forces encoding_format='base64' on outbound (Voyage's only accepted value)
2. Translates dimensions -> output_dimension on outbound
3. Drops Content-Length so the runtime recomputes from the mutated body
4. Decodes base64 embeddings to Float32 arrays on inbound (so the Zod schema
sees what it expects)
5. Synthesizes prompt_tokens from total_tokens when missing
This is a minimal, targeted fix. It only activates for Voyage and falls
through cleanly for all other providers. No public API changes.
* feat(dream): support .md files in transcript discovery
Transcript discovery only accepted .txt files. Many brain repos store
meeting transcripts and conversation logs as .md (markdown), which is
the natural format for brain content.
Changes:
- listTextFiles() now accepts both .txt and .md
- basename extraction handles both extensions for date inference
- readSingleTranscript() handles both extensions
No behavior change for existing .txt-only setups.
* fix(test): cast exitCode to unknown for TS strict-narrowing
TS narrows exitCode to null between declaration and assertion because
the mocked process.exit is behind `(process as any).exit`. The cast
preserves test intent without weakening the variable's type annotation.
Wave-side merge fix; ships alongside #688 (extract --dir default).
* fix(cli): add frontmatter + check-resolvable to CLI_ONLY_SELF_HELP
Companion to #634. Both commands have their own --help logic that prints
detailed usage with command-specific flags (e.g., --json, --fix, --strict
for check-resolvable). Without this, pr-634's generic short-circuit prints
"Usage: gbrain <cmd> - run gbrain --help for the full command list." and
the existing --help integration tests fail.
Verified: `gbrain frontmatter --help` and `gbrain check-resolvable --help`
now route to their handlers, which print full per-command usage and exit 0.
* fix(test): update discoverTranscripts test expectation for .md support
Companion to #708. The pre-#708 test asserted that .md files in the
session-corpus directory were skipped. Post-#708 they are discovered
alongside .txt. Renamed the test to 'skips non-txt non-md files' (uses
.pdf as the negative case) and added a positive .md discovery test that
pins #708's intended behavior.
* fix(skills): declare missing RESOLVER triggers in skill frontmatter
Companion to #718. The RESOLVER round-trip test (test/resolver.test.ts)
fuzzy-matches every RESOLVER.md trigger phrase against the target skill's
frontmatter triggers list. pr-718 added six new RESOLVER routings without
declaring matching triggers:
- media-ingest: 'PDF book', 'summarize this book', 'ingest it into my brain'
- article-enrichment: 'enriching the article', 'enrich the article', 'enrich pass'
- concept-synthesis: 'canon vs riff'
- perplexity-research: 'perplexity-research', 'surface new developments'
- academic-verify: 'Retraction Watch'
- voice-note-ingest: 'audio message'
Adds the missing triggers verbatim to each skill's frontmatter so the
round-trip invariant holds.
* chore: regenerate llms.txt + llms-full.txt after wave skill updates
* v0.30.3 release: bump VERSION + CHANGELOG entry
22-PR community fix wave with one P0 security upgrade (auth-code scope
escalation closed). 19 PRs landed across 5 lanes; 3 superseded by master
during cherry-pick; 1 deferred per E2 protocol (#681 architectural
conflict with v0.28 takes-holders); follow-up filed.
Headline fixes: #727 (auth-code scope-clamp, RFC 6749 §3.3 compliance),
#740/#751 (v0.29.1 PGLite migration connect), #741 (v39-v41 forward-
reference bootstrap), #757 (multi-source sourceId threading, closes
Postgres 21000), #728 (takes-fence redaction on remote reads).
See CHANGELOG.md for full per-PR attribution and decision history.
Co-Authored-By: lanceretter <lance@csatlanta.com>
Co-Authored-By: alexandreroumieu-codeapprentice <agency.aubergine.code@gmail.com>
Co-Authored-By: brandonlipman <brandon@offdeck.com>
Co-Authored-By: gus <gustavoraularagon@gmail.com>
Co-Authored-By: jeremyknows <jeremyknows@protonmail.com>
Co-Authored-By: Trevin Chow <trevin@trevinchow.com>
Co-Authored-By: WD <wd@WDdeMacBook-Pro.local>
Co-Authored-By: Federico Cachero <federicocachero.tango@gmail.com>
Co-Authored-By: Brandon Lipman <brandon@offdeck.com>
Co-Authored-By: joshsteinvc <josh@stein.vc>
Co-Authored-By: mgunnin <michael.gunnin@gmail.com>
Co-Authored-By: NineClaws Brain <joel@5nine64.com>
Co-Authored-By: joelwp <joel.phillips@gmail.com>
Co-Authored-By: Oscar <oscar@Mac-mini-de-Oscar.local>
* test(C6): regression test for #745 collectChildPutPageSlugs
Codex-mandated test gate (C6 from /codex review of v0.30.3 plan).
Pins behavior of collectChildPutPageSlugs() under both jsonb shapes:
- jsonb_typeof='object' (post-#745, normal write path)
- jsonb_typeof='string' (pre-#745 double-encoded, the bug shape)
Without this guard, a future regression of #745 would silently drop slugs:
child jobs finish, queue looks healthy, orchestrator writes nothing.
Worst on-call shape — silent failure with no alerting surface.
Adds an `__testing` namespace to src/core/cycle/synthesize.ts re-exporting
collectChildPutPageSlugs at unit-test granularity. Not part of the runtime
contract; matches the v0_29_1.ts `__testing` precedent for engine-internal
helpers.
* test(C8): #708 .md transcript discovery + self-consumption guard
Codex-mandated test gate (C8 from /codex review of v0.30.3 plan).
Pins three invariants for #708's broadening of transcript discovery:
1. .md files ARE discovered alongside .txt (the feature works).
2. Other extensions (.pdf, .doc, .json) are still SKIPPED.
3. v0.30.2's dream_generated frontmatter marker MUST guard .md files
against self-consumption — without this, every dream cycle would
loop on its own output indefinitely.
Adversarial cases: BOM + CRLF tolerance on .md frontmatter; the
--unsafe-bypass-dream-guard escape hatch for .md output; mixed .txt + .md
corpus dedup behavior pinned.
* test(C4): takes-fence redaction regression on get_page + get_versions
Codex-mandated test gate (C4 from /codex review of v0.30.3 plan).
Pins three privacy invariants for #728's fence-stripping in operations.ts:
1. Local CLI caller (no allow-list) sees full takes fence — operator
reads should preserve everything.
2. MCP-bound caller (allow-list set) sees compiled_truth with fence
STRIPPED on get_page AND get_versions.
3. Allow-list PRESENCE (not contents) flags MCP-bound identity. Even
a permissive ['world','garry','brain'] still strips, because the
typed read surface for takes is takes_list / takes_search, not
get_page or get_versions.
Lane 4 (#757 + #728) was the high-risk merge surface for this privacy
invariant. The test runs through dispatchToolCall to exercise the full
threading path (auth → context → handler → engine read → stripTakesFence)
so a future bad merge fails loudly at the conflict seam in operations.ts.
* test(C3): rewound-brain E2E for v39-v41 forward-reference bootstrap
Codex-mandated test gate (C3 from /codex review of v0.30.3 plan).
Pins the upgrade-path claim in the v0.30.3 release notes: brains stuck
at config.version < 39 (Postgres) or < 41 (PGLite) walk forward cleanly
through #741's bootstrap additions. Without this, the release note's
"old PGLite brains upgrade cleanly through v39-v41" was unproven.
Four cases:
1. pre-v39 (missing modality + embedding_image)
2. pre-v40 (missing emotional_weight + effective_date + effective_date_source)
3. pre-v41 (missing import_filename + salience_touched_at)
4. compounded pre-v34 wedge (v0.20 + v0.26.3 + v39-v41 all dropped at once)
Pattern follows test/e2e/v0_28_5-fix-wave.test.ts: build a fresh LATEST
brain, surgically rewind via DROP COLUMN CASCADE + UPDATE config.version,
then re-call initSchema and assert advancement to LATEST_VERSION with
the rewound columns restored. PGLite-only — Postgres-side bootstrap is
covered separately by test/e2e/postgres-bootstrap.test.ts.
* fix(test): rename migration-v0-29-1 to .serial.test.ts (CI lint)
CI's check-test-isolation lint flags the test for direct process.env.GBRAIN_HOME
mutation in beforeEach (rule R1: parallel-test-unsafe). The test is genuinely
env-coupled — it sets GBRAIN_HOME so loadConfig() inside the migration phases
finds the test fixture. Per CLAUDE.md ("When to quarantine instead of fix")
and the lint's own fix hint, env-coupled tests get renamed to *.serial.test.ts
to run in the serial bucket.
Verified: bash scripts/check-test-isolation.sh now reports OK; the renamed
test still runs green (1 pass / 0 fail, ~1.5s).
* fix(types): voyageCompatFetch — cast through unknown for Bun typeof fetch
CI's tsc --noEmit failed:
src/core/ai/gateway.ts(249,7): error TS2741: Property 'preconnect' is
missing in type '(input: RequestInfo | URL, init: RequestInit | ...) =>
Promise<Response>' but required in type 'typeof fetch'.
Bun's @types/bun extends the standard fetch type with a preconnect method
that arrow functions can't satisfy. The AI SDK only invokes the call
signature; the Bun extension surface is irrelevant to voyageCompatFetch's
behavior.
Cast through `unknown` (TS2352-safe pattern for cross-type-family casts)
with explicit param types on the arrow function. Comment names the exact
TS2741 the cast suppresses so a future maintainer can audit the choice.
Companion to #735 (Voyage encoding-format adapter) — the original PR
introduced voyageCompatFetch typed against typeof fetch; the wave-side
typecheck error was caught by CI on the assembled branch.
* fix(test/e2e): rename + update dream-cycle phase-order test
The test file said "v0.23 8-phase cycle" but ALL_PHASES has been 9
since v0.26.5 (added `purge`) and 10 since v0.29 (added
`recompute_emotional_weight` between patterns and embed). The
hardcoded 8-element array assertion was stale documentation.
Renamed the file from dream-cycle-eight-phase-pglite.test.ts to
dream-cycle-phase-order-pglite.test.ts to make the maintenance
contract explicit: this test pins the canonical phase sequence,
whatever its current length, against unintended reorderings or
removals.
Extracted EXPECTED_PHASES as a typed const so the assertion lives in
one place and TypeScript's CyclePhase narrowing catches typos in the
phase names.
* fix(test/e2e): cycle.test.ts expects 10 phases (v0.29 added recompute_emotional_weight)
Same root cause as dream-cycle-phase-order-pglite.test.ts: hardcoded
phase count assertion drifted behind ALL_PHASES growth.
Phase history:
v0.23 = 8 phases
v0.26.5 = 9 (added `purge` last)
v0.29 = 10 (added `recompute_emotional_weight` between patterns and embed)
* fix(test/e2e): scope GBRAIN_HOME to tmpdir for Doctor Command tests
`gbrain doctor`'s minions_migration check reads
`~/.gbrain/migrations/completed.jsonl` to detect half-installed
migrations. Pre-fix the test inherited the developer's local
$HOME, so stale partial entries from in-flight workspaces (e.g.
v0.31.0 in santiago) made the check fail and the test exit 1 —
masking real DB-health failures.
Added per-describe-block `gbrainHome` tmpdir, threaded through
`cliEnv()` so all spawned gbrain CLI calls in this block read a
hermetic, empty migrations ledger. Cleanup in afterAll.
* fix(claw-test): pass --dir explicitly to extract phase (companion to #688)
Pre-#688 `gbrain extract` defaulted to cwd. Post-#688 it requires
either a configured fs source or explicit --dir, otherwise it errors
out: "No brain directory configured."
The claw-test scripted scenarios run `gbrain init --pglite` in their
install_brain phase, which doesn't register a fs source. So the
extract phase needs --dir <brainDir> explicitly. Skip the extract
phase entirely when the scenario has no brain dir.
Captured brainDir at the import-phase site so it's reusable by extract.
* fix(preferences): route migration ledger paths through gbrainPath()
Pre-fix, preferences.ts used `$HOME/.gbrain` directly via its own
`home()` helper. Tests that set `process.env.HOME = tmpdir`
expecting hermetic isolation worked — but tests that set
`GBRAIN_HOME = tmpdir` (the documented override per
`src/core/config.ts`) didn't, because preferences ignored it.
Routed prefsDir(), prefsPath(), migrationsDir(), and
completedJsonlPath() through gbrainPath() (which honors
GBRAIN_HOME, falling back to homedir() when unset). The legacy
home() helper stays for any future code path that wants $HOME
specifically.
Updated three tests that mutated process.env.HOME to also mutate
GBRAIN_HOME so the same test body works against the new contract:
test/preferences.test.ts, test/migration-resume.test.ts,
test/e2e/migration-flow.test.ts.
* release: rename version slot to 0.31.1.1-fixwave
Originally bumped to 0.31.2 during the master merge to stay strictly
monotonic. Garry called the slot back to `0.31.1.1-fixwave` to
communicate intent: this is a fix wave on top of v0.31.1, not a new
minor or patch slot. The next regular release slot (v0.31.2) stays
free for in-flight feature work.
Format check:
- bun install accepts the literal version (verified)
- compareVersions() in src/commands/migrations/index.ts splits on
'.' and parseInt's each segment, taking only the first 3. So
'0.31.1.1-fixwave' compares as [0,31,1] = equal to '0.31.1' for
migration-ordering purposes. Wave has no new schema migrations,
so equality is fine.
- Compares stable to 0.31.1 in the migration runner; later versions
(0.31.2, 0.32.x, etc.) sort strictly above as normal.
Updated:
- VERSION
- package.json (with bun.lock refresh)
- CHANGELOG.md entry header + 'To take advantage of' block + 'For
contributors' reference
- llms.txt + llms-full.txt regenerated to match
---------
Co-authored-by: lanceretter <lance@csatlanta.com>
Co-authored-by: Oscar <oscar@Mac-mini-de-Oscar.local>
Co-authored-by: WD <wd@WDdeMacBook-Pro.local>
Co-authored-by: gus <gustavoraularagon@gmail.com>
Co-authored-by: Trevin Chow <trevin@trevinchow.com>
Co-authored-by: Brandon Lipman <brandon@offdeck.com>
Co-authored-by: Federico Cachero <federicocachero.tango@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Josh Stein <josh@threshold.vc>
Co-authored-by: Matt Gunnin <mgunnin@esports.one>
Co-authored-by: Michael Dela Cruz <adobobro@mac.lan>
Co-authored-by: Jeremy Knows <jeremy@veefriends.com>
Co-authored-by: joelwp <joel.phillips@gmail.com>
Co-authored-by: NineClaws Brain <joel@5nine64.com>
Co-authored-by: alexandreroumieu-codeapprentice <agency.aubergine.code@gmail.com>
Co-authored-by: jeremyknows <jeremyknows@protonmail.com>
Co-authored-by: joshsteinvc <josh@stein.vc>
Co-authored-by: mgunnin <michael.gunnin@gmail.com>
1437 lines
61 KiB
TypeScript
1437 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,
|
|
};
|
|
}
|
|
|
|
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);
|
|
});
|