Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(e2e): harden suite — kill flakes, no-op assertions, cross-test coupling (#1704)
Aurora Capital2c96787867e7
diff --git a/test/e2e/doctor-progress.test.ts b/test/e2e/doctor-progress.test.tsindex 9f3bb70925..f318f52e88 100644--- a/test/e2e/doctor-progress.test.ts+++ b/test/e2e/doctor-progress.test.ts@@ -20,6 +20,10 @@ import {const skip = !hasDatabase();const describeE2E = skip ? describe.skip : describe;+if (skip) {+ console.log('Skipping E2E doctor --progress-json tests (DATABASE_URL not set)');+}+const CLI = join(import.meta.dir, '..', '..', 'src', 'cli.ts');describeE2E('gbrain doctor --progress-json (E2E)', () => {diff --git a/test/e2e/graph-quality.test.ts b/test/e2e/graph-quality.test.tsindex 8d99addb6f..12a1736df9 100644--- a/test/e2e/graph-quality.test.ts+++ b/test/e2e/graph-quality.test.ts@@ -29,9 +29,15 @@ afterAll(async () => {});async function truncateAll() {- for (const t of ['content_chunks', 'links', 'tags', 'raw_data', 'timeline_entries', 'page_versions', 'ingest_log', 'pages']) {+ for (const t of ['content_chunks', 'links', 'tags', 'raw_data', 'timeline_entries', 'page_versions', 'ingest_log', 'config', 'pages']) {await (engine as any).db.exec(`DELETE FROM ${t}`);}+ // Re-seed the two config keys this file touches back to their documented+ // defaults (both default to ON). This makes every test deterministic even if+ // an earlier test threw before its finally restored auto_link/auto_timeline,+ // and even though absent-key already resolves truthy via isAuto*Enabled.+ await engine.setConfig('auto_link', 'true');+ await engine.setConfig('auto_timeline', 'true');}function makeContext(): OperationContext {@@ -77,10 +83,12 @@ describe('E2E graph quality (v0.10.1 pipeline)', () => {await runExtract(engine, ['links', '--source', 'db']);await runExtract(engine, ['timeline', '--source', 'db']);- // Verify graph populated.+ // Verify graph populated. Concrete floors derived from the seeded fixtures:+ // resolvable entity refs: alice->acme, bob->acme, standup->alice, standup->bob = 4+ // timeline lines: alice(2) + bob(1) + acme(1) + standup(1) = 5const stats = await engine.getStats();- expect(stats.link_count).toBeGreaterThan(0);- expect(stats.timeline_entry_count).toBeGreaterThan(0);+ expect(stats.link_count).toBeGreaterThanOrEqual(4);+ expect(stats.timeline_entry_count).toBeGreaterThanOrEqual(5);// Verify typed link inference.const aliceLinks = await engine.getLinks('people/alice');@@ -91,7 +99,16 @@ describe('E2E graph quality (v0.10.1 pipeline)', () => {const bobAcme = bobLinks.find(l => l.to_slug === 'companies/acme');expect(bobAcme?.link_type).toBe('invested_in');+ // The standup meeting references both Alice and Bob as attendees. Assert the+ // exact attendee edges are present and typed 'attended' (a plain .every()+ // would silently pass if a meeting->company edge were misclassified or if the+ // attendee edges were missing entirely).const meetingLinks = await engine.getLinks('meetings/standup');+ const attended = new Set(+ meetingLinks.filter(l => l.link_type === 'attended').map(l => l.to_slug),+ );+ expect(attended.has('people/alice')).toBe(true);+ expect(attended.has('people/bob')).toBe(true);expect(meetingLinks.every(l => l.link_type === 'attended')).toBe(true);});@@ -118,7 +135,9 @@ 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);+ // The page references exactly two seeded, resolvable targets (Alice + Acme),+ // so exactly two links are created.+ expect(autoLinks.created).toBe(2);expect(autoLinks.errors).toBe(0);// Verify links actually exist in DB.@@ -283,6 +302,53 @@ Mention of [Alice](people/alice).expect(paths[0].link_type).toBe('works_at');});+ test('graph-query traversal: direction out and both, plus depth:2 multi-hop', async () => {+ // Seed a 2-hop chain: alice -works_at-> acme -partnered_with-> beta.+ await engine.putPage('people/alice', { type: 'person', title: 'Alice', compiled_truth: '', timeline: '' });+ await engine.putPage('companies/acme', { type: 'company', title: 'Acme', compiled_truth: '', timeline: '' });+ await engine.putPage('companies/beta', { type: 'company', title: 'Beta', compiled_truth: '', timeline: '' });+ await engine.addLink('people/alice', 'companies/acme', '', 'works_at');+ await engine.addLink('companies/acme', 'companies/beta', '', 'partnered_with');++ // direction:'out' from alice, depth 1 -> only the first hop.+ const out1 = await engine.traversePaths('people/alice', { direction: 'out', depth: 1 });+ expect(out1.length).toBe(1);+ expect(out1[0].from_slug).toBe('people/alice');+ expect(out1[0].to_slug).toBe('companies/acme');+ expect(out1[0].depth).toBe(1);++ // depth:2 -> both hops, depths 1 and 2.+ const out2 = await engine.traversePaths('people/alice', { direction: 'out', depth: 2 });+ const out2Edges = new Set(out2.map(p => `${p.from_slug}->${p.to_slug}@${p.depth}`));+ expect(out2Edges.has('people/alice->companies/acme@1')).toBe(true);+ expect(out2Edges.has('companies/acme->companies/beta@2')).toBe(true);+ expect(out2.length).toBe(2);++ // direction:'both' from acme depth 1 -> sees the inbound edge from alice AND+ // the outbound edge to beta. Edges keep their natural from->to orientation.+ const both = await engine.traversePaths('companies/acme', { direction: 'both', depth: 1 });+ const bothEdges = new Set(both.map(p => `${p.from_slug}->${p.to_slug}`));+ expect(bothEdges.has('people/alice->companies/acme')).toBe(true);+ expect(bothEdges.has('companies/acme->companies/beta')).toBe(true);+ });++ test('graph-query cycle safety: A->B->A terminates and returns bounded results', 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: '' });+ // Create a 2-cycle: alice -> bob -> alice.+ await engine.addLink('people/alice', 'people/bob', '', 'knows');+ await engine.addLink('people/bob', 'people/alice', '', 'knows');++ // High depth must NOT loop forever; the visited-set guard bounds the walk.+ const paths = await engine.traversePaths('people/alice', { direction: 'out', depth: 100 });+ const edges = new Set(paths.map(p => `${p.from_slug}->${p.to_slug}`));+ // Both edges of the cycle are reachable exactly once.+ expect(edges.has('people/alice->people/bob')).toBe(true);+ expect(edges.has('people/bob->people/alice')).toBe(true);+ // Bounded: there are only two edges in the graph, so no path explosion.+ expect(paths.length).toBe(2);+ });+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', {diff --git a/test/e2e/jsonb-roundtrip.test.ts b/test/e2e/jsonb-roundtrip.test.tsindex 2b1b691990..9abb276f77 100644--- a/test/e2e/jsonb-roundtrip.test.ts+++ b/test/e2e/jsonb-roundtrip.test.ts@@ -21,6 +21,10 @@ import { hasDatabase, setupDB, teardownDB, getEngine, getConn } from './helpers.const skip = !hasDatabase();const describeE2E = skip ? describe.skip : describe;+if (skip) {+ console.log('Skipping E2E JSONB roundtrip tests (DATABASE_URL not set)');+}+describeE2E('E2E: JSONB roundtrip — v0.12.1 reliability wave', () => {beforeAll(async () => { await setupDB(); });afterAll(async () => { await teardownDB(); });diff --git a/test/e2e/mcp.test.ts b/test/e2e/mcp.test.tsindex 530f3c036a..1f985514ae 100644--- a/test/e2e/mcp.test.ts+++ b/test/e2e/mcp.test.ts@@ -56,6 +56,7 @@ describe('E2E: MCP Tool Generation', () => {expect(names).toContain('get_health');expect(names).toContain('sync_brain');expect(names).toContain('file_upload');+ expect(names).toContain('find_orphans');});test('MCP server module can be imported', async () => {diff --git a/test/e2e/mechanical.test.ts b/test/e2e/mechanical.test.tsindex 8d6c525685..3b21e1e92f 100644--- a/test/e2e/mechanical.test.ts+++ b/test/e2e/mechanical.test.ts@@ -175,6 +175,15 @@ describeE2E('E2E: Search', () => {for (const [query, score] of Object.entries(scores)) {console.log(` "${query}": ${(score * 100).toFixed(0)}%`);}++ // Guard value: every known-item query must surface at least one ground-truth+ // doc in the top 5. This is a deliberately loose floor (not a tuned P@5+ // threshold) — it catches a total keyword-retrieval regression without+ // breaking on every scoring/fixture tweak. Without it this test asserted+ // nothing and a 0%-precision result passed silently.+ for (const [query, score] of Object.entries(scores)) {+ expect(score).toBeGreaterThan(0);+ }});});@@ -205,10 +214,22 @@ describeE2E('E2E: Links', () => {}, 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;+ // Self-contained: do not depend on a prior test's add_link. add_link is+ // idempotent (ON CONFLICT DO NOTHING), so re-adding here is safe whether or+ // not the round-trip test ran first, and the test no longer false-passes or+ // false-fails based on describe-block ordering.+ await callOp('add_link', {+ from: 'people/sarah-chen',+ to: 'companies/novamind',+ link_type: 'founded',+ });++ 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);+ // Content assertion, not just shape: the linked company must be reachable.+ const reachable = graph.map((n: any) => n.slug ?? n.to_slug ?? n.to_page_slug);+ expect(reachable).toContain('companies/novamind');});test('remove_link removes the link', async () => {@@ -469,8 +490,14 @@ describeE2E('E2E: Admin', () => {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');+ // Value bounds, not just types: page_count must match the fixture inventory+ // and embed_coverage is a 0..1 fraction (src/commands/doctor.ts multiplies+ // by 100 and compares to 0.9). Type-only checks let embed_coverage: -9999+ // through; these catch a genuinely broken health payload.+ expect(health.page_count).toBe(16);+ expect(Number.isFinite(health.embed_coverage)).toBe(true);+ expect(health.embed_coverage).toBeGreaterThanOrEqual(0);+ expect(health.embed_coverage).toBeLessThanOrEqual(1);});});@@ -488,7 +515,17 @@ describeE2E('E2E: Chunks & Resolution', () => {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();+ // Content + ordering, not just truthiness (a whitespace-only chunk is truthy):+ // every chunk has real text and a numeric index, the indexes are+ // non-decreasing in return order, and the page's own name appears somewhere.+ for (const c of chunks) {+ expect(typeof c.chunk_text).toBe('string');+ expect(c.chunk_text.trim().length).toBeGreaterThan(0);+ expect(typeof c.chunk_index).toBe('number');+ }+ const indexes = chunks.map((c: any) => c.chunk_index);+ expect(indexes).toEqual([...indexes].sort((x, y) => x - y));+ expect(chunks.some((c: any) => c.chunk_text.includes('Sarah'))).toBe(true);}, 30_000);test('resolve_slugs finds partial match', async () => {@@ -662,9 +699,29 @@ describeE2E('E2E: file_list LIMIT enforcement', () => {}, 30_000);test('file_list without slug also respects LIMIT 100', async () => {- // The 150 rows from the previous test are still in the DB+ // Self-sufficient: seed our own >100 rows rather than relying on the+ // previous test's 150 rows surviving in the DB. A bun reorder, a focused+ // `-t` run, or a failure mid-insert in the prior test would otherwise leave+ // this asserting against an indeterminate row count.+ const sql = getConn();+ const seedSlug = 'test-limit-noslug';+ await sql`+ INSERT INTO pages (slug, title, type, compiled_truth, frontmatter)+ VALUES (${seedSlug}, ${'Test Limit NoSlug'}, ${'note'}, ${'body'}, ${'{}'}::jsonb)+ ON CONFLICT (source_id, slug) DO NOTHING+ `;+ for (let i = 0; i < 120; i++) {+ await sql`+ INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)+ VALUES (${seedSlug}, ${'nf-' + String(i).padStart(3, '0') + '.txt'}, ${seedSlug + '/nf-' + i + '.txt'}, ${'text/plain'}, ${100}, ${'nhash-' + i}, ${'{}'}::jsonb)+ ON CONFLICT (storage_path) DO NOTHING+ `;+ }+ const total = await sql`SELECT count(*)::int AS n FROM files`;+ expect(Number(total[0].n)).toBeGreaterThan(100); // cap is actually exercised+const files = await callOp('file_list', {}) as any[];- expect(files.length).toBeLessThanOrEqual(100);+ expect(files.length).toBe(100);});});diff --git a/test/e2e/migration-flow.test.ts b/test/e2e/migration-flow.test.tsindex 7ba06eebfe..c0726e4be6 100644--- a/test/e2e/migration-flow.test.ts+++ b/test/e2e/migration-flow.test.ts@@ -78,6 +78,19 @@ function freshTempHome(label: string) {return dir;}+// Restore HOME/PATH to the captured originals. Called from each test's+// `finally` so a throw mid-test can never leave HOME/PATH pointed at a temp+// dir for the rest of the bun process (which would silently break unrelated+// suites that read HOME). PATH keeps the shim prepended because the+// module-level shim install is what subsequent tests in this suite rely on;+// afterAll does the final teardown to the pristine origPath.+function restoreHomePath() {+ if (origHome === undefined) delete process.env.HOME;+ else process.env.HOME = origHome;+ if (origPath === undefined) delete process.env.PATH;+ else process.env.PATH = `${fakeBinDir}:${origPath ?? ''}`;+}+beforeAll(() => {if (SKIP) {console.log('[migration-flow.e2e] DATABASE_URL not set — skipping.');@@ -100,6 +113,15 @@ afterAll(() => {beforeEach(() => {if (SKIP) return;+ // Robust restore: if a prior test threw before its own finally ran (or+ // before afterAll), HOME/PATH could still point at a dead temp dir. Reset+ // them to the captured originals at the start of every test so a throw in+ // one test can never leak a temp HOME/PATH into sibling suites that read+ // them. freshTempHome() re-points HOME per test immediately after this.+ if (origHome === undefined) delete process.env.HOME;+ else process.env.HOME = origHome;+ if (origPath === undefined) delete process.env.PATH;+ else process.env.PATH = `${fakeBinDir}:${origPath ?? ''}`;try { if (tmp) rmSync(tmp, { recursive: true, force: true }); } catch { /* best-effort */ }});@@ -114,144 +136,160 @@ const COMMON_OPTS = {describeE2E('E2E: v0.11.0 orchestrator against live Postgres', () => {test('fresh install flow: schema → smoke → prefs → host-rewrite → completed', async () => {tmp = freshTempHome('fresh');- const result = await v0_11_0.orchestrator(COMMON_OPTS);+ try {+ const result = await v0_11_0.orchestrator(COMMON_OPTS);- // Orchestrator returns a structured result (status is `complete` when- // no pending-host-work TODOs fired, `partial` otherwise).- expect(result.version).toBe('0.11.0');- expect(['complete', 'partial']).toContain(result.status);+ // Orchestrator returns a structured result (status is `complete` when+ // no pending-host-work TODOs fired, `partial` otherwise).+ expect(result.version).toBe('0.11.0');+ expect(['complete', 'partial']).toContain(result.status);- // Phase D: preferences.json exists with 0o600 + mode=pain_triggered.- const prefsPath = join(tmp, '.gbrain', 'preferences.json');- expect(existsSync(prefsPath)).toBe(true);- expect(statSync(prefsPath).mode & 0o777).toBe(0o600);- const prefs = loadPreferences();- expect(prefs.minion_mode).toBe('pain_triggered');- expect(prefs.set_at).toBeTruthy();- expect(prefs.set_in_version).toBeTruthy();+ // Phase D: preferences.json exists with 0o600 + mode=pain_triggered.+ const prefsPath = join(tmp, '.gbrain', 'preferences.json');+ expect(existsSync(prefsPath)).toBe(true);+ expect(statSync(prefsPath).mode & 0o777).toBe(0o600);+ const prefs = loadPreferences();+ expect(prefs.minion_mode).toBe('pain_triggered');+ expect(prefs.set_at).toBeTruthy();+ expect(prefs.set_in_version).toBeTruthy();- // Bug 3 (v0.14.2) — orchestrator no longer writes completed.jsonl.- // The runner (apply-migrations.ts) persists the result after the- // orchestrator returns. A direct orchestrator call in E2E leaves the- // ledger empty; the runner path is tested separately in- // test/apply-migrations.test.ts + test/migration-resume.test.ts.- const completed = loadCompletedMigrations();- const v0110Entries = completed.filter(e => e.version === '0.11.0');- expect(v0110Entries.length).toBe(0);+ // Bug 3 (v0.14.2) — orchestrator no longer writes completed.jsonl.+ // The runner (apply-migrations.ts) persists the result after the+ // orchestrator returns. A direct orchestrator call in E2E leaves the+ // ledger empty; the runner path is tested separately in+ // test/apply-migrations.test.ts + test/migration-resume.test.ts.+ const completed = loadCompletedMigrations();+ const v0110Entries = completed.filter(e => e.version === '0.11.0');+ expect(v0110Entries.length).toBe(0);- // Phase F is skipped per COMMON_OPTS — autopilot should NOT have been- // installed on this host.- expect(result.autopilot_installed).toBe(false);+ // Phase F is skipped per COMMON_OPTS — autopilot should NOT have been+ // installed on this host.+ expect(result.autopilot_installed).toBe(false);+ } finally {+ restoreHomePath();+ }}, 60_000);test('idempotent rerun: second invocation is a safe no-op', async () => {tmp = freshTempHome('rerun');- const first = await v0_11_0.orchestrator(COMMON_OPTS);- expect(['complete', 'partial']).toContain(first.status);+ try {+ const first = await v0_11_0.orchestrator(COMMON_OPTS);+ expect(['complete', 'partial']).toContain(first.status);- const second = await v0_11_0.orchestrator(COMMON_OPTS);- expect(['complete', 'partial']).toContain(second.status);+ const second = await v0_11_0.orchestrator(COMMON_OPTS);+ expect(['complete', 'partial']).toContain(second.status);- // Bug 3 (v0.14.2) — orchestrator does not write completed.jsonl, so- // repeated direct invocations don't accumulate ledger entries. Assert- // the preferences state stays stable (the real idempotency signal for- // this orchestrator is "running again doesn't corrupt preferences").- expect(loadPreferences().minion_mode).toBe('pain_triggered');- const completed = loadCompletedMigrations();- expect(completed.filter(e => e.version === '0.11.0').length).toBe(0);+ // Bug 3 (v0.14.2) — orchestrator does not write completed.jsonl, so+ // repeated direct invocations don't accumulate ledger entries. Assert+ // the preferences state stays stable (the real idempotency signal for+ // this orchestrator is "running again doesn't corrupt preferences").+ expect(loadPreferences().minion_mode).toBe('pain_triggered');+ const completed = loadCompletedMigrations();+ expect(completed.filter(e => e.version === '0.11.0').length).toBe(0);+ } finally {+ restoreHomePath();+ }}, 90_000);test('host rewrite: builtin handlers auto-rewritten, non-builtins queued as JSONL TODOs', async () => {tmp = freshTempHome('host-rewrite');- // Fixture: AGENTS.md + cron/jobs.json with a mix of gbrain-builtin and- // non-builtin handlers.- const claudeDir = join(tmp, '.claude');- mkdirSync(claudeDir, { recursive: true });- writeFileSync(- join(claudeDir, 'AGENTS.md'),- '# Test AGENTS.md\n\nSome existing content referencing sessions_spawn routing.\n',- );- mkdirSync(join(claudeDir, 'cron'), { recursive: true });- writeFileSync(- join(claudeDir, 'cron', 'jobs.json'),- JSON.stringify({- jobs: [- { schedule: '*/5 * * * *', kind: 'agentTurn', skill: 'sync' }, // builtin- { schedule: '0 */30 * * *', kind: 'agentTurn', skill: 'ea-inbox-sweep' }, // non-builtin- { schedule: '*/10 * * * *', kind: 'agentTurn', skill: 'embed' }, // builtin- { schedule: '0 8 * * *', kind: 'agentTurn', skill: 'morning-briefing' }, // non-builtin- ],- }, null, 2) + '\n',- );+ try {+ // Fixture: AGENTS.md + cron/jobs.json with a mix of gbrain-builtin and+ // non-builtin handlers.+ const claudeDir = join(tmp, '.claude');+ mkdirSync(claudeDir, { recursive: true });+ writeFileSync(+ join(claudeDir, 'AGENTS.md'),+ '# Test AGENTS.md\n\nSome existing content referencing sessions_spawn routing.\n',+ );+ mkdirSync(join(claudeDir, 'cron'), { recursive: true });+ writeFileSync(+ join(claudeDir, 'cron', 'jobs.json'),+ JSON.stringify({+ jobs: [+ { schedule: '*/5 * * * *', kind: 'agentTurn', skill: 'sync' }, // builtin+ { schedule: '0 */30 * * *', kind: 'agentTurn', skill: 'ea-inbox-sweep' }, // non-builtin+ { schedule: '*/10 * * * *', kind: 'agentTurn', skill: 'embed' }, // builtin+ { schedule: '0 8 * * *', kind: 'agentTurn', skill: 'morning-briefing' }, // non-builtin+ ],+ }, null, 2) + '\n',+ );- const result = await v0_11_0.orchestrator(COMMON_OPTS);+ const result = await v0_11_0.orchestrator(COMMON_OPTS);- // Builtins rewritten in place; non-builtins left alone.- const cronAfter = JSON.parse(readFileSync(join(claudeDir, 'cron', 'jobs.json'), 'utf-8'));- expect(cronAfter.jobs[0].kind).toBe('shell'); // sync (builtin)- expect(cronAfter.jobs[0].cmd).toContain('gbrain jobs submit sync');- expect(cronAfter.jobs[1].kind).toBe('agentTurn'); // ea-inbox-sweep (non-builtin)- expect(cronAfter.jobs[2].kind).toBe('shell'); // embed (builtin)- expect(cronAfter.jobs[3].kind).toBe('agentTurn'); // morning-briefing (non-builtin)+ // Builtins rewritten in place; non-builtins left alone.+ const cronAfter = JSON.parse(readFileSync(join(claudeDir, 'cron', 'jobs.json'), 'utf-8'));+ expect(cronAfter.jobs[0].kind).toBe('shell'); // sync (builtin)+ expect(cronAfter.jobs[0].cmd).toContain('gbrain jobs submit sync');+ expect(cronAfter.jobs[1].kind).toBe('agentTurn'); // ea-inbox-sweep (non-builtin)+ expect(cronAfter.jobs[2].kind).toBe('shell'); // embed (builtin)+ expect(cronAfter.jobs[3].kind).toBe('agentTurn'); // morning-briefing (non-builtin)- // files_rewritten counts the 2 builtin rewrites.- expect(result.files_rewritten).toBeGreaterThanOrEqual(2);+ // files_rewritten counts the 2 builtin rewrites.+ expect(result.files_rewritten).toBeGreaterThanOrEqual(2);- // pending_host_work counts the 2 non-builtin TODOs.- expect(result.pending_host_work).toBe(2);+ // pending_host_work counts the 2 non-builtin TODOs.+ expect(result.pending_host_work).toBe(2);- // Status is "partial" because non-builtin TODOs remain.- expect(result.status).toBe('partial');+ // Status is "partial" because non-builtin TODOs remain.+ expect(result.status).toBe('partial');- // AGENTS.md got the marker injected.- const agentsMdAfter = readFileSync(join(claudeDir, 'AGENTS.md'), 'utf-8');- expect(agentsMdAfter).toContain('gbrain:subagent-routing v0.11.0');- expect(agentsMdAfter).toContain('skills/conventions/subagent-routing.md');+ // AGENTS.md got the marker injected.+ const agentsMdAfter = readFileSync(join(claudeDir, 'AGENTS.md'), 'utf-8');+ expect(agentsMdAfter).toContain('gbrain:subagent-routing v0.11.0');+ expect(agentsMdAfter).toContain('skills/conventions/subagent-routing.md');- // JSONL TODO file written under ~/.gbrain/migrations/.- const jsonlPath = join(tmp, '.gbrain', 'migrations', 'pending-host-work.jsonl');- expect(existsSync(jsonlPath)).toBe(true);- const lines = readFileSync(jsonlPath, 'utf-8').split('\n').filter(l => l.trim());- expect(lines.length).toBe(2);- const todos = lines.map(l => JSON.parse(l));- const handlers = todos.map(t => t.handler).sort();- expect(handlers).toEqual(['ea-inbox-sweep', 'morning-briefing']);- for (const todo of todos) {- expect(todo.type).toBe('cron-handler-needs-host-registration');- expect(todo.status).toBe('pending');- expect(todo.manifest_path).toContain('cron/jobs.json');+ // JSONL TODO file written under ~/.gbrain/migrations/.+ const jsonlPath = join(tmp, '.gbrain', 'migrations', 'pending-host-work.jsonl');+ expect(existsSync(jsonlPath)).toBe(true);+ const lines = readFileSync(jsonlPath, 'utf-8').split('\n').filter(l => l.trim());+ expect(lines.length).toBe(2);+ const todos = lines.map(l => JSON.parse(l));+ const handlers = todos.map(t => t.handler).sort();+ expect(handlers).toEqual(['ea-inbox-sweep', 'morning-briefing']);+ for (const todo of todos) {+ expect(todo.type).toBe('cron-handler-needs-host-registration');+ expect(todo.status).toBe('pending');+ expect(todo.manifest_path).toContain('cron/jobs.json');+ }+ } finally {+ restoreHomePath();}}, 90_000);test('resumable: partial run → orchestrator re-run → complete', async () => {tmp = freshTempHome('resumable');- // Simulate a stopgap-written partial entry BEFORE running the orchestrator.- mkdirSync(join(tmp, '.gbrain', 'migrations'), { recursive: true });- writeFileSync(- join(tmp, '.gbrain', 'migrations', 'completed.jsonl'),- JSON.stringify({- version: '0.11.0',- status: 'partial',- apply_migrations_pending: true,- mode: 'pain_triggered',- source: 'fix-v0.11.0.sh',- ts: new Date().toISOString(),- }) + '\n',- );+ try {+ // Simulate a stopgap-written partial entry BEFORE running the orchestrator.+ mkdirSync(join(tmp, '.gbrain', 'migrations'), { recursive: true });+ writeFileSync(+ join(tmp, '.gbrain', 'migrations', 'completed.jsonl'),+ JSON.stringify({+ version: '0.11.0',+ status: 'partial',+ apply_migrations_pending: true,+ mode: 'pain_triggered',+ source: 'fix-v0.11.0.sh',+ ts: new Date().toISOString(),+ }) + '\n',+ );- // Orchestrator re-running on a partial → should succeed (schema apply- // and smoke are idempotent; prefs are preserved from the partial- // record; host-rewrite runs its safe-skip pass). Per Bug 3 (v0.14.2),- // the orchestrator itself doesn't append to completed.jsonl — the- // runner does. The stopgap's partial entry stays unchanged here.- const result = await v0_11_0.orchestrator(COMMON_OPTS);- expect(['complete', 'partial']).toContain(result.status);+ // Orchestrator re-running on a partial → should succeed (schema apply+ // and smoke are idempotent; prefs are preserved from the partial+ // record; host-rewrite runs its safe-skip pass). Per Bug 3 (v0.14.2),+ // the orchestrator itself doesn't append to completed.jsonl — the+ // runner does. The stopgap's partial entry stays unchanged here.+ const result = await v0_11_0.orchestrator(COMMON_OPTS);+ expect(['complete', 'partial']).toContain(result.status);- const completed = loadCompletedMigrations();- const v0110 = completed.filter(e => e.version === '0.11.0');- // Just the stopgap partial — orchestrator doesn't add its own entry.- expect(v0110.length).toBe(1);- expect(v0110[0].status).toBe('partial');- expect(v0110[0].source).toBe('fix-v0.11.0.sh');+ const completed = loadCompletedMigrations();+ const v0110 = completed.filter(e => e.version === '0.11.0');+ // Just the stopgap partial — orchestrator doesn't add its own entry.+ expect(v0110.length).toBe(1);+ expect(v0110[0].status).toBe('partial');+ expect(v0110[0].source).toBe('fix-v0.11.0.sh');+ } finally {+ restoreHomePath();+ }}, 90_000);});diff --git a/test/e2e/minions-resilience.test.ts b/test/e2e/minions-resilience.test.tsindex 21614fdd53..bd1ce04196 100644--- a/test/e2e/minions-resilience.test.ts+++ b/test/e2e/minions-resilience.test.ts@@ -94,7 +94,7 @@ describeE2E('E2E: Minions resilience (OpenClaw real-world patterns)', () => {}, 30_000);// --- 2. Runaway handler: ignores AbortSignal, dead-lettered by handleTimeouts ---- test('runaway handler: ignores AbortSignal, handleTimeouts dead-letters in <2s', async () => {+ test('runaway handler: ignores AbortSignal, handleTimeouts dead-letters it', async () => {const { a, b } = await makeEngines();try {const queue = new MinionQueue(a);@@ -133,8 +133,14 @@ describeE2E('E2E: Minions resilience (OpenClaw real-world patterns)', () => {worker.stop();await startP;+ // Correctness gate: the job MUST be dead-lettered with the timeout reason.+ // We intentionally do NOT assert a wall-clock upper bound (deadAt - started):+ // on a loaded CI runner the stall/timeout sweep cadence varies, and the only+ // thing that matters is that the runaway job terminates as 'dead'. The 3s poll+ // deadline above is the real timeout — if the sweep is too slow, finalStatus+ // stays '' and this toBe('dead') fails loudly.expect(finalStatus).toBe('dead');- expect(deadAt - started).toBeLessThan(2000);+ void deadAt; // retained for debugging; no timing assertion (flake-prone)const final = await queue.getJob(job.id);expect(final?.error_text).toMatch(/timeout exceeded/i);@@ -304,7 +310,7 @@ describeE2E('E2E: Minions resilience (OpenClaw real-world patterns)', () => {}, 60_000);// --- 5. Cascade kill under load: cancelJob aborts all live descendants ---- test('cascade kill: cancelJob on parent aborts 10 live children within 2s', async () => {+ test('cascade kill: cancelJob on parent aborts 10 live children', async () => {const { a, b } = await makeEngines();try {const queue = new MinionQueue(a);@@ -374,8 +380,12 @@ describeE2E('E2E: Minions resilience (OpenClaw real-world patterns)', () => {worker.stop();await startP;+ // Correctness gate: all 10 cooperative handlers observed the abort and the+ // DB shows every descendant + root cancelled. We do NOT assert a wall-clock+ // upper bound on cancelElapsed — the 3s abort poll deadline above already+ // bounds the wait, and asserting a tighter time flakes on shared runners.expect(abortedChildren.size).toBe(10);- expect(cancelElapsed).toBeLessThan(3000);+ void cancelElapsed; // retained for debugging; no timing assertion (flake-prone)// DB truth: every descendant + root is 'cancelled'const conn = getConn();diff --git a/test/e2e/multi-source.test.ts b/test/e2e/multi-source.test.tsindex f30bef1210..5c45c6b7ac 100644--- a/test/e2e/multi-source.test.ts+++ b/test/e2e/multi-source.test.ts@@ -78,7 +78,11 @@ describeE2E('v0.18.0 multi-source — Postgres schema shape (fresh install)', ());expect(rows.length).toBe(1);expect(rows[0].is_nullable).toBe('NO');- expect(String(rows[0].column_default)).toContain('default');+ // Postgres renders a TEXT DEFAULT 'default' literal as `'default'::text`.+ // Assert the exact stored expression rather than a loose substring so a+ // drift in the schema DEFAULT (e.g. a different sentinel source id) fails+ // here instead of silently passing.+ expect(String(rows[0].column_default)).toBe("'default'::text");});test('composite UNIQUE pages(source_id, slug) replaces global UNIQUE(slug)', async () => {@@ -292,6 +296,18 @@ describeE2E('v0.18.0 multi-source — cascade delete covers every dependent row'`INSERT INTO files (source_id, page_id, filename, storage_path, content_hash)VALUES ('cascadetest', ${aliceId}, 'alice.pdf', 'cascadetest/people/alice/alice.pdf', 'fh1')`,);+ const aliceFile = await conn.unsafe(+ `SELECT id FROM files WHERE source_id = 'cascadetest' AND storage_path = 'cascadetest/people/alice/alice.pdf'`,+ );+ const aliceFileId = aliceFile[0].id as number;++ // file_migration_ledger row keyed on the file (FK file_id ON DELETE+ // CASCADE). Removing the source cascades sources → files → ledger.+ await conn.unsafe(+ `INSERT INTO file_migration_ledger (file_id, storage_path_old, storage_path_new, status)+ VALUES (${aliceFileId}, 'cascadetest/people/alice/alice.pdf', 'cascadetest/people/alice/alice.pdf', 'pending')+ ON CONFLICT (file_id) DO NOTHING`,+ );// Sanity: everything existsexpect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM pages WHERE source_id = 'cascadetest'`))[0].n).toBe(2);@@ -299,6 +315,7 @@ describeE2E('v0.18.0 multi-source — cascade delete covers every dependent row'expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM timeline_entries WHERE page_id = ${aliceId}`))[0].n).toBe(1);expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM links WHERE from_page_id = ${aliceId}`))[0].n).toBe(1);expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM files WHERE source_id = 'cascadetest'`))[0].n).toBe(1);+ expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM file_migration_ledger WHERE file_id = ${aliceFileId}`))[0].n).toBe(1);// Remove the source.// v0.26.5: populated sources require --confirm-destructive; --yes alone is rejected.@@ -310,6 +327,7 @@ describeE2E('v0.18.0 multi-source — cascade delete covers every dependent row'expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM timeline_entries WHERE page_id = ${aliceId}`))[0].n).toBe(0);expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM links WHERE from_page_id = ${aliceId}`))[0].n).toBe(0);expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM files WHERE source_id = 'cascadetest'`))[0].n).toBe(0);+ expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM file_migration_ledger WHERE file_id = ${aliceFileId}`))[0].n).toBe(0);// The sources row itself is gone.const src = await conn.unsafe(`SELECT id FROM sources WHERE id = 'cascadetest'`);@@ -378,8 +396,10 @@ describeE2E('v0.18.0 multi-source — sync --source routes through sources tabletest('performSync with no sourceId falls back to global sync.repo_path', async () => {const engine = getEngine();- // Global config is still '/some/other/default/path' from the- // previous test. Without --source, performSync uses it.+ // Self-contained: set the global config this test depends on directly+ // instead of inheriting the side effect of the previous test. Without+ // --source, performSync must read this global key.+ await engine.setConfig('sync.repo_path', '/some/other/default/path');let err: Error | null = null;try {await performSync(engine, {});diff --git a/test/e2e/search-quality.test.ts b/test/e2e/search-quality.test.tsindex 3b2e73a771..6c61d82931 100644--- a/test/e2e/search-quality.test.ts+++ b/test/e2e/search-quality.test.ts@@ -128,6 +128,17 @@ describe('SearchResult fields', () => {expect(r.chunk_index).toBeDefined();expect(typeof r.chunk_index).toBe('number');});++ test('empty keyword query returns a defined array without throwing', async () => {+ const results = await engine.searchKeyword('');+ expect(Array.isArray(results)).toBe(true);+ });++ test('zero vector search returns a defined array without throwing', async () => {+ const zeroVector = new Float32Array(1536);+ const results = await engine.searchVector(zeroVector);+ expect(Array.isArray(results)).toBe(true);+ });});describe('detail parameter', () => {@@ -145,9 +156,11 @@ describe('detail parameter', () => {});test('detail=low on vector search filters to compiled_truth', async () => {- // Use a timeline-direction embedding — with detail=low, should get no results- // or only compiled_truth results+ // Use a timeline-direction embedding — detail=low filters to compiled_truth.+ // Vector search returns every chunk with an embedding (ordered by distance),+ // so the seeded compiled_truth chunks are non-empty and ALL compiled_truth.const results = await engine.searchVector(basisEmbedding(1), { detail: 'low' });+ expect(results.length).toBeGreaterThan(0);for (const r of results) {expect(r.chunk_source).toBe('compiled_truth');}diff --git a/test/e2e/upgrade.test.ts b/test/e2e/upgrade.test.tsindex ecbe31e355..af204e4897 100644--- a/test/e2e/upgrade.test.ts+++ b/test/e2e/upgrade.test.ts@@ -73,7 +73,7 @@ describeE2E('E2E: Check-Update', () => {expect(stdout).toContain('--json');});- test('handles no-releases gracefully (current repo state)', async () => {+ test('check-update --json contract holds regardless of real release state', async () => {const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'check-update', '--json'], {cwd: new URL('../..', import.meta.url).pathname,stdout: 'pipe',@@ -84,8 +84,16 @@ describeE2E('E2E: Check-Update', () => {expect(exitCode).toBe(0);const output = JSON.parse(stdout);- // With no releases, should return false and an error- expect(output.update_available).toBe(false);+ // Don't pin update_available to a literal value — the repo may or may not+ // have a published release. Assert the JSON shape instead.+ expect(typeof output.update_available).toBe('boolean');+ expect(output.current_version).toBe(VERSION);+ if (output.latest_version != null) {+ expect(typeof output.latest_version).toBe('string');+ }+ if (output.release_url != null) {+ expect(typeof output.release_url).toBe('string');+ }});test('version comparison wiring works end-to-end', () => {