import { afterEach, describe, expect, spyOn, test } from 'bun:test'; import { existsSync } from 'node:fs'; import { mkdir, mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { DuckDBConnection, DuckDBInstance } from '@duckdb/node-api'; import { createNodeDuckDbExecutor, openResearchCopilotStore } from '@stock-bot/duckdb'; import { MarketDataStoreValidationError, VaultHoldoutFenceError, type BarRecord, } from '@stock-bot/research/market-data-store'; import { runResearchCopilotStdioHost, type PostgresResearchCopilotExecutor, type QueryDataResultPayload, type ResearchCopilotHostConfig, type StdioInput, type StdioOutput, } from '@stock-bot/research/mcp'; // QA coverage for T-184 beyond the implementation tests: // - budget env (`STOCKBOT_DUCKDB_*`) is forwarded and reaches DuckDB; // - invalid budget env fails closed without leaking native handles or the Postgres URL; // - `openStore: openResearchCopilotStore` works unwrapped (default env resolution); // - the Vault cutoff comes from `config.vaultCutoffTs` (not a constant); // - `databasePath` is forwarded. // Fixture: listing 202, rows at 2025-03-10/11/12 20:00Z (known_at == ts). const LISTING_ID = 202; const DAY1_MS = Date.UTC(2025, 2, 10, 20, 0, 0, 0); const DAY2_MS = Date.UTC(2025, 2, 11, 20, 0, 0, 0); const DAY3_MS = Date.UTC(2025, 2, 12, 20, 0, 0, 0); const FIXED_NOW_MS = Date.UTC(2025, 2, 11, 12, 0, 0, 0); const PG_SECRET = 'qa_only_fake_pw_7c1e'; const FAKE_POSTGRES_URL = `postgresql://research_ro:${PG_SECRET}@127.0.0.1:5433/trading_bot_dev`; const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; const tempDirs: string[] = []; const spies: Array<{ mockRestore(): void }> = []; afterEach(async () => { while (spies.length > 0) { spies.pop()?.mockRestore(); } while (tempDirs.length > 0) { const dir = tempDirs.pop(); if (dir !== undefined) { await rm(dir, { recursive: true, force: true }); } } }); function track(spy: T): T { spies.push(spy); return spy; } function bar(ts: number, base: number): BarRecord { return { listingId: LISTING_ID, ts, open: base, high: base + 1, low: base - 1, close: base + 0.5, volume: 1000 * base, vwap: base + 0.25, knownAt: ts, }; } const BAR1 = bar(DAY1_MS, 10); const BAR2 = bar(DAY2_MS, 20); const BAR3 = bar(DAY3_MS, 30); function config(curatedRoot: string, vaultCutoffTs: number): ResearchCopilotHostConfig { return { postgresUrl: FAKE_POSTGRES_URL, curatedRoot, vaultCutoffTs, principalId: AGENT_PRINCIPAL, libraryRoot: '/tmp/unused-library-root', referenceListingIds: { XNYS: [LISTING_ID] }, }; } async function makeRoot(): Promise { const root = await mkdtemp(join(tmpdir(), 'stockbot-t184-qa-')); tempDirs.push(root); return root; } function utcTs(ms: number): string { return `${new Date(ms).toISOString().slice(0, 19).replace('T', ' ')}+00`; } function utcDate(ms: number): string { return new Date(ms).toISOString().slice(0, 10); } async function writeFixture(root: string): Promise { const curatedRoot = join(root, 'curated'); await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); const rows = [BAR1, BAR2, BAR3] .map( b => // Explicit UTC literals: casting naive timestamps to TIMESTAMPTZ would use the host TimeZone. `(${LISTING_ID}::INTEGER, DATE '${utcDate(b.ts)}', TIMESTAMPTZ '${utcTs(b.ts)}', ${b.open}::DOUBLE, ${b.high}::DOUBLE, ${b.low}::DOUBLE, ${b.close}::DOUBLE, ${b.volume}::DOUBLE, ${b.vwap}::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '${utcTs(b.knownAt)}')` ) .join(',\n'); const writer = await createNodeDuckDbExecutor(); try { await writer.run(` COPY ( SELECT * FROM (VALUES ${rows}) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) `); } finally { await writer.close(); } return curatedRoot; } async function collect( iterable: AsyncIterable<{ readonly rows: readonly BarRecord[] }> ): Promise { const out: BarRecord[] = []; for await (const batch of iterable) { out.push(...batch.rows); } return out; } async function captureError(fn: () => Promise): Promise { try { await fn(); } catch (err) { return err; } return undefined; } function fullRangeQuery() { return { listingIds: [LISTING_ID], timeframe: '1d' as const, from: '2025-03-01', to: '2025-03-31', asOf: '2025-03-31', adjustment: 'raw' as const, }; } function memoryStdio(messages: readonly unknown[]): { readonly input: StdioInput; readonly output: StdioOutput; raw(): string; } { const chunks: string[] = []; return { input: { async *[Symbol.asyncIterator]() { for (const m of messages) { yield `${JSON.stringify(m)}\n`; } }, }, output: { write(chunk: string): boolean { chunks.push(chunk); return true; }, }, raw: () => chunks.join(''), }; } function fakePg(): { executor: PostgresResearchCopilotExecutor; calls: number } { const state = { calls: 0, executor: { async query>(): Promise<{ readonly rows: readonly Row[] }> { state.calls += 1; return { rows: [] }; }, } as PostgresResearchCopilotExecutor, }; return state; } function hostMessages(): unknown[] { return [ { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 't184-qa', version: '1.0.0' }, }, }, { jsonrpc: '2.0', method: 'notifications/initialized' }, { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'query_data', arguments: { listingIds: [LISTING_ID], from: '2025-03-01', to: '2025-03-31', asOf: '2025-03-31', }, }, }, ]; } describe('openResearchCopilotStore QA (T-184)', () => { test('uses config.vaultCutoffTs as the only cutoff: moving the cutoff moves the visible rows', async () => { const curatedRoot = await writeFixture(await makeRoot()); // Cutoff exactly at DAY2 ts: DAY2 (ts == cutoff) is excluded, only DAY1 visible. const atDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS)); try { expect(await collect(atDay2.store.bars(fullRangeQuery()))).toEqual([BAR1]); } finally { await atDay2.close(); } // Cutoff 1ms after DAY2: DAY1 + DAY2 visible, DAY3 still fenced. const afterDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS + 1)); try { expect(await collect(afterDay2.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2]); const err = await captureError(() => collect(afterDay2.store.bars({ ...fullRangeQuery(), from: '2025-03-12' })) ); expect(err).toBeInstanceOf(VaultHoldoutFenceError); } finally { await afterDay2.close(); } // Cutoff after all rows: everything visible (proves no hidden constant cutoff). const late = await openResearchCopilotStore(config(curatedRoot, Date.UTC(2025, 5, 1))); try { expect(await collect(late.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2, BAR3]); } finally { await late.close(); } }); test('forwards STOCKBOT_DUCKDB_* budget env so DuckDB receives the configured spill directory, threads and memory limit', async () => { const root = await makeRoot(); const curatedRoot = await writeFixture(root); const spillDir = join(root, 'spill'); await mkdir(spillDir, { recursive: true }); const runSpy = track(spyOn(DuckDBConnection.prototype, 'run')); const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), { env: { STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', STOCKBOT_DUCKDB_THREADS: '1', STOCKBOT_DUCKDB_TEMP_DIRECTORY: spillDir, }, }); try { expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]); } finally { await handle.close(); } const statements = runSpy.mock.calls.map(call => String(call[0])); expect(statements).toContain(`SET temp_directory = '${spillDir}';`); expect(statements).toContain('SET threads = 1;'); expect(statements).toContain("SET memory_limit = '512MB';"); }); test('invalid budget env fails closed: open rejects, native connection and instance closed once, no Postgres URL in the error', async () => { const curatedRoot = await writeFixture(await makeRoot()); const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync')); const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync')); const err = await captureError(() => openResearchCopilotStore(config(curatedRoot, DAY2_MS), { env: { STOCKBOT_DUCKDB_THREADS: 'not-a-number' }, }) ); expect(err).toBeInstanceOf(MarketDataStoreValidationError); expect(connClose).toHaveBeenCalledTimes(1); expect(instClose).toHaveBeenCalledTimes(1); const text = `${(err as Error).message} ${(err as Error).stack ?? ''}`; expect(text).not.toContain(PG_SECRET); expect(text).not.toContain('postgresql://'); }); test('forwards databasePath: a file-backed DuckDB database is created at the given path', async () => { const root = await makeRoot(); const curatedRoot = await writeFixture(root); const dbPath = join(root, 'copilot.duckdb'); expect(existsSync(dbPath)).toBe(false); const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), { databasePath: dbPath, }); try { expect(existsSync(dbPath)).toBe(true); expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]); } finally { await handle.close(); } }); test('host wired with openStore: openResearchCopilotStore (unwrapped, default env) serves query_data fenced at config cutoff and closes DuckDB once', async () => { const curatedRoot = await writeFixture(await makeRoot()); const pg = fakePg(); const io = memoryStdio(hostMessages()); const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync')); const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync')); await runResearchCopilotStdioHost({ config: config(curatedRoot, DAY2_MS + 1), openExecutor: async () => ({ executor: pg.executor, close: async () => {} }), openStore: openResearchCopilotStore, createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), newId: () => 'qa-id', now: () => FIXED_NOW_MS, stdio: { input: io.input, output: io.output }, }); const lines = io .raw() .trimEnd() .split('\n') .map(l => JSON.parse(l) as { id: number; result: Record }); expect(lines.map(l => l.id)).toEqual([1, 2]); const envelope = lines[1]!.result as { isError?: boolean; content: Array<{ text: string }>; }; expect(envelope.isError).toBeUndefined(); const payload = JSON.parse(envelope.content[0]!.text) as QueryDataResultPayload; expect(payload.vaultCutoffTs).toBe(DAY2_MS + 1); expect(payload.toMs).toBe(DAY2_MS); expect(payload.rows).toEqual([BAR1, BAR2]); expect(io.raw()).not.toContain(PG_SECRET); expect(pg.calls).toBe(0); expect(connClose).toHaveBeenCalledTimes(1); expect(instClose).toHaveBeenCalledTimes(1); }); test('host with empty curatedRoot: query_data fails without hanging, leaks no Postgres URL, and DuckDB still closes once at EOF', async () => { const root = await makeRoot(); const emptyRoot = join(root, 'curated'); await mkdir(emptyRoot, { recursive: true }); const io = memoryStdio(hostMessages()); const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync')); const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync')); await runResearchCopilotStdioHost({ config: config(emptyRoot, DAY2_MS), openExecutor: async () => ({ executor: fakePg().executor, close: async () => {} }), openStore: openResearchCopilotStore, createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), newId: () => 'qa-id', now: () => FIXED_NOW_MS, stdio: { input: io.input, output: io.output }, }); const lines = io .raw() .trimEnd() .split('\n') .map( l => JSON.parse(l) as { id: number; result?: { isError?: boolean; content?: Array<{ text: string }> }; error?: unknown; } ); const toolResponse = lines.find(l => l.id === 2); expect(toolResponse).toBeDefined(); const failed = toolResponse!.error !== undefined || toolResponse!.result?.isError === true; expect(failed).toBe(true); expect(io.raw()).not.toContain(PG_SECRET); expect(connClose).toHaveBeenCalledTimes(1); expect(instClose).toHaveBeenCalledTimes(1); }); });