mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* fix(subagent): bind Anthropic SDK messages.create() correctly The makeSubagentHandler was casting `new Anthropic()` directly to MessagesClient, but MessagesClient.create() maps to sdk.messages.create(), not sdk.create(). Every subagent job immediately died with: client.create is not a function Fix: wrap the SDK instance so .create() delegates to .messages.create() with proper `this` binding via .bind(sdk.messages). Discovered on first production run of gbrain agent against Supabase. Co-Authored-By: Wintermute <wintermute@openclaw.ai> * chore(ci): add typescript typecheck to test pipeline + clean up baseline errors Root cause infra gap that let the v0.16.0 subagent bug ship: CI ran only `bun test`, which transpiles types without checking them. Type errors only surfaced at runtime, in production. Changes: - Add `typescript` devDep and a `typecheck` npm script (`tsc --noEmit`). - Chain `bun run typecheck` into `bun run test` so developers get the same pipeline locally that CI runs. - Flip `.github/workflows/test.yml` to invoke `bun run test` (the npm script, including typecheck) instead of `bun test` (runner only). - Clean up 100+ pre-existing type errors across 30+ files so the first run of `tsc --noEmit` is green. Root causes were: - `databaseUrl` → `database_url` rename drift in test fixtures (9 files) - `PageType` union missing `'meeting'` / `'note'` entries that are already used in both src and tests (link-extraction.ts comments acknowledged the gap) - `GBrainConfig.storage` field never declared despite being read in files.ts and operations.ts - `ErrorCode` union missing `'permission_denied'` - `OrchestratorOpts` shape changed; test callers not updated - Dead-code comparisons in migration orchestrators against narrowed status types - postgres.js `Row`-callback type drift on several `.map()` calls - Buffer-as-BodyInit assignment in supabase.ts (real but non-fatal runtime bug; Uint8Array slice works and is type-correct) - Various `as X` single-step casts that now need `as unknown as X` per TS's stricter structural-conversion rules - Bump `beforeAll` hook timeout to 30s on four PGLite-heavy tests that were flaky under parallel test execution: wait-for-completion, extract-fs, e2e/search-quality, e2e/graph-quality. All pass in isolation; timeouts only happened when dozens of PGLite instances init'd simultaneously. The new CI pipeline now fails on any type error across src/ or test/, giving us the compile-time regression guard the subagent fix depends on. * fix(subagent): bind Anthropic SDK messages.create() correctly Shipped bug: v0.16.0 cast `new Anthropic()` to `MessagesClient`, but `.create()` lives at `sdk.messages.create`, not on the top-level client. Every subagent job in production died on first LLM call with `client.create is not a function`. Discovered on the first `gbrain agent run` against Supabase. Fix: assign `sdk.messages` directly to the `MessagesClient` slot. `sdk.messages` IS the object with a callable `.create()`; the original bug was picking the wrong entry point on the SDK. No helper, no wrapper, no `.bind()` — JS method-call semantics preserve `this` at the call site because `subagent.ts:336` invokes `client.create(...)` with `client === sdk.messages`. The one-line assignment also typechecks cleanly against the existing `MessagesClient` interface (SDK's first `create` overload: `(MessageCreateParamsNonStreaming, Core.RequestOptions?) => APIPromise<Message>` is assignable structurally). This gives us compile-time regression protection: anyone reverting to `new Anthropic()` would fail tsc because `Anthropic` has no top-level `.create`. (The companion chore commit puts `tsc --noEmit` in CI so this guard is enforced.) Also adds a `makeAnthropic?: () => Anthropic` dep-injection seam so the factory default construction branch is testable without real API calls. Regression test drives one handler turn through a fake SDK, asserting `sdk.messages.create` is actually called. If someone later reverts to `new Anthropic()`, both guards fire: tsc fails AND the test fails. Co-Authored-By: Wintermute <wintermute@garrytan.com> * chore(tests): add bunfig.toml + 60s hook timeouts to stabilize PGLite-heavy suites After turning on tsc in CI (previous commit), running the full `bun run test` suite in one shot triggered flaky `beforeEach/afterEach hook timed out` failures on 8+ test files. Every failure traced to PGLite WASM init contention when many test files spin up fresh PGLite instances in parallel; each one alone passes in isolation. - `bunfig.toml` sets the global test hook timeout to 60s (default is 5s), covering every test file without per-file edits. - Individual `beforeAll(fn, 60_000)` / `beforeEach(fn, 15_000)` calls on the 8 tests that flaked most stay in place as explicit safety nets so a future bunfig config change doesn't silently re-introduce the flake. Result: 1997 pass, 0 fail on `bun run test` (117 tests added since the prior baseline by picking up typecheck-gated passes). No infrastructure flake tolerated in CI. * chore: bump version and changelog (v0.16.3) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Wintermute <wintermute@garrytan.com> Co-authored-by: Wintermute <wintermute@openclaw.ai> Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
315 lines
11 KiB
TypeScript
315 lines
11 KiB
TypeScript
/**
|
|
* E2E test for the v0.10.1 knowledge graph layer.
|
|
*
|
|
* Runs the full pipeline against in-memory PGLite (no API keys, no external DB).
|
|
* 1. Seed pages with entity refs and timeline content
|
|
* 2. Run link-extract + timeline-extract
|
|
* 3. Verify graph populated
|
|
* 4. Test auto-link via put_page operation handler
|
|
* 5. Test reconciliation (edit page, stale links removed)
|
|
* 6. Test graph-query traversal
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
|
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
|
|
import { runExtract } from '../../src/commands/extract.ts';
|
|
import { operationsByName } from '../../src/core/operations.ts';
|
|
import type { OperationContext } from '../../src/core/operations.ts';
|
|
|
|
let engine: PGLiteEngine;
|
|
|
|
beforeAll(async () => {
|
|
engine = new PGLiteEngine();
|
|
await engine.connect({});
|
|
await engine.initSchema();
|
|
}, 60_000);
|
|
|
|
afterAll(async () => {
|
|
await engine.disconnect();
|
|
});
|
|
|
|
async function truncateAll() {
|
|
for (const t of ['content_chunks', 'links', 'tags', 'raw_data', 'timeline_entries', 'page_versions', 'ingest_log', 'pages']) {
|
|
await (engine as any).db.exec(`DELETE FROM ${t}`);
|
|
}
|
|
}
|
|
|
|
function makeContext(): OperationContext {
|
|
return {
|
|
engine,
|
|
config: { engine: 'pglite' } as any,
|
|
logger: { info: () => {}, warn: () => {}, error: () => {} },
|
|
dryRun: false,
|
|
};
|
|
}
|
|
|
|
describe('E2E graph quality (v0.10.1 pipeline)', () => {
|
|
beforeEach(truncateAll, 15_000);
|
|
|
|
test('full pipeline: seed -> link-extract -> timeline-extract -> verify', async () => {
|
|
// Seed 5 pages with entity refs and timeline content.
|
|
await engine.putPage('people/alice', {
|
|
type: 'person', title: 'Alice',
|
|
compiled_truth: 'Alice is the CEO of [Acme](companies/acme).',
|
|
timeline: '- **2026-01-15** | Joined as CEO\n- **2026-02-20** | Closed Series A',
|
|
});
|
|
await engine.putPage('people/bob', {
|
|
type: 'person', title: 'Bob',
|
|
compiled_truth: 'Bob is a YC partner who invested in [Acme](companies/acme).',
|
|
timeline: '- **2026-03-01** | Wrote check to Acme',
|
|
});
|
|
await engine.putPage('companies/acme', {
|
|
type: 'company', title: 'Acme',
|
|
compiled_truth: '',
|
|
timeline: '- **2026-01-01** | Founded',
|
|
});
|
|
await engine.putPage('meetings/standup', {
|
|
type: 'meeting', title: 'Standup',
|
|
compiled_truth: 'Attendees: [Alice](people/alice), [Bob](people/bob).',
|
|
timeline: '- **2026-04-01** | Met at YC office',
|
|
});
|
|
|
|
// Run extractions.
|
|
await runExtract(engine, ['links', '--source', 'db']);
|
|
await runExtract(engine, ['timeline', '--source', 'db']);
|
|
|
|
// Verify graph populated.
|
|
const stats = await engine.getStats();
|
|
expect(stats.link_count).toBeGreaterThan(0);
|
|
expect(stats.timeline_entry_count).toBeGreaterThan(0);
|
|
|
|
// Verify typed link inference.
|
|
const aliceLinks = await engine.getLinks('people/alice');
|
|
const acmeLink = aliceLinks.find(l => l.to_slug === 'companies/acme');
|
|
expect(acmeLink?.link_type).toBe('works_at');
|
|
|
|
const bobLinks = await engine.getLinks('people/bob');
|
|
const bobAcme = bobLinks.find(l => l.to_slug === 'companies/acme');
|
|
expect(bobAcme?.link_type).toBe('invested_in');
|
|
|
|
const meetingLinks = await engine.getLinks('meetings/standup');
|
|
expect(meetingLinks.every(l => l.link_type === 'attended')).toBe(true);
|
|
});
|
|
|
|
test('auto-link via put_page operation handler', async () => {
|
|
// Seed target pages first.
|
|
await engine.putPage('people/alice', { type: 'person', title: 'Alice', compiled_truth: '', timeline: '' });
|
|
await engine.putPage('companies/acme', { type: 'company', title: 'Acme', compiled_truth: '', timeline: '' });
|
|
|
|
// Use put_page operation (not engine.putPage directly) so the auto-link
|
|
// post-hook fires.
|
|
const putOp = operationsByName['put_page'];
|
|
expect(putOp).toBeDefined();
|
|
const result = await putOp.handler(makeContext(), {
|
|
slug: 'meetings/auto',
|
|
content: `---
|
|
type: meeting
|
|
title: Auto Meeting
|
|
---
|
|
|
|
Attendees: [Alice](people/alice). Discussed [Acme](companies/acme).
|
|
`,
|
|
});
|
|
|
|
// The response should include auto_links results.
|
|
expect((result as any).auto_links).toBeDefined();
|
|
const autoLinks = (result as any).auto_links;
|
|
expect(autoLinks.created).toBeGreaterThan(0);
|
|
expect(autoLinks.errors).toBe(0);
|
|
|
|
// Verify links actually exist in DB.
|
|
const links = await engine.getLinks('meetings/auto');
|
|
expect(links.length).toBe(2);
|
|
expect(new Set(links.map(l => l.to_slug))).toEqual(new Set(['people/alice', 'companies/acme']));
|
|
});
|
|
|
|
test('auto-link reconciliation: edit page removes stale links', async () => {
|
|
await engine.putPage('people/alice', { type: 'person', title: 'Alice', compiled_truth: '', timeline: '' });
|
|
await engine.putPage('people/bob', { type: 'person', title: 'Bob', compiled_truth: '', timeline: '' });
|
|
|
|
const putOp = operationsByName['put_page'];
|
|
|
|
// First write: links to Alice.
|
|
await putOp.handler(makeContext(), {
|
|
slug: 'notes/test',
|
|
content: `---
|
|
type: concept
|
|
title: Test Note
|
|
---
|
|
|
|
I met [Alice](people/alice) today.
|
|
`,
|
|
});
|
|
|
|
let links = await engine.getLinks('notes/test');
|
|
expect(links.length).toBe(1);
|
|
expect(links[0].to_slug).toBe('people/alice');
|
|
|
|
// Second write: removes Alice ref, adds Bob ref.
|
|
const result = await putOp.handler(makeContext(), {
|
|
slug: 'notes/test',
|
|
content: `---
|
|
type: concept
|
|
title: Test Note
|
|
---
|
|
|
|
Now I'm meeting with [Bob](people/bob).
|
|
`,
|
|
});
|
|
|
|
expect((result as any).auto_links.removed).toBe(1);
|
|
expect((result as any).auto_links.created).toBe(1);
|
|
|
|
links = await engine.getLinks('notes/test');
|
|
expect(links.length).toBe(1);
|
|
expect(links[0].to_slug).toBe('people/bob');
|
|
});
|
|
|
|
test('auto-timeline: put_page extracts + inserts timeline entries', async () => {
|
|
const putOp = operationsByName['put_page'];
|
|
const result = await putOp.handler(makeContext(), {
|
|
slug: 'people/dana',
|
|
content: `---
|
|
type: person
|
|
title: Dana
|
|
---
|
|
|
|
Dana is a founder.
|
|
|
|
## Timeline
|
|
|
|
- **2026-03-15** | Shipped v1.0
|
|
- **2026-04-02** | Closed seed round
|
|
`,
|
|
});
|
|
|
|
expect((result as any).auto_timeline).toBeDefined();
|
|
expect((result as any).auto_timeline.created).toBe(2);
|
|
|
|
const entries = await engine.getTimeline('people/dana');
|
|
expect(entries.length).toBe(2);
|
|
const dates = entries.map((e: any) => {
|
|
const d = e.date instanceof Date ? e.date.toISOString().slice(0, 10) : String(e.date).slice(0, 10);
|
|
return d;
|
|
}).sort();
|
|
expect(dates).toEqual(['2026-03-15', '2026-04-02']);
|
|
});
|
|
|
|
test('auto-timeline is idempotent: re-write does not duplicate entries', async () => {
|
|
const putOp = operationsByName['put_page'];
|
|
const content = `---
|
|
type: person
|
|
title: Eve
|
|
---
|
|
|
|
## Timeline
|
|
|
|
- **2026-03-15** | Shipped
|
|
`;
|
|
await putOp.handler(makeContext(), { slug: 'people/eve', content });
|
|
await putOp.handler(makeContext(), { slug: 'people/eve', content });
|
|
|
|
const entries = await engine.getTimeline('people/eve');
|
|
expect(entries.length).toBe(1);
|
|
});
|
|
|
|
test('auto-timeline respects auto_timeline=false config', async () => {
|
|
await engine.setConfig('auto_timeline', 'false');
|
|
try {
|
|
const putOp = operationsByName['put_page'];
|
|
const result = await putOp.handler(makeContext(), {
|
|
slug: 'people/frank',
|
|
content: `---
|
|
type: person
|
|
title: Frank
|
|
---
|
|
|
|
## Timeline
|
|
|
|
- **2026-03-15** | Something happened
|
|
`,
|
|
});
|
|
expect((result as any).auto_timeline).toBeUndefined();
|
|
const entries = await engine.getTimeline('people/frank');
|
|
expect(entries.length).toBe(0);
|
|
} finally {
|
|
await engine.setConfig('auto_timeline', 'true');
|
|
}
|
|
});
|
|
|
|
test('auto-link respects auto_link=false config', async () => {
|
|
await engine.setConfig('auto_link', 'false');
|
|
try {
|
|
await engine.putPage('people/alice', { type: 'person', title: 'Alice', compiled_truth: '', timeline: '' });
|
|
const putOp = operationsByName['put_page'];
|
|
const result = await putOp.handler(makeContext(), {
|
|
slug: 'notes/disabled',
|
|
content: `---
|
|
type: concept
|
|
title: Disabled Auto Link
|
|
---
|
|
|
|
Mention of [Alice](people/alice).
|
|
`,
|
|
});
|
|
|
|
// No auto_links field when disabled (we skip the helper entirely).
|
|
expect((result as any).auto_links).toBeUndefined();
|
|
|
|
const links = await engine.getLinks('notes/disabled');
|
|
expect(links.length).toBe(0);
|
|
} finally {
|
|
await engine.setConfig('auto_link', 'true');
|
|
}
|
|
});
|
|
|
|
test('graph-query end-to-end: traversePaths returns expected edges', async () => {
|
|
await engine.putPage('people/alice', { type: 'person', title: 'Alice', compiled_truth: '', timeline: '' });
|
|
await engine.putPage('people/bob', { type: 'person', title: 'Bob', compiled_truth: '', timeline: '' });
|
|
await engine.putPage('companies/acme', { type: 'company', title: 'Acme', compiled_truth: '', timeline: '' });
|
|
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
|
|
await engine.addLink('people/bob', 'companies/acme', '', 'invested_in');
|
|
|
|
// "Who works at Acme?" -> direction in, type works_at.
|
|
const paths = await engine.traversePaths('companies/acme', {
|
|
direction: 'in', linkType: 'works_at', depth: 1,
|
|
});
|
|
expect(paths.length).toBe(1);
|
|
expect(paths[0].from_slug).toBe('people/alice');
|
|
expect(paths[0].link_type).toBe('works_at');
|
|
});
|
|
|
|
test('search backlink boost: well-connected pages rank higher', async () => {
|
|
// Create 3 pages all matching a search term, but with different inbound link counts.
|
|
await engine.putPage('topic/popular', {
|
|
type: 'concept', title: 'Popular Topic',
|
|
compiled_truth: 'This is the popular topic about widgets.',
|
|
timeline: '',
|
|
});
|
|
await engine.putPage('topic/medium', {
|
|
type: 'concept', title: 'Medium Topic',
|
|
compiled_truth: 'This is a medium topic about widgets.',
|
|
timeline: '',
|
|
});
|
|
await engine.putPage('topic/obscure', {
|
|
type: 'concept', title: 'Obscure Topic',
|
|
compiled_truth: 'This is an obscure topic about widgets.',
|
|
timeline: '',
|
|
});
|
|
// Create inbound link references so each topic gets a backlink count.
|
|
for (let i = 0; i < 5; i++) {
|
|
await engine.putPage(`ref/popular-${i}`, {
|
|
type: 'concept', title: `Ref ${i}`, compiled_truth: '', timeline: '',
|
|
});
|
|
await engine.addLink(`ref/popular-${i}`, 'topic/popular', '', 'mentions');
|
|
}
|
|
await engine.addLink('ref/popular-0', 'topic/medium', '', 'mentions');
|
|
|
|
// Verify backlink counts.
|
|
const counts = await engine.getBacklinkCounts(['topic/popular', 'topic/medium', 'topic/obscure']);
|
|
expect(counts.get('topic/popular')).toBe(5);
|
|
expect(counts.get('topic/medium')).toBe(1);
|
|
expect(counts.get('topic/obscure')).toBe(0);
|
|
});
|
|
});
|