stock-bot/scripts/test/research-copilot-mcp-e2e.test.ts

1333 lines
49 KiB
TypeScript

import { createHash } from 'node:crypto';
import { chmod, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
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 {
FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
MCP_PROTOCOL_VERSION,
type PostgresResearchCopilotExecutor,
RESEARCH_COPILOT_TOOL_NAMES,
type StdioInput,
type StdioOutput,
} from '@stock-bot/research/mcp';
import { createNodeDuckDbExecutor } from '../../libs/data/duckdb/src/index';
import { openResearchCopilotStore } from '../../libs/data/duckdb/src/research-copilot-store';
import { runResearchCopilotMcp } from '../research-copilot-mcp';
const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url));
const SNAPSHOT_CLI_PATH = join(REPO_ROOT, 'scripts/export-notebook-snapshot.ts');
const DATASET_ID = 'synthetic:mcp-copilot-ec1:seed-20261205:v1';
const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
const VAULT_CUTOFF_ISO = '2024-07-01T00:00:00Z';
const VAULT_CUTOFF_DATE = '2024-07-01';
const VAULT_CUTOFF_TS = Date.parse(VAULT_CUTOFF_ISO);
const FIXED_NOW_MS = Date.UTC(2024, 5, 29, 12, 0, 0, 0);
const PRE_CUTOFF_LISTING_IDS = [101, 102, 103, 104, 105, 106, 107, 108] as const;
const VAULT_ONLY_TRIAL_ID = 99;
interface StoredTrialRow {
readonly trial_id: number;
readonly created_at: string;
readonly principal_id: string;
readonly campaign_id: string | null;
readonly stage: string;
readonly universe_market: string;
readonly horizon_bucket: string;
readonly hypothesis_id: string | null;
readonly expression_hash: string;
readonly sample_start: string;
readonly sample_end: string;
readonly n_obs: number;
readonly sharpe_unann: number;
readonly skewness: number;
readonly kurtosis: number;
readonly daily_series: number[];
}
interface StoredFindingRow {
readonly id: string;
readonly kind: string;
readonly title: string;
readonly summary: string;
readonly status: string;
readonly created_at: string;
readonly trial_refs: readonly string[];
readonly evidence_refs: readonly string[];
readonly idempotency_key: string | null;
}
interface SecurityMasterListingFixture {
readonly listing_id: number;
readonly instrument_id: number;
readonly ticker: string;
readonly class_suffix: string | null;
readonly name: string;
readonly mic: string;
readonly country_iso: string;
readonly calendar_code: string;
readonly currency: string;
readonly isin: string | null;
readonly first_bar_date: string;
readonly last_bar_date: string;
readonly delisted_at: string | null;
}
interface InMemoryCopilotDatabase {
readonly executor: PostgresResearchCopilotExecutor;
readonly trials: StoredTrialRow[];
readonly findings: StoredFindingRow[];
}
function sqlString(value: string): string {
return `'${value.replace(/'/g, "''")}'`;
}
function generateWeekdays(startDate: string, endDate: string): string[] {
const out: string[] = [];
const startMs = Date.parse(`${startDate}T00:00:00Z`);
const endMs = Date.parse(`${endDate}T00:00:00Z`);
for (let ms = startMs; ms <= endMs; ms += 86_400_000) {
const dt = new Date(ms);
const day = dt.getUTCDay();
if (day !== 0 && day !== 6) {
out.push(dt.toISOString().slice(0, 10));
}
}
return out;
}
function createInteractiveStdioHarness(): {
readonly input: StdioInput;
readonly output: StdioOutput;
readonly stderr: { write(chunk: string): boolean; text(): string };
request(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
notify(method: string, params?: Record<string, unknown>): void;
callTool(
name: string,
args: Record<string, unknown>
): Promise<{ readonly isError: boolean; readonly text: string; readonly parsed: unknown }>;
closeInput(): void;
} {
const incomingQueue: string[] = [];
let incomingResolver: ((value: IteratorResult<string>) => void) | null = null;
let inputClosed = false;
const responseQueue: Record<string, unknown>[] = [];
const responseWaiters: Array<(msg: Record<string, unknown>) => void> = [];
let outputBuffer = '';
const stderrChunks: string[] = [];
let nextRpcId = 1;
const pushInputLine = (line: string): void => {
if (incomingResolver !== null) {
const resolve = incomingResolver;
incomingResolver = null;
resolve({ value: line, done: false });
return;
}
incomingQueue.push(line);
};
const input: StdioInput = {
[Symbol.asyncIterator](): AsyncIterator<string> {
return {
next(): Promise<IteratorResult<string>> {
if (incomingQueue.length > 0) {
return Promise.resolve({ value: incomingQueue.shift() as string, done: false });
}
if (inputClosed) {
return Promise.resolve({ value: undefined as unknown as string, done: true });
}
return new Promise<IteratorResult<string>>(resolve => {
incomingResolver = resolve;
});
},
};
},
};
const output: StdioOutput = {
write(chunk: string): boolean {
outputBuffer += chunk;
let newlineIdx = outputBuffer.indexOf('\n');
while (newlineIdx !== -1) {
const line = outputBuffer.slice(0, newlineIdx);
outputBuffer = outputBuffer.slice(newlineIdx + 1);
if (line.trim().length > 0) {
const parsed = JSON.parse(line) as Record<string, unknown>;
const waiter = responseWaiters.shift();
if (waiter !== undefined) {
waiter(parsed);
} else {
responseQueue.push(parsed);
}
}
newlineIdx = outputBuffer.indexOf('\n');
}
return true;
},
};
const readNextResponse = (): Promise<Record<string, unknown>> => {
if (responseQueue.length > 0) {
return Promise.resolve(responseQueue.shift() as Record<string, unknown>);
}
return new Promise<Record<string, unknown>>(resolve => {
responseWaiters.push(resolve);
});
};
const request = async (
method: string,
params: Record<string, unknown> = {}
): Promise<Record<string, unknown>> => {
const id = nextRpcId;
nextRpcId += 1;
pushInputLine(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);
const response = await readNextResponse();
expect(response.id).toBe(id);
return response;
};
const notify = (method: string, params?: Record<string, unknown>): void => {
const payload =
params !== undefined
? { jsonrpc: '2.0', method, params }
: { jsonrpc: '2.0', method };
pushInputLine(`${JSON.stringify(payload)}\n`);
};
const callTool = async (
name: string,
args: Record<string, unknown>
): Promise<{ readonly isError: boolean; readonly text: string; readonly parsed: unknown }> => {
const resp = await request('tools/call', { name, arguments: args });
expect(resp.error).toBeUndefined();
const result = resp.result as {
isError?: boolean;
content: Array<{ type: string; text: string }>;
};
expect(result.content).toHaveLength(1);
const text = result.content[0]?.text ?? '';
let parsed: unknown = null;
try {
parsed = JSON.parse(text);
} catch {
parsed = null;
}
return {
isError: result.isError === true,
text,
parsed,
};
};
const closeInput = (): void => {
inputClosed = true;
if (incomingResolver !== null) {
const resolve = incomingResolver;
incomingResolver = null;
resolve({ value: undefined as unknown as string, done: true });
}
};
return {
input,
output,
stderr: {
write(chunk: string): boolean {
stderrChunks.push(chunk);
return true;
},
text: () => stderrChunks.join(''),
},
request,
notify,
callTool,
closeInput,
};
}
function createInMemoryCopilotDatabase(): InMemoryCopilotDatabase {
const listings: SecurityMasterListingFixture[] = [
{
listing_id: 101,
instrument_id: 1001,
ticker: 'ACME',
class_suffix: null,
name: 'Acme Holdings Corp',
mic: 'XNYS',
country_iso: 'US',
calendar_code: 'XNYS',
currency: 'USD',
isin: 'US0000001011',
first_bar_date: '2020-01-02',
last_bar_date: '2024-09-15',
delisted_at: '2024-09-15',
},
...PRE_CUTOFF_LISTING_IDS.slice(1).map((listingId, idx) => ({
listing_id: listingId,
instrument_id: 1002 + idx,
ticker: `SYN${idx + 2}`,
class_suffix: null,
name: `Synthetic Equity ${idx + 2} Inc`,
mic: 'XNYS',
country_iso: 'US',
calendar_code: 'XNYS',
currency: 'USD',
isin: `US000000${listingId}1`,
first_bar_date: '2020-01-02',
last_bar_date: '2024-09-15',
delisted_at: null,
})),
{
listing_id: 109,
instrument_id: 1009,
ticker: 'ACME2',
class_suffix: null,
name: 'Acme Post-Cutoff Listing Corp',
mic: 'XNYS',
country_iso: 'US',
calendar_code: 'XNYS',
currency: 'USD',
isin: 'US0000001091',
first_bar_date: '2024-07-02',
last_bar_date: '2024-09-15',
delisted_at: null,
},
];
// Pre-seed a Vault-only trial (sample_end >= 2024-07-01) in an unrelated cluster
// so file_finding can verify fail-closed rejection without polluting US_EQ / swing_1_10d.
const trials: StoredTrialRow[] = [
{
trial_id: VAULT_ONLY_TRIAL_ID,
created_at: '2024-07-16T00:00:00.000000Z',
principal_id: AGENT_PRINCIPAL,
campaign_id: null,
stage: 'signal_ic',
universe_market: 'FX',
horizon_bucket: 'position_10d_plus',
hypothesis_id: null,
expression_hash: '0'.repeat(64),
sample_start: '2024-07-01',
sample_end: '2024-07-15',
n_obs: 10,
sharpe_unann: 0.25,
skewness: 0,
kurtosis: 3,
daily_series: [0.01, -0.02, 0.03, 0.01, -0.01, 0.02, 0.01, -0.02, 0.02, 0.01],
},
];
let nextTrialId = 100;
const findings: StoredFindingRow[] = [];
const providerCaveats = [
{
id: 'caveat-ceo-shorts-lag',
provider: 'ceo_ca',
dataset: 'shorts',
caveat: 'CIRO semi-monthly short interest is published +4 TSX business days after report_date at 17:00 ET.',
created_at: '2024-01-10T00:00:00.000Z',
},
];
const executor: PostgresResearchCopilotExecutor = {
async query<Row = Record<string, unknown>>(
text: string,
params: readonly unknown[] = []
): Promise<{ readonly rows: readonly Row[] }> {
// 1. search_symbols
if (text.includes('listing_symbol_history')) {
const cutoffDate = String(params[0] ?? '');
const rawQuery = String(params[2] ?? '').toLowerCase();
const country = params[3] === null || params[3] === undefined ? null : String(params[3]);
const includeDelisted = Boolean(params[4]);
const matched = listings
.filter(row => {
if (row.first_bar_date > cutoffDate) {
return false;
}
if (country !== null && row.country_iso !== country) {
return false;
}
if (!includeDelisted && row.delisted_at !== null && row.delisted_at <= cutoffDate) {
return false;
}
return (
row.ticker.toLowerCase().includes(rawQuery) ||
row.name.toLowerCase().includes(rawQuery) ||
(row.isin !== null && row.isin.toLowerCase() === rawQuery)
);
})
.map(row => ({
listing_id: row.listing_id,
instrument_id: row.instrument_id,
ticker: row.ticker,
class_suffix: row.class_suffix,
name: row.name,
mic: row.mic,
currency: row.currency,
isin: row.isin,
first_bar_date: row.first_bar_date,
last_bar_date: row.last_bar_date,
delisted_at: row.delisted_at,
}));
return { rows: matched as unknown as readonly Row[] };
}
// 2. Listing exchange calendar lookup (event_study)
if (text.includes('calendar_code AS calendar_code')) {
const requestedIds = new Set((params[0] as readonly number[]) ?? []);
const matched = listings
.filter(row => requestedIds.has(row.listing_id))
.map(row => ({
listing_id: row.listing_id,
calendar_code: row.calendar_code,
}));
return { rows: matched as unknown as readonly Row[] };
}
// 3. trial_ledger INSERT
if (text.startsWith('INSERT INTO trial_ledger')) {
const receipts: Array<{ trial_id: string; created_at: string }> = [];
for (let offset = 0; offset < params.length; offset += 14) {
const id = nextTrialId;
nextTrialId += 1;
const createdAt = new Date(FIXED_NOW_MS + id * 1000).toISOString();
const rawSeries = params[offset + 13] as readonly number[];
// Round-trip through Float32Array to mirror PostgreSQL `real[]`.
const storedSeries = Array.from(Float32Array.from(rawSeries));
trials.push({
trial_id: id,
created_at: createdAt,
principal_id: String(params[offset]),
campaign_id: (params[offset + 1] as string | null) ?? null,
stage: String(params[offset + 2]),
universe_market: String(params[offset + 3]),
horizon_bucket: String(params[offset + 4]),
hypothesis_id: (params[offset + 5] as string | null) ?? null,
expression_hash: String(params[offset + 6]),
sample_start: String(params[offset + 7]),
sample_end: String(params[offset + 8]),
n_obs: Number(params[offset + 9]),
sharpe_unann: Number(params[offset + 10]),
skewness: Number(params[offset + 11]),
kurtosis: Number(params[offset + 12]),
daily_series: storedSeries,
});
receipts.push({ trial_id: String(id), created_at: createdAt });
}
return { rows: receipts as unknown as readonly Row[] };
}
// 4. trial_ledger visibility lookup (file_finding)
if (text.includes('SELECT 1 AS visible FROM') && text.includes('trial_ledger')) {
const trialRef = String(params[0] ?? '');
const cutoffDate = String(params[1] ?? '');
const visible = trials.some(
row => String(row.trial_id) === trialRef && row.sample_end < cutoffDate
);
return { rows: (visible ? [{ visible: 1 }] : []) as unknown as readonly Row[] };
}
// 5. trial_ledger target lookup by trial_id
if (text.includes('FROM trial_ledger') && text.includes('WHERE trial_id = $1::bigint')) {
const targetId = Number(params[0]);
const found = trials.filter(row => row.trial_id === targetId);
return { rows: found as unknown as readonly Row[] };
}
// 6. trial_ledger cluster lookup
if (
text.includes('FROM trial_ledger') &&
text.includes('WHERE universe_market = $1') &&
text.includes('AND horizon_bucket = $2')
) {
const market = String(params[0]);
const bucket = String(params[1]);
const asOf = params[2] !== undefined ? String(params[2]) : undefined;
const found = trials
.filter(
row =>
row.universe_market === market &&
row.horizon_bucket === bucket &&
(asOf === undefined || row.created_at <= asOf)
)
.sort((a, b) => a.trial_id - b.trial_id);
return { rows: found as unknown as readonly Row[] };
}
// 7. findings INSERT
if (text.includes('INSERT INTO') && text.includes('findings')) {
const id = String(params[0]);
const kind = String(params[1]);
const title = String(params[2]);
const summary = String(params[3]);
const status = String(params[4]);
const createdAt = String(params[5]);
const trialRefs = [...(params[6] as readonly string[])];
const evidenceRefs = [...(params[7] as readonly string[])];
const idempotencyKey =
params[8] === null || params[8] === undefined ? null : String(params[8]);
if (
idempotencyKey !== null &&
findings.some(row => row.idempotency_key === idempotencyKey)
) {
return { rows: [] };
}
findings.push({
id,
kind,
title,
summary,
status,
created_at: createdAt,
trial_refs: trialRefs,
evidence_refs: evidenceRefs,
idempotency_key: idempotencyKey,
});
return { rows: [{ id, created_at: createdAt }] as unknown as readonly Row[] };
}
// 8. findings SELECT by idempotency_key
if (text.includes('findings') && text.includes('WHERE idempotency_key = $1::text')) {
const key = String(params[0]);
const found = findings.filter(row => row.idempotency_key === key);
return { rows: found as unknown as readonly Row[] };
}
// 9. findings SELECT (read_knowledge)
if (text.includes('findings') && text.includes('FROM')) {
const sorted = [...findings].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
return { rows: sorted as unknown as readonly Row[] };
}
// 10. provider_caveats SELECT (read_knowledge)
if (text.includes('provider_caveats')) {
return { rows: providerCaveats as unknown as readonly Row[] };
}
throw new Error(`Unhandled SQL in in-memory copilot executor: ${text}`);
},
};
return { executor, trials, findings };
}
async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{
readonly preCutoffSessions: readonly string[];
readonly restatedQ1TtmNetIncome: number;
}> {
const barsDir = join(curatedRoot, 'bars_1d', 'year=2024');
const fundDir = join(curatedRoot, 'fundamentals_pit', 'year=2024');
const shortsDir = join(curatedRoot, 'shorts');
const eventsDir = join(curatedRoot, 'events', 'year=2024');
await Promise.all([
mkdir(barsDir, { recursive: true }),
mkdir(fundDir, { recursive: true }),
mkdir(shortsDir, { recursive: true }),
mkdir(eventsDir, { recursive: true }),
]);
const preCutoffSessions = generateWeekdays('2024-04-01', '2024-06-28');
const postCutoffSessions = ['2024-07-01', '2024-07-02', '2024-07-03'];
const builder = await createNodeDuckDbExecutor();
try {
// 1. bars_1d/year=2024/part.parquet
await builder.run(`
CREATE TABLE bars_1d (
listing_id INTEGER,
ts TIMESTAMPTZ,
session_date DATE,
open DOUBLE,
high DOUBLE,
low DOUBLE,
close DOUBLE,
volume DOUBLE,
vwap DOUBLE,
currency VARCHAR,
source VARCHAR,
known_at TIMESTAMPTZ
);
`);
const barValues: string[] = [];
for (let i = 0; i < PRE_CUTOFF_LISTING_IDS.length; i += 1) {
const listingId = PRE_CUTOFF_LISTING_IDS[i] as number;
let price = 50 + i * 5;
for (let d = 0; d < preCutoffSessions.length; d += 1) {
const sessionDate = preCutoffSessions[d] as string;
const dailyRet =
0.0015 * (i - 3.5) * Math.sin(0.27 * d + 0.5) +
0.008 * Math.cos(0.41 * d + 0.9 * i) +
0.0007 * (i - 3.5);
price = Math.max(5, price * (1 + dailyRet));
const open = Number((price * 0.998).toFixed(6));
const high = Number((price * 1.005).toFixed(6));
const low = Number((price * 0.995).toFixed(6));
const close = Number(price.toFixed(6));
const volume = 100_000 + i * 5_000 + d * 100;
const tsIso = `${sessionDate}T20:00:00Z`;
barValues.push(
`(${listingId}, TIMESTAMPTZ ${sqlString(tsIso)}, DATE ${sqlString(sessionDate)}, ${open}, ${high}, ${low}, ${close}, ${volume}, ${close}, 'USD', 'eod_prices', TIMESTAMPTZ ${sqlString(tsIso)})`
);
}
// Post-cutoff Vault sentinel bars at close = 9999.0.
for (const sessionDate of postCutoffSessions) {
const tsIso = `${sessionDate}T20:00:00Z`;
barValues.push(
`(${listingId}, TIMESTAMPTZ ${sqlString(tsIso)}, DATE ${sqlString(sessionDate)}, 9999.0, 9999.0, 9999.0, 9999.0, 500000.0, 9999.0, 'USD', 'eod_prices', TIMESTAMPTZ ${sqlString(tsIso)})`
);
}
}
await builder.run(`INSERT INTO bars_1d VALUES ${barValues.join(', ')};`);
await builder.run(
`COPY (SELECT * FROM bars_1d ORDER BY listing_id ASC, session_date ASC) TO ${sqlString(join(barsDir, 'part.parquet'))} (FORMAT PARQUET);`
);
// 2. fundamentals_pit/year=2024/part.parquet
await builder.run(`
CREATE TABLE fundamentals_pit (
listing_id INTEGER,
effective_known_at TIMESTAMPTZ,
known_at_source VARCHAR,
has_estimated_lag BOOLEAN,
period_end DATE,
fiscal_period VARCHAR,
currency VARCHAR,
period_known_at TIMESTAMPTZ,
revenue DOUBLE,
net_income DOUBLE,
operating_cash_flow DOUBLE,
total_assets DOUBLE,
total_equity DOUBLE,
shares_outstanding DOUBLE,
ttm_revenue DOUBLE,
ttm_net_income DOUBLE,
ttm_operating_cash_flow DOUBLE,
ttm_period_end DATE,
ttm_currency VARCHAR,
ttm_has_estimated_lag BOOLEAN
);
`);
const fundValues: string[] = [];
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) {
const listingId = PRE_CUTOFF_LISTING_IDS[i] as number;
const q1Ttm = 10_000_000 * (i + 1);
const q2Ttm = 12_000_000 * (i + 1) + (i % 2 === 0 ? 1_500_000 : -500_000);
fundValues.push(
`(${listingId}, TIMESTAMPTZ '2024-03-20T20:00:00Z', 'filing_timestamp', FALSE, DATE '2024-03-31', 'Q1', 'USD', TIMESTAMPTZ '2024-03-20T20:00:00Z', ${q1Ttm * 2}, ${q1Ttm / 4}, ${q1Ttm / 3}, 100000000.0, 50000000.0, 10000000.0, ${q1Ttm * 4}, ${q1Ttm}, ${q1Ttm * 1.1}, DATE '2024-03-31', 'USD', FALSE)`
);
fundValues.push(
`(${listingId}, TIMESTAMPTZ '2024-05-10T20:00:00Z', 'filing_timestamp', FALSE, DATE '2024-04-30', 'Q2', 'USD', TIMESTAMPTZ '2024-05-10T20:00:00Z', ${q2Ttm * 2}, ${q2Ttm / 4}, ${q2Ttm / 3}, 105000000.0, 52000000.0, 10000000.0, ${q2Ttm * 4}, ${q2Ttm}, ${q2Ttm * 1.1}, DATE '2024-04-30', 'USD', FALSE)`
);
}
// Restated Q1 for listing 101 with effective_known_at > Q2 that updates ttm_net_income
// while preserving Q2's period_end ('2024-04-30').
fundValues.push(
`(101, TIMESTAMPTZ '2024-05-20T20:00:00Z', 'filing_timestamp', FALSE, DATE '2024-04-30', 'Q2', 'USD', TIMESTAMPTZ '2024-05-10T20:00:00Z', 85000000.0, 10625000.0, 14000000.0, 105000000.0, 52000000.0, 10000000.0, 170000000.0, ${restatedQ1TtmNetIncome}, 46000000.0, DATE '2024-04-30', 'USD', FALSE)`
);
// Estimated-lag snapshot for listing 108 (excluded when allowEstimatedLag: false).
fundValues.push(
`(108, TIMESTAMPTZ '2024-03-25T20:00:00Z', 'statutory_lag_estimate', TRUE, DATE '2024-03-31', 'Q1', 'USD', TIMESTAMPTZ '2024-03-25T20:00:00Z', 20000000.0, 5000000.0, 6000000.0, 90000000.0, 45000000.0, 10000000.0, 80000000.0, 20000000.0, 22000000.0, DATE '2024-03-31', 'USD', TRUE)`
);
// Post-cutoff Vault snapshot for listing 101 (must be excluded by Vault fence).
fundValues.push(
`(101, TIMESTAMPTZ '2024-07-02T20:00:00Z', 'filing_timestamp', FALSE, DATE '2024-06-30', 'Q3', 'USD', TIMESTAMPTZ '2024-07-02T20:00:00Z', 999999999.0, 999999999.0, 999999999.0, 999999999.0, 999999999.0, 10000000.0, 999999999.0, 999999999.0, 999999999.0, DATE '2024-06-30', 'USD', FALSE)`
);
await builder.run(`INSERT INTO fundamentals_pit VALUES ${fundValues.join(', ')};`);
await builder.run(
`COPY (SELECT * FROM fundamentals_pit ORDER BY listing_id ASC, effective_known_at ASC) TO ${sqlString(join(fundDir, 'part.parquet'))} (FORMAT PARQUET);`
);
// 3. shorts/part.parquet (+4 TSX business-day known_at + post-cutoff row)
await builder.run(`
CREATE TABLE shorts (
listing_id INTEGER,
report_date DATE,
known_at TIMESTAMPTZ,
shares_short DOUBLE,
net_change DOUBLE,
pct_float DOUBLE,
source VARCHAR
);
`);
const shortSchedule: ReadonlyArray<readonly [string, string]> = [
['2024-04-15', '2024-04-19T21:00:00Z'],
['2024-04-30', '2024-05-06T21:00:00Z'],
['2024-05-15', '2024-05-22T21:00:00Z'],
['2024-05-31', '2024-06-06T21:00:00Z'],
['2024-06-15', '2024-06-21T21:00:00Z'],
// Post-cutoff known_at (excluded by Vault fence)
['2024-06-30', '2024-07-05T21:00:00Z'],
];
const shortValues: string[] = [];
for (let i = 0; i < PRE_CUTOFF_LISTING_IDS.length; i += 1) {
const listingId = PRE_CUTOFF_LISTING_IDS[i] as number;
for (let s = 0; s < shortSchedule.length; s += 1) {
const [reportDate, knownAtIso] = shortSchedule[s] as readonly [string, string];
const pctFloat = Number((0.02 + 0.015 * ((i + s) % 8) + 0.002 * i).toFixed(6));
const sharesShort = Math.round(pctFloat * 10_000_000);
const netChange = (s % 2 === 0 ? 1 : -1) * (10_000 + i * 2_500);
shortValues.push(
`(${listingId}, DATE ${sqlString(reportDate)}, TIMESTAMPTZ ${sqlString(knownAtIso)}, ${sharesShort}, ${netChange}, ${pctFloat}, 'ceo_shorts')`
);
}
}
await builder.run(`INSERT INTO shorts VALUES ${shortValues.join(', ')};`);
await builder.run(
`COPY (SELECT * FROM shorts ORDER BY listing_id ASC, report_date ASC) TO ${sqlString(join(shortsDir, 'part.parquet'))} (FORMAT PARQUET);`
);
// 4. events/year=2024/part.parquet (filing + earnings + ceo_post newswire/retail + post-cutoff)
await builder.run(`
CREATE TABLE events (
listing_id INTEGER,
ts TIMESTAMPTZ,
known_at TIMESTAMPTZ,
known_at_source VARCHAR,
kind VARCHAR,
subtype VARCHAR,
payload_json VARCHAR
);
`);
const eventRows: Array<{
readonly listingId: number;
readonly ts: string;
readonly knownAt: string;
readonly knownAtSource: string;
readonly kind: string;
readonly subtype: string;
readonly payload: string;
}> = [
// Filings & earnings
{
listingId: 101,
ts: '2024-04-12T15:00:00Z',
knownAt: '2024-04-12T15:00:00Z',
knownAtSource: 'filing_timestamp',
kind: 'filing',
subtype: '8-k',
payload: '{"form_type":"8-K"}',
},
{
listingId: 102,
ts: '2024-05-01T20:05:00Z',
knownAt: '2024-05-01T20:05:00Z',
knownAtSource: 'statutory_lag_estimate',
kind: 'earnings',
subtype: 'amc',
payload: '{"eps":1.25}',
},
// 8 pre-cutoff ceo_post newswire events across 4 distinct trading dates
// (including known_at > ts post_edited on listing 101)
{
listingId: 101,
ts: '2024-04-18T14:00:00Z',
knownAt: '2024-04-18T15:30:00Z',
knownAtSource: 'post_edited',
kind: 'ceo_post',
subtype: 'newswire',
payload: '{"spiel_id":"nw-101","is_edited":true}',
},
{
listingId: 102,
ts: '2024-04-18T14:15:00Z',
knownAt: '2024-04-18T14:15:00Z',
knownAtSource: 'post_timestamp',
kind: 'ceo_post',
subtype: 'newswire',
payload: '{"spiel_id":"nw-102","is_edited":false}',
},
{
listingId: 103,
ts: '2024-05-02T14:00:00Z',
knownAt: '2024-05-02T14:00:00Z',
knownAtSource: 'post_timestamp',
kind: 'ceo_post',
subtype: 'newswire',
payload: '{"spiel_id":"nw-103","is_edited":false}',
},
{
listingId: 104,
ts: '2024-05-02T14:30:00Z',
knownAt: '2024-05-02T14:30:00Z',
knownAtSource: 'post_timestamp',
kind: 'ceo_post',
subtype: 'newswire',
payload: '{"spiel_id":"nw-104","is_edited":false}',
},
{
listingId: 105,
ts: '2024-05-16T14:00:00Z',
knownAt: '2024-05-16T14:00:00Z',
knownAtSource: 'post_timestamp',
kind: 'ceo_post',
subtype: 'newswire',
payload: '{"spiel_id":"nw-105","is_edited":false}',
},
{
listingId: 106,
ts: '2024-05-16T14:30:00Z',
knownAt: '2024-05-16T14:30:00Z',
knownAtSource: 'post_timestamp',
kind: 'ceo_post',
subtype: 'newswire',
payload: '{"spiel_id":"nw-106","is_edited":false}',
},
{
listingId: 107,
ts: '2024-06-04T14:00:00Z',
knownAt: '2024-06-04T14:00:00Z',
knownAtSource: 'post_timestamp',
kind: 'ceo_post',
subtype: 'newswire',
payload: '{"spiel_id":"nw-107","is_edited":false}',
},
{
listingId: 108,
ts: '2024-06-04T14:30:00Z',
knownAt: '2024-06-04T14:30:00Z',
knownAtSource: 'post_timestamp',
kind: 'ceo_post',
subtype: 'newswire',
payload: '{"spiel_id":"nw-108","is_edited":false}',
},
// Pre-cutoff retail posts (must be excluded by subtypes: ['newswire'])
{
listingId: 101,
ts: '2024-04-22T15:00:00Z',
knownAt: '2024-04-22T15:00:00Z',
knownAtSource: 'post_timestamp',
kind: 'ceo_post',
subtype: 'retail',
payload: '{"spiel_id":"rt-101","is_edited":false}',
},
// Post-cutoff Vault ceo_post (must be excluded by Vault fence)
{
listingId: 101,
ts: '2024-07-02T14:00:00Z',
knownAt: '2024-07-02T14:00:00Z',
knownAtSource: 'post_timestamp',
kind: 'ceo_post',
subtype: 'newswire',
payload: '{"spiel_id":"nw-vault-101","is_edited":false}',
},
];
const eventValues = eventRows.map(
row =>
`(${row.listingId}, TIMESTAMPTZ ${sqlString(row.ts)}, TIMESTAMPTZ ${sqlString(row.knownAt)}, ${sqlString(row.knownAtSource)}, ${sqlString(row.kind)}, ${sqlString(row.subtype)}, ${sqlString(row.payload)})`
);
await builder.run(`INSERT INTO events VALUES ${eventValues.join(', ')};`);
await builder.run(
`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 };
} finally {
await builder.close();
}
}
async function writeLibraryFixture(libraryRoot: string): Promise<void> {
const methodologyDir = join(libraryRoot, 'cards', 'methodology');
await mkdir(methodologyDir, { recursive: true });
await writeFile(
join(libraryRoot, 'library.yml'),
['id: research_lib', 'sections:', ' methodology: Methodology Cards', ''].join('\n'),
'utf8'
);
await writeFile(
join(methodologyDir, 'pit-event-studies.md'),
[
'---',
'title: Point-in-Time Event Studies',
'summary: Anchor events on known_at and fence all windows strictly before Vault cutoff.',
'matches: ["pit", "event-study", "vault"]',
'---',
'Always align filings and ceo_post text events on known_at rather than event timestamp.',
'',
].join('\n'),
'utf8'
);
}
async function writeCleanFakeMarimoShim(workDir: string, htmlContent: string): Promise<string> {
const shimPath = join(workDir, 'fake-marimo-e2e');
const script = [
'#!/usr/bin/env bun',
"import { writeFileSync } from 'node:fs';",
'const args = process.argv.slice(2);',
`const htmlContent = ${JSON.stringify(htmlContent)};`,
'if (args[0] === "check") {',
' process.stdout.write(JSON.stringify({ issues: [], summary: { errored: false, total_files: 1 } }));',
' process.exit(0);',
'}',
'if (args[0] === "export" && args[1] === "html") {',
' writeFileSync(args[4], htmlContent, "utf8");',
' process.exit(0);',
'}',
'process.stderr.write("unexpected args: " + JSON.stringify(args));',
'process.exit(2);',
].join('\n');
await writeFile(shimPath, `${script}\n`, 'utf8');
await chmod(shimPath, 0o755);
return shimPath;
}
async function runSnapshotSubprocess(
notebookPath: string,
outputPath: string,
marimoShimPath: string
): Promise<NotebookSnapshotReceipt> {
const proc = Bun.spawn(
[
process.execPath,
'run',
SNAPSHOT_CLI_PATH,
'--notebook',
notebookPath,
'--out',
outputPath,
'--marimo',
marimoShimPath,
],
{
cwd: REPO_ROOT,
stdin: 'ignore',
stdout: 'pipe',
stderr: 'pipe',
}
);
const [exitCode, stdout, stderr] = await Promise.all([
proc.exited,
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
]);
expect(exitCode).toBe(0);
expect(stderr).toBe('');
return JSON.parse(stdout.trim()) as NotebookSnapshotReceipt;
}
interface E2eRunSummary {
readonly fundExpressionHash: string;
readonly fundRankIcMean: number | null;
readonly shortsExpressionHash: string;
readonly shortsRankIcMean: number | null;
readonly eventExpressionHash: string;
readonly eventCarMean: number | null;
readonly snapshotSha256: string;
}
describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () => {
let workDir = '';
beforeEach(async () => {
const rawDir = await mkdtemp(join(tmpdir(), 'research-copilot-mcp-e2e-'));
workDir = await realpath(rawDir);
});
afterEach(async () => {
if (workDir) {
await rm(workDir, { recursive: true, force: true });
workDir = '';
}
});
test('executes full Vault-fenced study + notebook snapshot + finding + knowledge pipeline with deterministic replay', async () => {
const curatedRoot = join(workDir, 'curated');
const libraryRoot = join(workDir, 'library');
const duckdbTmpDir = join(workDir, 'duckdb-tmp');
const notebookDir = join(workDir, 'notebooks');
const snapshotDir = join(workDir, 'snapshots');
await Promise.all([
mkdir(curatedRoot, { recursive: true }),
mkdir(libraryRoot, { recursive: true }),
mkdir(duckdbTmpDir, { recursive: true }),
mkdir(notebookDir, { recursive: true }),
mkdir(snapshotDir, { recursive: true }),
]);
const { restatedQ1TtmNetIncome } = await writeCuratedParquetFixtures(curatedRoot);
await writeLibraryFixture(libraryRoot);
const notebookPath = join(notebookDir, 'ec1-study.py');
const snapshotHtml = `<!doctype html><html><body><h1>${DATASET_ID}</h1></body></html>\n`;
await writeFile(notebookPath, '# synthetic EC1 marimo notebook fixture\n', 'utf8');
const marimoShimPath = await writeCleanFakeMarimoShim(workDir, snapshotHtml);
const buildEnv = (): Record<string, string | undefined> => ({
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',
});
// 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.
const pitCheckStore = await openResearchCopilotStore(
{
postgresUrl: 'postgresql://research_ro:hermetic@127.0.0.1:5433/trading_bot_dev',
curatedRoot,
vaultCutoffTs: VAULT_CUTOFF_TS,
principalId: AGENT_PRINCIPAL,
libraryRoot,
referenceListingIds: { XNYS: [101] },
},
{ env: buildEnv() }
);
try {
const pitTable = 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);
} finally {
await pitCheckStore.close();
}
const executeFullPipeline = async (runTag: string): Promise<E2eRunSummary> => {
const db = createInMemoryCopilotDatabase();
const stdio = createInteractiveStdioHarness();
let executorClosed = false;
let idSeq = 0;
const serverPromise = runResearchCopilotMcp({
env: buildEnv(),
input: stdio.input,
output: stdio.output,
stderr: stdio.stderr,
openExecutor: () => ({
executor: db.executor,
close: () => {
executorClosed = true;
},
}),
newId: () => {
idSeq += 1;
return `00000000-0000-4000-8000-${String(idSeq).padStart(12, '0')}`;
},
now: () => FIXED_NOW_MS,
});
// 1. initialize + notifications/initialized + tools/list
const initResp = await stdio.request('initialize', {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'ec1-e2e-client', version: '1.0.0' },
});
expect(initResp.error).toBeUndefined();
stdio.notify('notifications/initialized');
const listResp = await stdio.request('tools/list', {});
const listedTools = (listResp.result as { tools: Array<{ name: string }> }).tools.map(
t => t.name
);
expect(listedTools).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]);
// 2. search_symbols: post-cutoff delistedAt masked, lastBarDate clamped, post-cutoff listing 109 excluded
const searchRes = await stdio.callTool('search_symbols', {
query: 'ACME',
country: 'US',
includeDelisted: true,
});
expect(searchRes.isError).toBe(false);
const searchPayload = searchRes.parsed as {
scope: string;
rowCount: number;
rows: Array<{
listingId: number;
ticker: string;
lastBarDate: string | null;
delistedAt: string | null;
}>;
};
expect(searchPayload.scope).toBe('vault_fenced');
expect(searchPayload.rowCount).toBe(1);
expect(searchPayload.rows[0]?.listingId).toBe(101);
expect(searchPayload.rows[0]?.delistedAt).toBeNull();
expect(searchPayload.rows[0]?.lastBarDate).toBe('2024-06-30');
// 3. query_data: straddling `to` clamped, 9999.0 Vault sentinel bars excluded
const queryStraddle = await stdio.callTool('query_data', {
listingIds: [101],
from: '2024-06-20',
to: '2024-07-10',
timeframe: '1d',
adjustment: 'raw',
});
expect(queryStraddle.isError).toBe(false);
const queryPayload = queryStraddle.parsed as {
clampedTo: boolean;
rowCount: number;
rows: Array<{ close: number; ts: number }>;
};
expect(queryPayload.clampedTo).toBe(true);
expect(queryPayload.rowCount).toBeGreaterThan(0);
expect(queryPayload.rows.every(r => r.close !== 9999.0 && r.ts < VAULT_CUTOFF_TS)).toBe(true);
// query_data: from >= Vault cutoff rejected with VaultHoldoutFenceError
const queryVaultRejected = await stdio.callTool('query_data', {
listingIds: [101],
from: VAULT_CUTOFF_DATE,
to: '2024-07-10',
timeframe: '1d',
adjustment: 'raw',
});
expect(queryVaultRejected.isError).toBe(true);
expect(queryVaultRejected.text).toContain('VaultHoldoutFenceError');
// 4. analyze_signal #1: PIT fundamentals (ttm_net_income, allowEstimatedLag: false)
const fundRes = await stdio.callTool('analyze_signal', {
listingIds: [...PRE_CUTOFF_LISTING_IDS],
from: '2024-04-01',
to: '2024-07-10',
horizonSessions: 5,
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
signal: {
source: 'fundamentals',
field: 'ttm_net_income',
allowEstimatedLag: false,
},
});
expect(fundRes.isError).toBe(false);
const fundPayload = fundRes.parsed as {
status: string;
clampedTo: boolean;
analysis: { rankIc: { mean: number | null } };
trial: { trialId: number; expressionHash: string; sampleEnd: string };
deflatedSharpe: { clusterSize: number; dsr: number | null };
};
expect(fundPayload.status).toBe('ok');
expect(fundPayload.clampedTo).toBe(true);
expect(fundPayload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true);
expect(fundPayload.deflatedSharpe.clusterSize).toBe(1);
// 5. analyze_signal #2: shorts alt-data (pct_float) in same relatedness cluster
const shortsRes = await stdio.callTool('analyze_signal', {
listingIds: [...PRE_CUTOFF_LISTING_IDS],
from: '2024-04-01',
to: '2024-07-10',
horizonSessions: 5,
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
signal: {
source: 'shorts',
field: 'pct_float',
},
});
expect(shortsRes.isError).toBe(false);
const shortsPayload = shortsRes.parsed as {
status: string;
clampedTo: boolean;
analysis: { rankIc: { mean: number | null } };
trial: { trialId: number; expressionHash: string; sampleEnd: string };
deflatedSharpe: { clusterSize: number; dsr: number | null };
};
expect(shortsPayload.status).toBe('ok');
expect(shortsPayload.clampedTo).toBe(true);
expect(shortsPayload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true);
expect(shortsPayload.deflatedSharpe.clusterSize).toBe(2);
expect(
shortsPayload.deflatedSharpe.dsr !== null &&
Number.isFinite(shortsPayload.deflatedSharpe.dsr)
).toBe(true);
// 6. event_study #3: ceo_post (subtype: newswire)
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;
clampedTo: boolean;
eventCount: number;
study: { clustered: { carMean: number } | null; diagnostics: { usedEvents: number } };
trial: { trialId: number; expressionHash: string; sampleEnd: string };
deflatedSharpe: { clusterSize: number; dsr: number | null };
};
expect(eventPayload.status).toBe('ok');
expect(eventPayload.clampedTo).toBe(true);
// Only the 8 pre-cutoff newswire ceo_post events are included (retail + Vault rows excluded).
expect(eventPayload.eventCount).toBe(8);
expect(eventPayload.study.diagnostics.usedEvents).toBe(8);
expect(eventPayload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true);
expect(eventPayload.deflatedSharpe.clusterSize).toBe(3);
// Verify every recorded research trial_ledger row satisfies Vault cutoff and trialMoments parity.
const recordedResearchTrials = db.trials.filter(t => t.trial_id !== VAULT_ONLY_TRIAL_ID);
expect(recordedResearchTrials).toHaveLength(3);
for (const row of recordedResearchTrials) {
expect(row.sample_end < VAULT_CUTOFF_DATE).toBe(true);
const expectedMoments = trialMoments(row.daily_series);
expect(expectedMoments).not.toBeNull();
expect(row.n_obs).toBe(expectedMoments?.nObs);
expect(row.sharpe_unann).toBeCloseTo(expectedMoments?.sharpeUnann ?? Number.NaN, 4);
expect(row.skewness).toBeCloseTo(expectedMoments?.skewness ?? Number.NaN, 4);
expect(row.kurtosis).toBeCloseTo(expectedMoments?.kurtosis ?? Number.NaN, 4);
}
// 7. Real subprocess invocation of scripts/export-notebook-snapshot.ts
const snapshotOutPath = join(snapshotDir, `ec1-${runTag}.html`);
const receipt = await runSnapshotSubprocess(notebookPath, snapshotOutPath, marimoShimPath);
const diskBytes = await readFile(snapshotOutPath);
expect(receipt.bytes).toBe(diskBytes.byteLength);
expect(receipt.sha256).toBe(createHash('sha256').update(diskBytes).digest('hex'));
// 8. file_finding: Vault-only trial ref fails closed with zero findings inserts
const vaultRefAttempt = await stdio.callTool('file_finding', {
kind: 'finding',
title: 'Should Fail On Vault Trial Ref',
summary: 'Must fail closed when referencing a Vault-only trial.',
trialRefs: [String(VAULT_ONLY_TRIAL_ID)],
evidenceRefs: [DATASET_ID],
});
expect(vaultRefAttempt.isError).toBe(true);
expect(vaultRefAttempt.text).toContain(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(db.findings).toHaveLength(0);
// 9. file_finding: valid filing with 3 research-visible trialRefs + snapshot sha256 + idempotency
const researchTrialRefs = [
String(fundPayload.trial.trialId),
String(shortsPayload.trial.trialId),
String(eventPayload.trial.trialId),
];
const findingArgs = {
kind: 'finding',
title: 'EC1 PIT Fundamentals, Shorts, and Newswire Event Study',
summary:
'Synthetic EC1 study combining PIT fundamentals, +4d shorts, and ceo_post newswire events under zero modeled costs.',
trialRefs: researchTrialRefs,
evidenceRefs: [DATASET_ID, `sha256:${receipt.sha256}`],
idempotencyKey: 'ec1-study-finding-v1',
};
const filedFirst = await stdio.callTool('file_finding', findingArgs);
expect(filedFirst.isError).toBe(false);
const filedFirstPayload = filedFirst.parsed as {
id: string;
createdAt: string;
created: boolean;
};
expect(filedFirstPayload.created).toBe(true);
expect(db.findings).toHaveLength(1);
// Identical replay with same idempotencyKey -> created: false, identical id/createdAt
const filedReplay = await stdio.callTool('file_finding', findingArgs);
expect(filedReplay.isError).toBe(false);
const filedReplayPayload = filedReplay.parsed as {
id: string;
createdAt: string;
created: boolean;
};
expect(filedReplayPayload.created).toBe(false);
expect(filedReplayPayload.id).toBe(filedFirstPayload.id);
expect(filedReplayPayload.createdAt).toBe(filedFirstPayload.createdAt);
expect(db.findings).toHaveLength(1);
// Mutated payload with same idempotencyKey -> conflict error
const filedConflict = await stdio.callTool('file_finding', {
...findingArgs,
summary: 'Mutated summary for conflict check.',
});
expect(filedConflict.isError).toBe(true);
expect(filedConflict.text).toContain(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT);
expect(db.findings).toHaveLength(1);
// 10. read_knowledge (source: 'all') returns pending_review finding, library card, and provider_caveats
const knowledgeRes = await stdio.callTool('read_knowledge', {
source: 'all',
});
expect(knowledgeRes.isError).toBe(false);
const knowledgePayload = knowledgeRes.parsed as {
rows: Array<{ source: string; id: string; status?: string }>;
sources: { library: number; findings: number; provider_caveats: number };
};
expect(knowledgePayload.sources.library).toBe(1);
expect(knowledgePayload.sources.findings).toBe(1);
expect(knowledgePayload.sources.provider_caveats).toBe(1);
const findingRow = knowledgePayload.rows.find(r => r.source === 'findings');
expect(findingRow?.id).toBe(filedFirstPayload.id);
expect(findingRow?.status).toBe('pending_review');
expect(
knowledgePayload.rows.some(
r => r.source === 'library' && r.id === 'research_lib:methodology/pit-event-studies'
)
).toBe(true);
expect(
knowledgePayload.rows.some(
r => r.source === 'provider_caveats' && r.id === 'caveat-ceo-shorts-lag'
)
).toBe(true);
// 11. Clean EOF shutdown
stdio.closeInput();
const exitCode = await serverPromise;
expect(exitCode).toBe(0);
expect(stdio.stderr.text()).toBe('');
expect(executorClosed).toBe(true);
return {
fundExpressionHash: fundPayload.trial.expressionHash,
fundRankIcMean: fundPayload.analysis.rankIc.mean,
shortsExpressionHash: shortsPayload.trial.expressionHash,
shortsRankIcMean: shortsPayload.analysis.rankIc.mean,
eventExpressionHash: eventPayload.trial.expressionHash,
eventCarMean: eventPayload.study.clustered?.carMean ?? null,
snapshotSha256: receipt.sha256,
};
};
const run1 = await executeFullPipeline('run1');
const run2 = await executeFullPipeline('run2');
// Deterministic replay parity across runs
expect(run2).toEqual(run1);
});
});