diff --git a/scripts/test/research-copilot-mcp-e2e.test.ts b/scripts/test/research-copilot-mcp-e2e.test.ts index 746c8e09..0f57a72d 100644 --- a/scripts/test/research-copilot-mcp-e2e.test.ts +++ b/scripts/test/research-copilot-mcp-e2e.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { trialMoments } from '@stock-bot/calculations'; -import type { NotebookSnapshotReceipt } from '@stock-bot/research'; +import type { MarketDataStore, NotebookSnapshotReceipt } from '@stock-bot/research'; import { FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, @@ -526,7 +526,10 @@ function createInMemoryCopilotDatabase(): InMemoryCopilotDatabase { async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{ readonly preCutoffSessions: readonly string[]; + readonly q2PreRestatementTtmNetIncome: number; readonly restatedQ1TtmNetIncome: number; + readonly shortsApril15PctFloat: number; + readonly shortsApril30PctFloat: number; }> { const barsDir = join(curatedRoot, 'bars_1d', 'year=2024'); const fundDir = join(curatedRoot, 'fundamentals_pit', 'year=2024'); @@ -624,6 +627,7 @@ async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{ `); const fundValues: string[] = []; + const q2PreRestatementTtmNetIncome = 13_500_000.0; const restatedQ1TtmNetIncome = 42_500_000.0; // Verified Q1 + Q2 snapshots for listings 101..107 (7 listings >= DEFAULT_MIN_CROSS_SECTION = 5). for (let i = 0; i < 7; i += 1) { @@ -820,6 +824,17 @@ async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{ subtype: 'retail', payload: '{"spiel_id":"rt-101","is_edited":false}', }, + // Pre-cutoff ts with post-cutoff known_at (June 28 post edited after July 1 Vault cutoff): + // proves the DuckDB events scan fences on known_at as well as ts. + { + listingId: 102, + ts: '2024-06-28T14:00:00Z', + knownAt: '2024-07-02T14:00:00Z', + knownAtSource: 'post_edited', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-vault-edited-102","is_edited":true}', + }, // Post-cutoff Vault ceo_post (must be excluded by Vault fence) { listingId: 101, @@ -841,7 +856,13 @@ async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{ `COPY (SELECT * FROM events ORDER BY listing_id ASC, ts ASC, kind ASC, subtype ASC, payload_json ASC, known_at ASC, known_at_source ASC) TO ${sqlString(join(eventsDir, 'part.parquet'))} (FORMAT PARQUET);` ); - return { preCutoffSessions, restatedQ1TtmNetIncome }; + return { + preCutoffSessions, + q2PreRestatementTtmNetIncome, + restatedQ1TtmNetIncome, + shortsApril15PctFloat: 0.02, + shortsApril30PctFloat: 0.035, + }; } finally { await builder.close(); } @@ -930,8 +951,10 @@ async function runSnapshotSubprocess( interface E2eRunSummary { readonly fundExpressionHash: string; readonly fundRankIcMean: number | null; + readonly fundFirstSeriesPoint: { readonly date: string; readonly value: number } | null; readonly shortsExpressionHash: string; readonly shortsRankIcMean: number | null; + readonly shortsFirstSeriesPoint: { readonly date: string; readonly value: number } | null; readonly eventExpressionHash: string; readonly eventCarMean: number | null; readonly snapshotSha256: string; @@ -966,14 +989,14 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = mkdir(snapshotDir, { recursive: true }), ]); - const { restatedQ1TtmNetIncome } = await writeCuratedParquetFixtures(curatedRoot); + const { + q2PreRestatementTtmNetIncome, + restatedQ1TtmNetIncome, + shortsApril15PctFloat, + shortsApril30PctFloat, + } = await writeCuratedParquetFixtures(curatedRoot); await writeLibraryFixture(libraryRoot); - const notebookPath = join(notebookDir, 'ec1-study.py'); - const snapshotHtml = `

${DATASET_ID}

\n`; - await writeFile(notebookPath, '# synthetic EC1 marimo notebook fixture\n', 'utf8'); - const marimoShimPath = await writeCleanFakeMarimoShim(workDir, snapshotHtml); - const buildEnv = (): Record => ({ PATH: process.env.PATH, NODE_ENV: 'test', @@ -990,9 +1013,8 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = STOCKBOT_DUCKDB_THREADS: '2', }); - // Verify PIT fundamentals semantics directly via openResearchCopilotStore: - // restated Q1 (effective_known_at 2024-05-20 > Q2 2024-05-10) updates ttm_net_income - // without overwriting Q2 period_end ('2024-04-30'), and estimated-lag listing 108 is excluded. + // Verify PIT fundamentals, shorts +4d release, and events known_at Vault boundaries + // directly via openResearchCopilotStore before running the stdio pipeline. const pitCheckStore = await openResearchCopilotStore( { postgresUrl: 'postgresql://research_ro:hermetic@127.0.0.1:5433/trading_bot_dev', @@ -1005,16 +1027,76 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = { env: buildEnv() } ); try { - const pitTable = await pitCheckStore.store.fundamentalsAsOf({ + // Fundamentals BEFORE Q1 restatement (effective_known_at 2024-05-20): returns Q2 value, + // excludes estimated-lag listing 108. + const preRestatementTable = await pitCheckStore.store.fundamentalsAsOf({ + listingIds: [101, 108], + fields: ['ttm_net_income'], + asOf: '2024-05-19', + allowEstimatedLag: false, + }); + expect(preRestatementTable.rows).toHaveLength(1); + expect(preRestatementTable.rows[0]?.listing_id).toBe(101); + expect(preRestatementTable.rows[0]?.period_end).toBe('2024-04-30'); + expect(preRestatementTable.rows[0]?.ttm_net_income).toBe(q2PreRestatementTtmNetIncome); + + // Fundamentals AFTER Q1 restatement (effective_known_at 2024-05-20 > Q2 2024-05-10): + // updates ttm_net_income without overwriting Q2 period_end ('2024-04-30'). + const postRestatementTable = await pitCheckStore.store.fundamentalsAsOf({ listingIds: [101, 108], fields: ['ttm_net_income'], asOf: '2024-05-25', allowEstimatedLag: false, }); - expect(pitTable.rows).toHaveLength(1); - expect(pitTable.rows[0]?.listing_id).toBe(101); - expect(pitTable.rows[0]?.period_end).toBe('2024-04-30'); - expect(pitTable.rows[0]?.ttm_net_income).toBe(restatedQ1TtmNetIncome); + expect(postRestatementTable.rows).toHaveLength(1); + expect(postRestatementTable.rows[0]?.listing_id).toBe(101); + expect(postRestatementTable.rows[0]?.period_end).toBe('2024-04-30'); + expect(postRestatementTable.rows[0]?.ttm_net_income).toBe(restatedQ1TtmNetIncome); + + // Shorts ON report_date (2024-04-30, before +4 TSX business-day known_at 2024-05-06T21:00Z): + // only the 2024-04-15 observation is visible; 2024-04-30 is NOT usable on its report date. + const shortsOnReportDate = await pitCheckStore.store.shortsAsOf({ + listingIds: [101], + from: '2024-04-01', + to: '2024-05-10', + asOf: '2024-04-30', + }); + expect(shortsOnReportDate.rows).toHaveLength(1); + expect(shortsOnReportDate.rows[0]?.report_date).toBe('2024-04-15'); + expect(shortsOnReportDate.rows[0]?.pct_float).toBe(shortsApril15PctFloat); + + // Shorts AFTER release (2024-05-07): 2024-04-30 observation becomes visible. + const shortsAfterRelease = await pitCheckStore.store.shortsAsOf({ + listingIds: [101], + from: '2024-04-01', + to: '2024-05-10', + asOf: '2024-05-07', + }); + expect(shortsAfterRelease.rows).toHaveLength(2); + expect(shortsAfterRelease.rows[1]?.report_date).toBe('2024-04-30'); + expect(shortsAfterRelease.rows[1]?.pct_float).toBe(shortsApril30PctFloat); + + // Events DuckDB boundary: excludes both post-cutoff ts/known_at (nw-vault-101) AND + // pre-cutoff ts (2024-06-28) with post-cutoff known_at (2024-07-02, nw-vault-edited-102). + const ceoPostEvents = await pitCheckStore.store.events({ + kinds: ['ceo_post'], + listingIds: [...PRE_CUTOFF_LISTING_IDS], + from: '2024-04-01', + to: '2024-07-10', + }); + expect(ceoPostEvents.rows).toHaveLength(9); + expect( + ceoPostEvents.rows.every( + r => Number(r.ts) < VAULT_CUTOFF_TS && Number(r.known_at) < VAULT_CUTOFF_TS + ) + ).toBe(true); + expect( + ceoPostEvents.rows.some( + r => + String(r.payload_json).includes('nw-vault-101') || + String(r.payload_json).includes('nw-vault-edited-102') + ) + ).toBe(false); } finally { await pitCheckStore.close(); } @@ -1128,7 +1210,12 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = const fundPayload = fundRes.parsed as { status: string; clampedTo: boolean; - analysis: { rankIc: { mean: number | null } }; + analysis: { + rankIc: { mean: number | null }; + ledgerSeries: { + points: Array<{ date: string; value: number }>; + }; + }; trial: { trialId: number; expressionHash: string; sampleEnd: string }; deflatedSharpe: { clusterSize: number; dsr: number | null }; }; @@ -1136,6 +1223,12 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = expect(fundPayload.clampedTo).toBe(true); expect(fundPayload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); expect(fundPayload.deflatedSharpe.clusterSize).toBe(1); + expect(fundPayload.analysis.ledgerSeries.points.length).toBeGreaterThan(0); + expect( + fundPayload.analysis.ledgerSeries.points.every( + pt => pt.date < VAULT_CUTOFF_DATE && Number.isFinite(pt.value) + ) + ).toBe(true); // 5. analyze_signal #2: shorts alt-data (pct_float) in same relatedness cluster const shortsRes = await stdio.callTool('analyze_signal', { @@ -1154,7 +1247,12 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = const shortsPayload = shortsRes.parsed as { status: string; clampedTo: boolean; - analysis: { rankIc: { mean: number | null } }; + analysis: { + rankIc: { mean: number | null }; + ledgerSeries: { + points: Array<{ date: string; value: number }>; + }; + }; trial: { trialId: number; expressionHash: string; sampleEnd: string }; deflatedSharpe: { clusterSize: number; dsr: number | null }; }; @@ -1166,6 +1264,16 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = shortsPayload.deflatedSharpe.dsr !== null && Number.isFinite(shortsPayload.deflatedSharpe.dsr) ).toBe(true); + // First shorts report (2024-04-15) has known_at 2024-04-19T21:00Z (after 20:00Z close), + // so the earliest eligible signal session is Monday 2024-04-22, never 2024-04-15. + expect(shortsPayload.analysis.ledgerSeries.points.length).toBeGreaterThan(0); + expect(shortsPayload.analysis.ledgerSeries.points[0]?.date).toBe('2024-04-22'); + expect(Number.isFinite(shortsPayload.analysis.ledgerSeries.points[0]?.value)).toBe(true); + expect( + shortsPayload.analysis.ledgerSeries.points.every( + pt => pt.date >= '2024-04-22' && pt.date < VAULT_CUTOFF_DATE && Number.isFinite(pt.value) + ) + ).toBe(true); // 6. event_study #3: ceo_post (subtype: newswire) const eventRes = await stdio.callTool('event_study', { @@ -1213,11 +1321,63 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = } // 7. Real subprocess invocation of scripts/export-notebook-snapshot.ts + // Render a deterministic fixture manifest containing study settings, baselines, + // trial hashes, and results so the filed sha256 evidence digest binds to the study. + const snapshotManifest = { + datasetId: DATASET_ID, + vaultCutoffIso: VAULT_CUTOFF_ISO, + modeledCosts: 'zero', + baselines: { + signal: 'zero_ic', + eventStudy: 'equal_weight', + }, + studies: { + fundamentals: { + field: 'ttm_net_income', + allowEstimatedLag: false, + horizonSessions: 5, + expressionHash: fundPayload.trial.expressionHash, + rankIcMean: fundPayload.analysis.rankIc.mean, + firstSeriesPoint: fundPayload.analysis.ledgerSeries.points[0] ?? null, + }, + shorts: { + field: 'pct_float', + horizonSessions: 5, + expressionHash: shortsPayload.trial.expressionHash, + rankIcMean: shortsPayload.analysis.rankIc.mean, + firstSeriesPoint: shortsPayload.analysis.ledgerSeries.points[0] ?? null, + }, + eventStudy: { + kinds: ['ceo_post'], + subtypes: ['newswire'], + preDays: 2, + postDays: 3, + expressionHash: eventPayload.trial.expressionHash, + eventCount: eventPayload.eventCount, + carMean: eventPayload.study.clustered?.carMean ?? null, + }, + }, + }; + const manifestJson = JSON.stringify(snapshotManifest); + const expectedSnapshotHtml = `

${DATASET_ID}

\n`; + const runWorkDir = join(workDir, `snapshot-run-${runTag}`); + await mkdir(runWorkDir, { recursive: true }); + const notebookPath = join(notebookDir, `ec1-study-${runTag}.py`); + await writeFile(notebookPath, `# synthetic EC1 manifest: ${manifestJson}\n`, 'utf8'); + const marimoShimPath = await writeCleanFakeMarimoShim(runWorkDir, expectedSnapshotHtml); + const snapshotOutPath = join(snapshotDir, `ec1-${runTag}.html`); const receipt = await runSnapshotSubprocess(notebookPath, snapshotOutPath, marimoShimPath); const diskBytes = await readFile(snapshotOutPath); + const diskHtml = diskBytes.toString('utf8'); + expect(diskHtml).toBe(expectedSnapshotHtml); + expect(diskHtml).toContain(fundPayload.trial.expressionHash); + expect(diskHtml).toContain(shortsPayload.trial.expressionHash); + expect(diskHtml).toContain(eventPayload.trial.expressionHash); expect(receipt.bytes).toBe(diskBytes.byteLength); - expect(receipt.sha256).toBe(createHash('sha256').update(diskBytes).digest('hex')); + expect(receipt.sha256).toBe( + createHash('sha256').update(expectedSnapshotHtml, 'utf8').digest('hex') + ); // 8. file_finding: Vault-only trial ref fails closed with zero findings inserts const vaultRefAttempt = await stdio.callTool('file_finding', { @@ -1256,6 +1416,7 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = }; expect(filedFirstPayload.created).toBe(true); expect(db.findings).toHaveLength(1); + expect(db.findings[0]?.evidence_refs).toContain(`sha256:${receipt.sha256}`); // Identical replay with same idempotencyKey -> created: false, identical id/createdAt const filedReplay = await stdio.callTool('file_finding', findingArgs); @@ -1316,8 +1477,10 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = return { fundExpressionHash: fundPayload.trial.expressionHash, fundRankIcMean: fundPayload.analysis.rankIc.mean, + fundFirstSeriesPoint: fundPayload.analysis.ledgerSeries.points[0] ?? null, shortsExpressionHash: shortsPayload.trial.expressionHash, shortsRankIcMean: shortsPayload.analysis.rankIc.mean, + shortsFirstSeriesPoint: shortsPayload.analysis.ledgerSeries.points[0] ?? null, eventExpressionHash: eventPayload.trial.expressionHash, eventCarMean: eventPayload.study.clustered?.carMean ?? null, snapshotSha256: receipt.sha256, @@ -1330,4 +1493,129 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = // Deterministic replay parity across runs expect(run2).toEqual(run1); }); + + test('reports vaultExcludedEvents when a controlled store returns a post-cutoff fenced event', async () => { + const curatedRoot = join(workDir, 'curated'); + const libraryRoot = join(workDir, 'library'); + const duckdbTmpDir = join(workDir, 'duckdb-tmp'); + await Promise.all([ + mkdir(curatedRoot, { recursive: true }), + mkdir(libraryRoot, { recursive: true }), + mkdir(duckdbTmpDir, { recursive: true }), + ]); + + await writeCuratedParquetFixtures(curatedRoot); + await writeLibraryFixture(libraryRoot); + + const env: Record = { + PATH: process.env.PATH, + NODE_ENV: 'test', + RESEARCH_MCP_POSTGRES_URL: + 'postgresql://research_ro:hermetic@127.0.0.1:5433/trading_bot_dev?sslmode=disable', + RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro', + RESEARCH_MCP_CURATED_ROOT: curatedRoot, + RESEARCH_MCP_VAULT_CUTOFF_TS: VAULT_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: libraryRoot, + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), + STOCKBOT_DUCKDB_TEMP_DIRECTORY: duckdbTmpDir, + STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', + STOCKBOT_DUCKDB_THREADS: '2', + }; + + const db = createInMemoryCopilotDatabase(); + const stdio = createInteractiveStdioHarness(); + let storeClosed = false; + + const serverPromise = runResearchCopilotMcp({ + env, + input: stdio.input, + output: stdio.output, + stderr: stdio.stderr, + openExecutor: () => ({ + executor: db.executor, + close: () => {}, + }), + openStore: async hostConfig => { + const real = await openResearchCopilotStore(hostConfig, { env }); + const wrappedStore: MarketDataStore = { + bars: q => real.store.bars(q), + async events(q) { + const base = await real.store.events(q); + return { + columns: base.columns, + rows: [ + ...base.rows, + { + listing_id: 102, + ts: Date.parse('2024-06-28T14:00:00Z'), + known_at: Date.parse('2024-07-02T14:00:00Z'), + known_at_source: 'post_edited', + kind: 'ceo_post', + subtype: 'newswire', + payload_json: '{"spiel_id":"nw-vault-leaked-102","is_edited":true}', + }, + ], + }; + }, + shortsAsOf: q => real.store.shortsAsOf(q), + fx: q => real.store.fx(q), + crossSection: q => real.store.crossSection(q), + fundamentalsAsOf: q => real.store.fundamentalsAsOf(q), + macroAsOf: q => real.store.macroAsOf(q), + universe: q => real.store.universe(q), + }; + return { + store: wrappedStore, + close: async () => { + storeClosed = true; + await real.close(); + }, + }; + }, + now: () => FIXED_NOW_MS, + }); + + const initResp = await stdio.request('initialize', { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: 'ec1-vault-diag-client', version: '1.0.0' }, + }); + expect(initResp.error).toBeUndefined(); + stdio.notify('notifications/initialized'); + + const eventRes = await stdio.callTool('event_study', { + listingIds: [...PRE_CUTOFF_LISTING_IDS], + from: '2024-04-01', + to: '2024-07-10', + event: { + kinds: ['ceo_post'], + subtypes: ['newswire'], + }, + preDays: 2, + postDays: 3, + benchmark: 'equal_weight', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(eventRes.isError).toBe(false); + const eventPayload = eventRes.parsed as { + status: string; + eventCount: number; + vaultExcludedEvents: number; + panelDiagnostics: { vaultExcludedEvents: number }; + study: { diagnostics: { eventsUsed: number } }; + }; + expect(eventPayload.status).toBe('ok'); + expect(eventPayload.eventCount).toBe(8); + expect(eventPayload.vaultExcludedEvents).toBe(1); + expect(eventPayload.panelDiagnostics.vaultExcludedEvents).toBe(1); + expect(eventPayload.study.diagnostics.eventsUsed).toBe(8); + + stdio.closeInput(); + const exitCode = await serverPromise; + expect(exitCode).toBe(0); + expect(stdio.stderr.text()).toBe(''); + expect(storeClosed).toBe(true); + }); }); diff --git a/studio.config.json b/studio.config.json index 95ba0cc9..4e56a017 100644 --- a/studio.config.json +++ b/studio.config.json @@ -43,7 +43,6 @@ "docs": { "pitch": "design/pitch.md", "pillars": "design/pillars.md", - "brand": "design/marketing/brand.md", "agents": "AGENTS.md", "index": "design/README.md", "plan": "design/PLATFORM-PLAN.md",