1451 lines
49 KiB
TypeScript
1451 lines
49 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import {
|
|
EventPanelError,
|
|
type EventStudyExchangeCalendars,
|
|
buildEventStudyInput,
|
|
eventsTableToEventRows,
|
|
} from '../src/event-panel';
|
|
import {
|
|
type BarBatch,
|
|
type BarRecord,
|
|
type EventKind,
|
|
type MarketDataStore,
|
|
MarketDataStoreValidationError,
|
|
type Table,
|
|
type TableRow,
|
|
VaultHoldoutFenceError,
|
|
VaultScopeNotAuthorizedError,
|
|
} from '../src/market-data-store';
|
|
import {
|
|
AdjFactorsSnapshotError,
|
|
type BarsQuery,
|
|
EVENTS_COLUMNS,
|
|
type EventsQuery,
|
|
MarketDataStoreNotImplementedError,
|
|
type UniverseQuery,
|
|
} from '../src/market-data-store-duckdb';
|
|
import {
|
|
EVENT_STUDY_MAX_LISTING_IDS,
|
|
EVENT_STUDY_MAX_POST_DAYS,
|
|
EVENT_STUDY_MAX_PRE_DAYS,
|
|
EVENT_STUDY_MAX_SUBTYPES,
|
|
EVENT_STUDY_MAX_SUBTYPE_LENGTH,
|
|
type EventStudyExchangeCalendarQuery,
|
|
type EventStudyResultPayload,
|
|
createEventStudyTool,
|
|
createMcpServer,
|
|
} from '../src/mcp/index';
|
|
import { SignalStudyError, runEventStudy } from '../src/signal-study';
|
|
import { TrialLedgerError, type TrialLedgerExecutor } from '../src/trial-ledger';
|
|
|
|
// Synthetic fixture: seeded (20261201) 8 listings, 60 pre-cutoff + 8 post-cutoff
|
|
// business sessions from 2022-11-01, daily close-to-close returns, raw adjustment,
|
|
// no fills or transaction costs, XNYS 21:00 UTC close calendar.
|
|
const SEED = 20261201;
|
|
const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
|
const CAMPAIGN_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
|
const HYPOTHESIS_UUID = '12345678-1234-4123-8123-123456789abc';
|
|
|
|
function createSeededRng(seed: number): () => number {
|
|
let state = seed >>> 0;
|
|
return () => {
|
|
state = (state + 0x6d2b79f5) >>> 0;
|
|
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
|
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
|
};
|
|
}
|
|
|
|
function makeBusinessDates(startDate: string, count: number): string[] {
|
|
const out: string[] = new Array(count);
|
|
const current = new Date(`${startDate}T00:00:00.000Z`);
|
|
let written = 0;
|
|
while (written < count) {
|
|
const day = current.getUTCDay();
|
|
if (day !== 0 && day !== 6) {
|
|
out[written] = current.toISOString().slice(0, 10);
|
|
written += 1;
|
|
}
|
|
current.setUTCDate(current.getUTCDate() + 1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0): number {
|
|
const [y, m, d] = date.split('-').map(Number);
|
|
return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, 0);
|
|
}
|
|
|
|
function parseBound(raw: string, endOfDay: boolean): number {
|
|
if (raw.length === 10) {
|
|
return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`);
|
|
}
|
|
return Date.parse(raw);
|
|
}
|
|
|
|
interface StoredTrialRow {
|
|
readonly trial_id: string;
|
|
readonly created_at: Date;
|
|
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: readonly number[];
|
|
}
|
|
|
|
function createFakeTrialLedger(options?: {
|
|
insertError?: Error;
|
|
dsrReadError?: Error;
|
|
}): {
|
|
executor: TrialLedgerExecutor;
|
|
rows: StoredTrialRow[];
|
|
insertCalls: number;
|
|
selectCalls: number;
|
|
} {
|
|
const rows: StoredTrialRow[] = [];
|
|
let nextTrialId = 1;
|
|
const state = {
|
|
rows,
|
|
insertCalls: 0,
|
|
selectCalls: 0,
|
|
executor: null as unknown as TrialLedgerExecutor,
|
|
};
|
|
|
|
state.executor = {
|
|
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
|
const trimmed = text.trimStart();
|
|
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
|
state.insertCalls += 1;
|
|
if (options?.insertError !== undefined) {
|
|
throw options.insertError;
|
|
}
|
|
const p = params ?? [];
|
|
const trialId = nextTrialId++;
|
|
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId));
|
|
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
|
const stored: StoredTrialRow = {
|
|
trial_id: String(trialId),
|
|
created_at: createdAt,
|
|
principal_id: p[0] as string,
|
|
campaign_id: (p[1] as string | null) ?? null,
|
|
stage: p[2] as string,
|
|
universe_market: p[3] as string,
|
|
horizon_bucket: p[4] as string,
|
|
hypothesis_id: (p[5] as string | null) ?? null,
|
|
expression_hash: p[6] as string,
|
|
sample_start: p[7] as string,
|
|
sample_end: p[8] as string,
|
|
n_obs: p[9] as number,
|
|
sharpe_unann: p[10] as number,
|
|
skewness: p[11] as number,
|
|
kurtosis: p[12] as number,
|
|
daily_series: dailySeries,
|
|
};
|
|
rows.push(stored);
|
|
return {
|
|
rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row],
|
|
rowCount: 1,
|
|
};
|
|
}
|
|
|
|
if (trimmed.startsWith('SELECT')) {
|
|
state.selectCalls += 1;
|
|
if (options?.dsrReadError !== undefined) {
|
|
throw options.dsrReadError;
|
|
}
|
|
if (text.includes('WHERE trial_id = $1::bigint')) {
|
|
const targetId = String(params?.[0]);
|
|
const matched = rows.filter(r => r.trial_id === targetId);
|
|
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
|
}
|
|
if (text.includes('WHERE universe_market = $1')) {
|
|
const market = params?.[0] as string;
|
|
const bucket = params?.[1] as string;
|
|
const matched = rows.filter(
|
|
r => r.universe_market === market && r.horizon_bucket === bucket
|
|
);
|
|
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
|
}
|
|
}
|
|
|
|
return { rows: [], rowCount: 0 };
|
|
},
|
|
};
|
|
|
|
return state;
|
|
}
|
|
|
|
interface SyntheticEventFixture {
|
|
readonly listingIds: number[];
|
|
readonly allDates: string[];
|
|
readonly vaultCutoffDate: string;
|
|
readonly vaultCutoffTs: number;
|
|
readonly bars: BarRecord[];
|
|
readonly eventsTable: Table;
|
|
}
|
|
|
|
function buildSyntheticEventFixture(options?: {
|
|
preCutoffSessions?: number;
|
|
postCutoffSessions?: number;
|
|
listingCount?: number;
|
|
zeroVariance?: boolean;
|
|
}): SyntheticEventFixture {
|
|
const rand = createSeededRng(SEED);
|
|
const listingCount = options?.listingCount ?? 8;
|
|
const preCutoffSessions = options?.preCutoffSessions ?? 65;
|
|
const postCutoffSessions = options?.postCutoffSessions ?? 8;
|
|
const zeroVariance = options?.zeroVariance ?? false;
|
|
|
|
const allDates = makeBusinessDates('2022-11-01', preCutoffSessions + postCutoffSessions);
|
|
const vaultCutoffDate = allDates[preCutoffSessions]!;
|
|
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
|
|
const listingIds = Array.from({ length: listingCount }, (_, i) => 60_001 + i);
|
|
|
|
const bars: BarRecord[] = [];
|
|
const eventRows: TableRow[] = [];
|
|
const prices = Array.from({ length: listingCount }, (_, i) => 20 + i * 3);
|
|
|
|
// Place filings across multiple pre-cutoff dates (well inside window) and some post-cutoff.
|
|
const eventDayIndices = [12, 18, 26, 34, 42, 50];
|
|
const eventSet = new Set<string>();
|
|
for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) {
|
|
const t = eventDayIndices[eIdx]!;
|
|
if (t >= preCutoffSessions) {
|
|
continue;
|
|
}
|
|
// 2 listings per event date => 12 events across 6 distinct dates (spans pre and post 2023-01-01)
|
|
for (let k = 0; k < 2; k += 1) {
|
|
const l = (eIdx * 2 + k) % listingCount;
|
|
eventSet.add(`${t}:${l}`);
|
|
const date = allDates[t]!;
|
|
const ts = makeUtcMs(date, 14); // 09:00 ET intraday filing -> anchors on same session
|
|
const kind: EventKind = eIdx % 2 === 0 ? 'filing' : 'earnings';
|
|
const subtype = kind === 'filing' ? '8-K' : 'Q4';
|
|
eventRows.push({
|
|
listing_id: listingIds[l]!,
|
|
ts,
|
|
known_at: ts,
|
|
known_at_source: 'exact',
|
|
kind,
|
|
subtype,
|
|
payload_json: '{}',
|
|
});
|
|
}
|
|
}
|
|
|
|
for (let t = 0; t < allDates.length; t += 1) {
|
|
const date = allDates[t]!;
|
|
const closeTs = makeUtcMs(date, 21); // 16:00 ET close
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
let close: number;
|
|
if (zeroVariance) {
|
|
close = 100;
|
|
} else {
|
|
const isEvent = eventSet.has(`${t}:${l}`);
|
|
const base = (rand() - 0.5) * 0.015;
|
|
const dailyRet = isEvent ? base + 0.025 + l * 0.002 : base;
|
|
prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet));
|
|
close = Number(prices[l]!.toFixed(6));
|
|
}
|
|
bars.push({
|
|
listingId: listingIds[l]!,
|
|
ts: closeTs,
|
|
open: close,
|
|
high: close,
|
|
low: close,
|
|
close,
|
|
volume: 25_000,
|
|
vwap: close,
|
|
knownAt: closeTs,
|
|
});
|
|
}
|
|
}
|
|
|
|
return {
|
|
listingIds,
|
|
allDates,
|
|
vaultCutoffDate,
|
|
vaultCutoffTs,
|
|
bars,
|
|
eventsTable: {
|
|
columns: [...EVENTS_COLUMNS],
|
|
rows: eventRows,
|
|
},
|
|
};
|
|
}
|
|
|
|
interface FakeStoreState {
|
|
readonly store: MarketDataStore;
|
|
readonly barsCalls: BarsQuery[];
|
|
readonly eventsCalls: EventsQuery[];
|
|
readonly universeCalls: UniverseQuery[];
|
|
}
|
|
|
|
function createFakeStore(
|
|
fixture: SyntheticEventFixture,
|
|
options?: {
|
|
extraBars?: readonly BarRecord[];
|
|
extraEvents?: readonly TableRow[];
|
|
universeResolver?: (q: UniverseQuery) => number[];
|
|
barsError?: unknown;
|
|
eventsError?: unknown;
|
|
universeError?: unknown;
|
|
}
|
|
): FakeStoreState {
|
|
const barsCalls: BarsQuery[] = [];
|
|
const eventsCalls: EventsQuery[] = [];
|
|
const universeCalls: UniverseQuery[] = [];
|
|
|
|
const store: MarketDataStore = {
|
|
bars(q: BarsQuery): AsyncIterable<BarBatch> {
|
|
barsCalls.push(q);
|
|
const ids = new Set(q.listingIds);
|
|
const fromMs = parseBound(q.from, false);
|
|
const toMs = parseBound(q.to, true);
|
|
const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true);
|
|
const rows = fixture.bars.filter(
|
|
b =>
|
|
ids.has(b.listingId) &&
|
|
b.ts >= fromMs &&
|
|
b.ts <= toMs &&
|
|
b.ts <= asOfMs &&
|
|
b.knownAt <= asOfMs
|
|
);
|
|
const thrown = options?.barsError;
|
|
return {
|
|
async *[Symbol.asyncIterator]() {
|
|
if (thrown !== undefined) {
|
|
throw thrown;
|
|
}
|
|
yield { rows: [...rows, ...(options?.extraBars ?? [])] };
|
|
},
|
|
};
|
|
},
|
|
async events(q: EventsQuery): Promise<Table> {
|
|
eventsCalls.push(q);
|
|
if (options?.eventsError !== undefined) {
|
|
throw options.eventsError;
|
|
}
|
|
const kinds = new Set<string>(q.kinds);
|
|
const ids = q.listingIds !== undefined ? new Set(q.listingIds) : null;
|
|
const fromMs = parseBound(q.from, false);
|
|
const toMs = parseBound(q.to, true);
|
|
const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true);
|
|
const rows = fixture.eventsTable.rows.filter(r => {
|
|
if (!kinds.has(r.kind as string)) {
|
|
return false;
|
|
}
|
|
if (ids !== null && !ids.has(r.listing_id as number)) {
|
|
return false;
|
|
}
|
|
const ts = r.ts as number;
|
|
const knownAt = r.known_at as number;
|
|
return ts >= fromMs && ts <= toMs && knownAt <= asOfMs;
|
|
});
|
|
return {
|
|
columns: fixture.eventsTable.columns,
|
|
rows: [...rows, ...(options?.extraEvents ?? [])],
|
|
};
|
|
},
|
|
async universe(q: UniverseQuery): Promise<number[]> {
|
|
universeCalls.push(q);
|
|
if (options?.universeError !== undefined) {
|
|
throw options.universeError;
|
|
}
|
|
return options?.universeResolver ? options.universeResolver(q) : fixture.listingIds;
|
|
},
|
|
crossSection() {
|
|
throw new MarketDataStoreNotImplementedError('crossSection');
|
|
},
|
|
fundamentalsAsOf() {
|
|
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
|
},
|
|
shortsAsOf() {
|
|
throw new MarketDataStoreNotImplementedError('shortsAsOf');
|
|
},
|
|
macroAsOf() {
|
|
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
|
},
|
|
fx() {
|
|
throw new MarketDataStoreNotImplementedError('fx');
|
|
},
|
|
};
|
|
|
|
return { store, barsCalls, eventsCalls, universeCalls };
|
|
}
|
|
|
|
function createFakeCalendarResolver(
|
|
dates: readonly string[],
|
|
options?: {
|
|
hourUtc?: number;
|
|
error?: unknown;
|
|
}
|
|
): {
|
|
calls: EventStudyExchangeCalendarQuery[];
|
|
resolveExchangeCalendars: (
|
|
q: EventStudyExchangeCalendarQuery
|
|
) => Promise<EventStudyExchangeCalendars>;
|
|
} {
|
|
const calls: EventStudyExchangeCalendarQuery[] = [];
|
|
const hourUtc = options?.hourUtc ?? 21;
|
|
|
|
return {
|
|
calls,
|
|
async resolveExchangeCalendars(
|
|
q: EventStudyExchangeCalendarQuery
|
|
): Promise<EventStudyExchangeCalendars> {
|
|
calls.push(q);
|
|
if (options?.error !== undefined) {
|
|
throw options.error;
|
|
}
|
|
const sessions = dates
|
|
.filter(d => d >= q.fromDate && d <= q.toDate)
|
|
.map(date => ({ date, closeTs: makeUtcMs(date, hourUtc) }));
|
|
const listingCalendarId = new Map<number, string>();
|
|
for (const id of q.listingIds) {
|
|
listingCalendarId.set(id, 'XNYS');
|
|
}
|
|
return {
|
|
calendars: new Map([['XNYS', sessions]]),
|
|
listingCalendarId,
|
|
};
|
|
},
|
|
};
|
|
}
|
|
|
|
async function callEventStudy(
|
|
server: ReturnType<typeof createMcpServer>,
|
|
args: Record<string, unknown>,
|
|
id = 1
|
|
): Promise<{
|
|
rpc: Record<string, unknown>;
|
|
result?: { content: Array<{ type: string; text: string }>; isError?: boolean };
|
|
payload?: EventStudyResultPayload;
|
|
}> {
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id,
|
|
method: 'tools/call',
|
|
params: { name: 'event_study', arguments: args },
|
|
})
|
|
);
|
|
const rpc = JSON.parse(raw!) as Record<string, unknown>;
|
|
const result = rpc.result as
|
|
| { content: Array<{ type: string; text: string }>; isError?: boolean }
|
|
| undefined;
|
|
let payload: EventStudyResultPayload | undefined;
|
|
if (result !== undefined && !result.isError && result.content[0]?.text) {
|
|
payload = JSON.parse(result.content[0].text) as EventStudyResultPayload;
|
|
}
|
|
return { rpc, result, payload };
|
|
}
|
|
|
|
describe('MCP event_study tool', () => {
|
|
test('tools/list advertises strict JSON schema and exported bounds constants', async () => {
|
|
const fixture = buildSyntheticEventFixture();
|
|
const fakeStore = createFakeStore(fixture);
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(fixture.allDates);
|
|
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
expect(EVENT_STUDY_MAX_LISTING_IDS).toBe(500);
|
|
expect(EVENT_STUDY_MAX_PRE_DAYS).toBe(60);
|
|
expect(EVENT_STUDY_MAX_POST_DAYS).toBe(60);
|
|
expect(EVENT_STUDY_MAX_SUBTYPES).toBe(100);
|
|
expect(EVENT_STUDY_MAX_SUBTYPE_LENGTH).toBe(128);
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} })
|
|
);
|
|
const parsed = JSON.parse(raw!) as {
|
|
result: {
|
|
tools: Array<{
|
|
name: string;
|
|
inputSchema: {
|
|
type: string;
|
|
additionalProperties: boolean;
|
|
properties: Record<string, Record<string, unknown>>;
|
|
};
|
|
}>;
|
|
};
|
|
};
|
|
|
|
expect(parsed.result.tools).toHaveLength(1);
|
|
const tool = parsed.result.tools[0]!;
|
|
expect(tool.name).toBe('event_study');
|
|
expect(tool.inputSchema.type).toBe('object');
|
|
expect(tool.inputSchema.additionalProperties).toBe(false);
|
|
|
|
const props = tool.inputSchema.properties;
|
|
expect(props.scope).toBeUndefined();
|
|
expect(props.principalId).toBeUndefined();
|
|
expect(props.vaultCutoffDate).toBeUndefined();
|
|
expect(props.vault_evaluation_only).toBeUndefined();
|
|
|
|
const eventSchema = props.event as {
|
|
additionalProperties?: boolean;
|
|
properties?: {
|
|
subtypes?: {
|
|
maxItems?: number;
|
|
items?: { maxLength?: number };
|
|
};
|
|
};
|
|
};
|
|
expect(eventSchema.additionalProperties).toBe(false);
|
|
expect(eventSchema.properties?.subtypes?.maxItems).toBe(EVENT_STUDY_MAX_SUBTYPES);
|
|
expect(eventSchema.properties?.subtypes?.items?.maxLength).toBe(
|
|
EVENT_STUDY_MAX_SUBTYPE_LENGTH
|
|
);
|
|
});
|
|
|
|
test('happy path matches direct runEventStudy, writes one event_study trial, and omits raw series', async () => {
|
|
const fixture = buildSyntheticEventFixture();
|
|
const fakeStore = createFakeStore(fixture);
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(fixture.allDates);
|
|
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const from = fixture.allDates[0]!;
|
|
const to = fixture.allDates[64]!;
|
|
const preDays = 3;
|
|
const postDays = 5;
|
|
|
|
const { result, payload } = await callEventStudy(server, {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
event: { kinds: ['filing', 'earnings'] },
|
|
preDays,
|
|
postDays,
|
|
benchmark: 'equal_weight',
|
|
adjustment: 'raw',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
campaignId: CAMPAIGN_UUID,
|
|
hypothesisId: HYPOTHESIS_UUID,
|
|
});
|
|
|
|
expect(result?.isError).toBeUndefined();
|
|
expect(payload).toBeDefined();
|
|
expect(payload?.status).toBe('ok');
|
|
if (!payload || payload.status !== 'ok') {
|
|
throw new Error('Expected ok payload');
|
|
}
|
|
|
|
expect(payload.scope).toBe('vault_fenced');
|
|
expect(payload.vaultCutoffTs).toBe(fixture.vaultCutoffTs);
|
|
expect(payload.vaultCutoffDate).toBe(fixture.vaultCutoffDate);
|
|
expect(payload.clampedTo).toBe(false);
|
|
expect(payload.clampedAsOf).toBe(false);
|
|
expect(payload.listingCount).toBe(fixture.listingIds.length);
|
|
expect(payload.eventCount).toBe(12);
|
|
expect(payload.vaultExcludedEvents).toBe(0);
|
|
expect(payload.study.offsets).toHaveLength(preDays + postDays + 1);
|
|
expect(payload.study.hasBenchmark).toBe(true);
|
|
expect(payload.study.diagnostics.eventsUsed).toBeGreaterThanOrEqual(5);
|
|
expect(payload.study.clustered).not.toBeNull();
|
|
expect(payload.study.recency).not.toBeNull();
|
|
|
|
// Verify no raw arrays or typed series are exposed in the JSON payload.
|
|
const serialized = result!.content[0]!.text;
|
|
expect(serialized).not.toContain('entityReturns');
|
|
expect(serialized).not.toContain('benchmarkReturns');
|
|
expect(serialized).not.toContain('eventCars');
|
|
expect(serialized).not.toContain('meanCars');
|
|
expect(serialized).not.toContain('eventCounts');
|
|
|
|
// Verify trial_ledger write
|
|
expect(ledger.insertCalls).toBe(1);
|
|
expect(ledger.rows).toHaveLength(1);
|
|
const row = ledger.rows[0]!;
|
|
expect(row.stage).toBe('event_study');
|
|
expect(row.principal_id).toBe(AGENT_PRINCIPAL);
|
|
expect(row.universe_market).toBe('US_EQ');
|
|
expect(row.horizon_bucket).toBe('swing_1_10d');
|
|
expect(row.campaign_id).toBe(CAMPAIGN_UUID);
|
|
expect(row.hypothesis_id).toBe(HYPOTHESIS_UUID);
|
|
expect(row.sample_end < fixture.vaultCutoffDate).toBe(true);
|
|
expect(payload.trial.trialId).toBe(1);
|
|
expect(payload.deflatedSharpe.trialId).toBe(1);
|
|
expect(payload.deflatedSharpe.clusterSize).toBe(1);
|
|
|
|
// Direct parity check against buildEventStudyInput + runEventStudy
|
|
const directLedger = createFakeTrialLedger();
|
|
const directEvents = eventsTableToEventRows(fixture.eventsTable, {
|
|
kinds: ['earnings', 'filing'],
|
|
});
|
|
const directCal = await cal.resolveExchangeCalendars({
|
|
listingIds: fixture.listingIds,
|
|
fromDate: from,
|
|
toDate: to,
|
|
});
|
|
const directBuilt = buildEventStudyInput({
|
|
bars: fixture.bars.filter(b => b.ts < fixture.vaultCutoffTs),
|
|
events: directEvents,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
benchmark: 'equal_weight',
|
|
exchangeCalendars: directCal,
|
|
});
|
|
const directRun = await runEventStudy(directLedger.executor, {
|
|
principalId: AGENT_PRINCIPAL,
|
|
campaignId: CAMPAIGN_UUID,
|
|
hypothesisId: HYPOTHESIS_UUID,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
expression: {
|
|
expression: 'mcp:event_study:v1:earnings,filing',
|
|
params: {
|
|
version: 1,
|
|
kinds: ['earnings', 'filing'],
|
|
subtypes: null,
|
|
preDays,
|
|
postDays,
|
|
benchmark: 'equal_weight',
|
|
adjustment: 'raw',
|
|
effectiveFrom: payload.effectiveFrom,
|
|
effectiveTo: payload.effectiveTo,
|
|
effectiveAsOf: payload.effectiveAsOf,
|
|
},
|
|
universe: {
|
|
kind: 'listingIds',
|
|
listingIds: fixture.listingIds,
|
|
},
|
|
horizon: `${postDays}d`,
|
|
},
|
|
input: directBuilt.input,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
options: { preDays, postDays },
|
|
});
|
|
|
|
expect(directRun.status).toBe('ok');
|
|
if (directRun.status !== 'ok') {
|
|
throw new Error('Expected direct ok');
|
|
}
|
|
|
|
expect(payload.trial.expressionHash).toBe(directRun.trial.expressionHash);
|
|
expect(row.daily_series).toEqual(directLedger.rows[0]!.daily_series);
|
|
expect(payload.study.offsets).toEqual(
|
|
directRun.study.offsets.map(o => ({
|
|
offset: o.offset,
|
|
n: o.n,
|
|
aar: o.aar,
|
|
caar: o.caar,
|
|
caarFromZero: o.caarFromZero,
|
|
}))
|
|
);
|
|
});
|
|
|
|
test('replay with reordered/duplicated IDs, kinds, and subtypes yields identical expressionHash and results; param change alters hash', async () => {
|
|
const fixture = buildSyntheticEventFixture();
|
|
const from = fixture.allDates[0]!;
|
|
const to = fixture.allDates[64]!;
|
|
|
|
const runWithArgs = async (args: Record<string, unknown>) => {
|
|
const fakeStore = createFakeStore(fixture);
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(fixture.allDates);
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
const res = await callEventStudy(server, args);
|
|
expect(res.payload?.status).toBe('ok');
|
|
return res.payload as Extract<EventStudyResultPayload, { status: 'ok' }>;
|
|
};
|
|
|
|
const p1 = await runWithArgs({
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
event: { kinds: ['filing', 'earnings'], subtypes: ['8-K', 'Q4'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
const p2 = await runWithArgs({
|
|
listingIds: [...fixture.listingIds].reverse().concat(fixture.listingIds[0]!),
|
|
from,
|
|
to,
|
|
event: { kinds: ['earnings', 'filing', 'earnings'], subtypes: ['Q4', '8-K', 'Q4'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
expect(p2.trial.expressionHash).toBe(p1.trial.expressionHash);
|
|
expect(p2.study.offsets).toEqual(p1.study.offsets);
|
|
expect(p2.event.kinds).toEqual(['earnings', 'filing']);
|
|
expect(p2.event.subtypes).toEqual(['8-K', 'Q4']);
|
|
|
|
// Changing benchmark changes the expressionHash
|
|
const p3 = await runWithArgs({
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
event: { kinds: ['filing', 'earnings'], subtypes: ['8-K', 'Q4'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
benchmark: 'none',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
expect(p3.trial.expressionHash).not.toBe(p1.trial.expressionHash);
|
|
expect(p3.study.hasBenchmark).toBe(false);
|
|
expect(p1.study.hasBenchmark).toBe(true);
|
|
// With equal_weight benchmark vs none, AAR values differ when cross-sectional mean return is non-zero
|
|
expect(p3.study.offsets[2]!.aar).not.toBeCloseTo(p1.study.offsets[2]!.aar, 8);
|
|
});
|
|
|
|
test('Vault fence clamps to/asOf, filters leaky store rows, and matches clean replay', async () => {
|
|
const fixture = buildSyntheticEventFixture();
|
|
const from = fixture.allDates[0]!;
|
|
const postCutoffTo = fixture.allDates[fixture.allDates.length - 1]!;
|
|
const cutoffDate = fixture.vaultCutoffDate;
|
|
|
|
const poisonedEvents: TableRow[] = [
|
|
// Post-cutoff ts & known_at
|
|
{
|
|
listing_id: fixture.listingIds[0]!,
|
|
ts: makeUtcMs(cutoffDate, 14),
|
|
known_at: makeUtcMs(cutoffDate, 14),
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// Valid ts in window, but known_at in Vault
|
|
{
|
|
listing_id: fixture.listingIds[1]!,
|
|
ts: makeUtcMs(fixture.allDates[20]!, 14),
|
|
known_at: makeUtcMs(cutoffDate, 15),
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// Foreign listing
|
|
{
|
|
listing_id: 999_999,
|
|
ts: makeUtcMs(fixture.allDates[20]!, 14),
|
|
known_at: makeUtcMs(fixture.allDates[20]!, 14),
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// Before study window
|
|
{
|
|
listing_id: fixture.listingIds[2]!,
|
|
ts: makeUtcMs('2022-01-05', 14),
|
|
known_at: makeUtcMs('2022-01-05', 14),
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
];
|
|
|
|
const poisonedBars: BarRecord[] = [
|
|
// Post-cutoff bar with NaN close (must never be read or affect returns)
|
|
{
|
|
listingId: fixture.listingIds[0]!,
|
|
ts: makeUtcMs(cutoffDate, 21),
|
|
open: Number.NaN,
|
|
high: Number.NaN,
|
|
low: Number.NaN,
|
|
close: Number.NaN,
|
|
volume: 100,
|
|
knownAt: makeUtcMs(cutoffDate, 21),
|
|
},
|
|
// Foreign listing bar
|
|
{
|
|
listingId: 999_999,
|
|
ts: makeUtcMs(fixture.allDates[15]!, 21),
|
|
open: 50,
|
|
high: 50,
|
|
low: 50,
|
|
close: 50,
|
|
volume: 100,
|
|
knownAt: makeUtcMs(fixture.allDates[15]!, 21),
|
|
},
|
|
];
|
|
|
|
const leakyStore = createFakeStore(fixture, {
|
|
extraBars: poisonedBars,
|
|
extraEvents: poisonedEvents,
|
|
});
|
|
const leakyLedger = createFakeTrialLedger();
|
|
const leakyCal = createFakeCalendarResolver(fixture.allDates);
|
|
|
|
const leakyServer = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: leakyStore.store,
|
|
ledger: leakyLedger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: leakyCal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const leakyRes = await callEventStudy(leakyServer, {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to: postCutoffTo,
|
|
asOf: postCutoffTo,
|
|
event: { kinds: ['filing', 'earnings'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
expect(leakyRes.payload?.status).toBe('ok');
|
|
const leakyPayload = leakyRes.payload as Extract<EventStudyResultPayload, { status: 'ok' }>;
|
|
expect(leakyPayload.clampedTo).toBe(true);
|
|
expect(leakyPayload.clampedAsOf).toBe(true);
|
|
expect(leakyPayload.toMs).toBeLessThan(fixture.vaultCutoffTs);
|
|
expect(leakyPayload.asOfMs).toBeLessThan(fixture.vaultCutoffTs);
|
|
expect(leakyPayload.vaultExcludedEvents).toBe(2);
|
|
expect(leakyPayload.panelDiagnostics.vaultExcludedDates).toBe(1);
|
|
expect(leakyPayload.eventCount).toBe(12);
|
|
|
|
// Verify no store call received a bound >= vaultCutoffTs
|
|
expect(Date.parse(leakyStore.barsCalls[0]!.to)).toBeLessThan(fixture.vaultCutoffTs);
|
|
expect(Date.parse(leakyStore.barsCalls[0]!.asOf!)).toBeLessThan(fixture.vaultCutoffTs);
|
|
expect(Date.parse(leakyStore.eventsCalls[0]!.to)).toBeLessThan(fixture.vaultCutoffTs);
|
|
expect(Date.parse(leakyStore.eventsCalls[0]!.asOf!)).toBeLessThan(fixture.vaultCutoffTs);
|
|
expect(leakyCal.calls[0]!.toDate < fixture.vaultCutoffDate).toBe(true);
|
|
|
|
// Compare against clean store with same arguments
|
|
const cleanStore = createFakeStore(fixture);
|
|
const cleanLedger = createFakeTrialLedger();
|
|
const cleanCal = createFakeCalendarResolver(fixture.allDates);
|
|
const cleanServer = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: cleanStore.store,
|
|
ledger: cleanLedger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cleanCal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const cleanRes = await callEventStudy(cleanServer, {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to: postCutoffTo,
|
|
asOf: postCutoffTo,
|
|
event: { kinds: ['filing', 'earnings'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
const cleanPayload = cleanRes.payload as Extract<EventStudyResultPayload, { status: 'ok' }>;
|
|
expect(cleanPayload.panelDiagnostics.vaultExcludedDates).toBe(0);
|
|
expect(leakyPayload.study.offsets).toEqual(cleanPayload.study.offsets);
|
|
expect(leakyPayload.trial.expressionHash).toBe(cleanPayload.trial.expressionHash);
|
|
expect(leakyLedger.rows[0]!.daily_series).toEqual(cleanLedger.rows[0]!.daily_series);
|
|
});
|
|
|
|
test('named universe resolves strictly pre-start and earlier explicit asOf caps calendar & events', async () => {
|
|
const fixture = buildSyntheticEventFixture();
|
|
const fakeStore = createFakeStore(fixture);
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(fixture.allDates);
|
|
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: 'operator',
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const from = fixture.allDates[0]!; // 2022-11-01
|
|
const to = fixture.allDates[64]!;
|
|
const earlierAsOf = fixture.allDates[40]!; // Excludes events at day 42 and 50
|
|
|
|
const res = await callEventStudy(server, {
|
|
universe: 'US_EQ',
|
|
from,
|
|
to,
|
|
asOf: earlierAsOf,
|
|
event: { kinds: ['filing', 'earnings'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
expect(fakeStore.universeCalls).toHaveLength(1);
|
|
expect(fakeStore.universeCalls[0]!.ref).toBe('US_EQ');
|
|
expect(fakeStore.universeCalls[0]!.date).toBe('2022-10-31'); // Strictly before 2022-11-01
|
|
expect(cal.calls[0]!.toDate).toBe(earlierAsOf);
|
|
expect(res.payload?.status).toBe('ok');
|
|
expect(res.payload?.eventCount).toBe(8); // Only days 12, 18, 26, 34 (2 listings each)
|
|
expect(ledger.rows[0]!.principal_id).toBe('operator');
|
|
});
|
|
|
|
test('strict input schema rejects invalid arguments with zero dependency calls and accepts boundary windows', async () => {
|
|
const fixture = buildSyntheticEventFixture();
|
|
const fakeStore = createFakeStore(fixture);
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(fixture.allDates);
|
|
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const validBase = {
|
|
listingIds: [60_001],
|
|
from: fixture.allDates[0]!,
|
|
to: fixture.allDates[64]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 2,
|
|
postDays: 5,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const invalidCases: Record<string, unknown>[] = [
|
|
{ ...validBase, scope: 'vault_evaluation_only' },
|
|
{ ...validBase, principalId: 'operator' },
|
|
{ ...validBase, vaultCutoffDate: '2099-01-01' },
|
|
{ ...validBase, vault_evaluation_only: true },
|
|
{ ...validBase, extraKey: 123 },
|
|
{ ...validBase, event: { kinds: ['filing'], unknownNested: true } },
|
|
{ ...validBase, universe: 'US_EQ' }, // both listingIds and universe
|
|
{
|
|
from: fixture.allDates[0]!,
|
|
to: fixture.allDates[64]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 2,
|
|
postDays: 5,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
}, // neither selector
|
|
{ ...validBase, event: { kinds: [] } },
|
|
{ ...validBase, event: { kinds: ['unknown_kind'] } },
|
|
{ ...validBase, event: { kinds: ['filing'], subtypes: [] } },
|
|
{
|
|
...validBase,
|
|
event: {
|
|
kinds: ['filing'],
|
|
subtypes: Array.from({ length: EVENT_STUDY_MAX_SUBTYPES + 1 }, (_, i) => `SUB_${i}`),
|
|
},
|
|
},
|
|
{
|
|
...validBase,
|
|
event: {
|
|
kinds: ['filing'],
|
|
subtypes: ['x'.repeat(EVENT_STUDY_MAX_SUBTYPE_LENGTH + 1)],
|
|
},
|
|
},
|
|
{ ...validBase, preDays: -1 },
|
|
{ ...validBase, preDays: 61 },
|
|
{ ...validBase, preDays: 1.5 },
|
|
{ ...validBase, postDays: -1 },
|
|
{ ...validBase, postDays: 61 },
|
|
{ ...validBase, postDays: 2.5 },
|
|
{ ...validBase, postDays: 10, horizonBucket: 'position_10d_plus' },
|
|
{ ...validBase, postDays: 11, horizonBucket: 'swing_1_10d' },
|
|
{ ...validBase, campaignId: 'not-a-uuid' },
|
|
{ ...validBase, hypothesisId: 'not-a-uuid' },
|
|
{
|
|
universe: 'US_EQ',
|
|
from: fixture.allDates[0]!,
|
|
to: fixture.allDates[64]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 2,
|
|
postDays: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
];
|
|
|
|
for (let i = 0; i < invalidCases.length; i += 1) {
|
|
const res = await callEventStudy(server, invalidCases[i]!, i + 1);
|
|
expect(res.result?.isError).toBe(true);
|
|
expect(res.result?.content[0]?.text).toContain('Invalid arguments for tool "event_study"');
|
|
}
|
|
|
|
expect(fakeStore.barsCalls).toHaveLength(0);
|
|
expect(fakeStore.eventsCalls).toHaveLength(0);
|
|
expect(fakeStore.universeCalls).toHaveLength(0);
|
|
expect(cal.calls).toHaveLength(0);
|
|
expect(ledger.insertCalls).toBe(0);
|
|
|
|
// Valid boundary windows: 0, 10 (swing_1_10d), 11, 60 (position_10d_plus)
|
|
const boundaryWindows: Array<{ preDays: number; postDays: number; bucket: string }> = [
|
|
{ preDays: 0, postDays: 0, bucket: 'swing_1_10d' },
|
|
{ preDays: 0, postDays: 10, bucket: 'swing_1_10d' },
|
|
{ preDays: 11, postDays: 11, bucket: 'position_10d_plus' },
|
|
{ preDays: 60, postDays: 60, bucket: 'position_10d_plus' },
|
|
];
|
|
for (const w of boundaryWindows) {
|
|
const res = await callEventStudy(server, {
|
|
...validBase,
|
|
preDays: w.preDays,
|
|
postDays: w.postDays,
|
|
horizonBucket: w.bucket,
|
|
});
|
|
expect(res.result?.isError).toBeUndefined();
|
|
expect(res.payload).toBeDefined();
|
|
}
|
|
});
|
|
|
|
test('insufficient_data paths (empty universe, empty grid, below_min_events, zero_variance_series) write zero ledger rows', async () => {
|
|
const fixture = buildSyntheticEventFixture();
|
|
|
|
// 1. Empty resolved universe -> zero bars/events/calendar/ledger calls
|
|
{
|
|
const fakeStore = createFakeStore(fixture, { universeResolver: () => [] });
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(fixture.allDates);
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
const res = await callEventStudy(server, {
|
|
universe: 'US_EQ',
|
|
from: fixture.allDates[0]!,
|
|
to: fixture.allDates[64]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
expect(res.payload?.status).toBe('insufficient_data');
|
|
if (res.payload?.status === 'insufficient_data') {
|
|
expect(res.payload.reason).toBe('below_min_events');
|
|
}
|
|
expect(res.payload?.listingCount).toBe(0);
|
|
expect(fakeStore.barsCalls).toHaveLength(0);
|
|
expect(fakeStore.eventsCalls).toHaveLength(0);
|
|
expect(cal.calls).toHaveLength(0);
|
|
expect(ledger.insertCalls).toBe(0);
|
|
}
|
|
|
|
// 2. Empty session grid (no bars in range)
|
|
{
|
|
const emptyBarsFixture: SyntheticEventFixture = { ...fixture, bars: [] };
|
|
const fakeStore = createFakeStore(emptyBarsFixture);
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(fixture.allDates);
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
const res = await callEventStudy(server, {
|
|
listingIds: fixture.listingIds,
|
|
from: fixture.allDates[0]!,
|
|
to: fixture.allDates[64]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
expect(res.payload?.status).toBe('insufficient_data');
|
|
expect(res.payload?.eventCount).toBe(0);
|
|
expect(ledger.insertCalls).toBe(0);
|
|
}
|
|
|
|
// 3. Below minimum events (subtype with no matches)
|
|
{
|
|
const fakeStore = createFakeStore(fixture);
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(fixture.allDates);
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
const res = await callEventStudy(server, {
|
|
listingIds: fixture.listingIds,
|
|
from: fixture.allDates[0]!,
|
|
to: fixture.allDates[64]!,
|
|
event: { kinds: ['filing'], subtypes: ['NONEXISTENT_SUBTYPE'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
expect(res.payload?.status).toBe('insufficient_data');
|
|
if (res.payload?.status === 'insufficient_data') {
|
|
expect(res.payload.reason).toBe('below_min_events');
|
|
}
|
|
expect(ledger.insertCalls).toBe(0);
|
|
}
|
|
|
|
// 4. Zero-variance clustered CAR series
|
|
{
|
|
const flatFixture = buildSyntheticEventFixture({ zeroVariance: true });
|
|
const fakeStore = createFakeStore(flatFixture);
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(flatFixture.allDates);
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: flatFixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
const res = await callEventStudy(server, {
|
|
listingIds: flatFixture.listingIds,
|
|
from: flatFixture.allDates[0]!,
|
|
to: flatFixture.allDates[64]!,
|
|
event: { kinds: ['filing', 'earnings'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
benchmark: 'none',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
expect(res.payload?.status).toBe('insufficient_data');
|
|
if (res.payload?.status === 'insufficient_data') {
|
|
expect(res.payload.reason).toBe('zero_variance_series');
|
|
}
|
|
// Offsets are still projected when study.status === 'ok'
|
|
expect(res.payload?.study.offsets).toHaveLength(7);
|
|
expect(ledger.insertCalls).toBe(0);
|
|
}
|
|
});
|
|
|
|
test('factory option validation, wholly-in-Vault request, and sanitized error mapping without secret leaks', async () => {
|
|
const fixture = buildSyntheticEventFixture();
|
|
const fakeStore = createFakeStore(fixture);
|
|
const ledger = createFakeTrialLedger();
|
|
const cal = createFakeCalendarResolver(fixture.allDates);
|
|
const SECRET = 'SECRET_MARKER_SQL_URI_88421';
|
|
|
|
// Factory option validation
|
|
expect(() =>
|
|
createEventStudyTool({
|
|
store: {} as MarketDataStore,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
})
|
|
).toThrow(MarketDataStoreValidationError);
|
|
|
|
expect(() =>
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: {} as TrialLedgerExecutor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
})
|
|
).toThrow(SignalStudyError);
|
|
|
|
expect(() =>
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: null as unknown as typeof cal.resolveExchangeCalendars,
|
|
})
|
|
).toThrow(EventPanelError);
|
|
|
|
expect(() =>
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: 'invalid-principal',
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
})
|
|
).toThrow(TrialLedgerError);
|
|
|
|
expect(() =>
|
|
createEventStudyTool({
|
|
store: fakeStore.store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: Number.NaN },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: cal.resolveExchangeCalendars,
|
|
})
|
|
).toThrow(MarketDataStoreValidationError);
|
|
|
|
// Request wholly in Vault -> zero dependency calls
|
|
{
|
|
const s = createFakeStore(fixture);
|
|
const l = createFakeTrialLedger();
|
|
const c = createFakeCalendarResolver(fixture.allDates);
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: s.store,
|
|
ledger: l.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: c.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
const res = await callEventStudy(server, {
|
|
listingIds: fixture.listingIds,
|
|
from: fixture.vaultCutoffDate,
|
|
to: fixture.allDates[fixture.allDates.length - 1]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
expect(res.result?.isError).toBe(true);
|
|
expect(res.result?.content[0]?.text).toContain('VaultHoldoutFenceError');
|
|
expect(s.barsCalls).toHaveLength(0);
|
|
expect(s.eventsCalls).toHaveLength(0);
|
|
expect(c.calls).toHaveLength(0);
|
|
expect(l.insertCalls).toBe(0);
|
|
}
|
|
|
|
const baseArgs = {
|
|
listingIds: fixture.listingIds,
|
|
from: fixture.allDates[0]!,
|
|
to: fixture.allDates[64]!,
|
|
event: { kinds: ['filing', 'earnings'] },
|
|
preDays: 2,
|
|
postDays: 4,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const errorCases: Array<{
|
|
name: string;
|
|
storeOpts?: Parameters<typeof createFakeStore>[1];
|
|
calError?: unknown;
|
|
ledgerOpts?: Parameters<typeof createFakeTrialLedger>[0];
|
|
expectedPrefix: string;
|
|
}> = [
|
|
{
|
|
name: 'store VaultHoldoutFenceError',
|
|
storeOpts: {
|
|
barsError: new VaultHoldoutFenceError('2025-01-01', 1, 1, `leak ${SECRET}`),
|
|
},
|
|
expectedPrefix: 'VaultHoldoutFenceError:',
|
|
},
|
|
{
|
|
name: 'store VaultScopeNotAuthorizedError',
|
|
storeOpts: { barsError: new VaultScopeNotAuthorizedError(`leak ${SECRET}`) },
|
|
expectedPrefix: 'VaultScopeNotAuthorizedError:',
|
|
},
|
|
{
|
|
name: 'store MarketDataStoreValidationError',
|
|
storeOpts: {
|
|
eventsError: new MarketDataStoreValidationError(`leak ${SECRET}`, 'from'),
|
|
},
|
|
expectedPrefix: 'MarketDataStoreValidationError:',
|
|
},
|
|
{
|
|
name: 'store MarketDataStoreNotImplementedError',
|
|
storeOpts: {
|
|
eventsError: new MarketDataStoreNotImplementedError('events', `leak ${SECRET}`),
|
|
},
|
|
expectedPrefix: 'MarketDataStoreNotImplementedError:',
|
|
},
|
|
{
|
|
name: 'store AdjFactorsSnapshotError',
|
|
storeOpts: {
|
|
barsError: new AdjFactorsSnapshotError('missing_snapshot', `leak ${SECRET}`),
|
|
},
|
|
expectedPrefix: 'AdjFactorsSnapshotError:',
|
|
},
|
|
{
|
|
name: 'calendar resolver generic Error',
|
|
calError: new Error(`calendar db down ${SECRET}`),
|
|
expectedPrefix: 'Error: Exchange calendar resolution failed.',
|
|
},
|
|
{
|
|
name: 'calendar resolver EventPanelError',
|
|
calError: new EventPanelError('invalid_option', `bad cal ${SECRET}`),
|
|
expectedPrefix: 'EventPanelError:',
|
|
},
|
|
{
|
|
name: 'SignalStudyError from store/runner',
|
|
storeOpts: {
|
|
eventsError: new SignalStudyError('invalid_panel', `bad panel ${SECRET}`),
|
|
},
|
|
expectedPrefix: 'SignalStudyError:',
|
|
},
|
|
{
|
|
name: 'TrialLedgerError on INSERT',
|
|
ledgerOpts: {
|
|
insertError: new TrialLedgerError('VAULT_FENCE_VIOLATION', `pg detail ${SECRET}`),
|
|
},
|
|
expectedPrefix: 'TrialLedgerError:',
|
|
},
|
|
];
|
|
|
|
for (const tc of errorCases) {
|
|
const s = createFakeStore(fixture, tc.storeOpts);
|
|
const l = createFakeTrialLedger(tc.ledgerOpts);
|
|
const c = createFakeCalendarResolver(fixture.allDates, { error: tc.calError });
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: s.store,
|
|
ledger: l.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: c.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const res = await callEventStudy(server, baseArgs);
|
|
expect(res.result?.isError).toBe(true);
|
|
const text = res.result?.content[0]?.text ?? '';
|
|
expect(text).toContain(tc.expectedPrefix);
|
|
expect(text).not.toContain(SECRET);
|
|
}
|
|
|
|
// Post-insert DSR read failure: trial is recorded once (no retry) and sanitized message informs caller
|
|
{
|
|
const s = createFakeStore(fixture);
|
|
const l = createFakeTrialLedger({
|
|
dsrReadError: new Error(`pg select timeout ${SECRET}`),
|
|
});
|
|
const c = createFakeCalendarResolver(fixture.allDates);
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: s.store,
|
|
ledger: l.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: c.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const res = await callEventStudy(server, baseArgs);
|
|
expect(res.result?.isError).toBe(true);
|
|
const text = res.result?.content[0]?.text ?? '';
|
|
expect(text).toBe(
|
|
'SignalStudyError: Trial was recorded, but cluster deflated Sharpe evaluation failed.'
|
|
);
|
|
expect(text).not.toContain(SECRET);
|
|
expect(l.insertCalls).toBe(1);
|
|
expect(l.rows).toHaveLength(1);
|
|
}
|
|
});
|
|
});
|