1116 lines
37 KiB
TypeScript
1116 lines
37 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import type { EventStudyExchangeCalendars } from '../src/event-panel';
|
|
import type {
|
|
BarBatch,
|
|
BarRecord,
|
|
EventKind,
|
|
MarketDataStore,
|
|
Table,
|
|
TableRow,
|
|
} from '../src/market-data-store';
|
|
import {
|
|
type BarsQuery,
|
|
EVENTS_COLUMNS,
|
|
type EventsQuery,
|
|
MarketDataStoreNotImplementedError,
|
|
type UniverseQuery,
|
|
} from '../src/market-data-store-duckdb';
|
|
import {
|
|
type EventStudyExchangeCalendarQuery,
|
|
type EventStudyResultPayload,
|
|
createEventStudyTool,
|
|
createMcpServer,
|
|
} from '../src/mcp/index';
|
|
import type { TrialLedgerExecutor } from '../src/trial-ledger';
|
|
|
|
// QA fixture: deterministic synthetic equity bars & events with explicit
|
|
// half-day closes, intraday Vault cutoffs, exact boundary timestamps, and
|
|
// malformed rows. Models gross daily close-to-close returns, raw adjustment,
|
|
// no fills or transaction costs.
|
|
const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
|
|
|
function makeBusinessDates(startDate: string, count: number): string[] {
|
|
const out: string[] = [];
|
|
const current = new Date(`${startDate}T00:00:00.000Z`);
|
|
while (out.length < count) {
|
|
const day = current.getUTCDay();
|
|
if (day !== 0 && day !== 6) {
|
|
out.push(current.toISOString().slice(0, 10));
|
|
}
|
|
current.setUTCDate(current.getUTCDate() + 1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function utcMs(date: string, hour: number, minute = 0, second = 0, ms = 0): number {
|
|
const [y, m, d] = date.split('-').map(Number);
|
|
return Date.UTC(y!, m! - 1, d!, hour, minute, second, ms);
|
|
}
|
|
|
|
function createFakeLedger(): {
|
|
executor: TrialLedgerExecutor;
|
|
insertCalls: number;
|
|
rows: Array<{ expression_hash: string; daily_series: number[] }>;
|
|
} {
|
|
const rows: Array<{ expression_hash: string; daily_series: number[] }> = [];
|
|
let nextId = 1;
|
|
const state = {
|
|
rows,
|
|
insertCalls: 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;
|
|
const p = params ?? [];
|
|
const id = nextId++;
|
|
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
|
rows.push({
|
|
expression_hash: p[6] as string,
|
|
daily_series: dailySeries,
|
|
});
|
|
return {
|
|
rows: [
|
|
{
|
|
trial_id: String(id),
|
|
created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, id)),
|
|
} as unknown as Row,
|
|
],
|
|
rowCount: 1,
|
|
};
|
|
}
|
|
if (trimmed.startsWith('SELECT')) {
|
|
const storedRows = rows.map((r, idx) => ({
|
|
trial_id: String(idx + 1),
|
|
created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, idx + 1)),
|
|
principal_id: AGENT_PRINCIPAL,
|
|
campaign_id: null,
|
|
stage: 'event_study',
|
|
universe_market: 'US_EQ',
|
|
horizon_bucket: 'swing_1_10d',
|
|
hypothesis_id: null,
|
|
expression_hash: r.expression_hash,
|
|
sample_start: '2023-01-02',
|
|
sample_end: '2023-02-01',
|
|
n_obs: r.daily_series.length,
|
|
sharpe_unann: 0.5,
|
|
skewness: 0,
|
|
kurtosis: 3,
|
|
daily_series: r.daily_series,
|
|
}));
|
|
return { rows: storedRows as unknown as Row[], rowCount: storedRows.length };
|
|
}
|
|
return { rows: [], rowCount: 0 };
|
|
},
|
|
};
|
|
|
|
return state;
|
|
}
|
|
|
|
function createPassThroughStore(params: {
|
|
bars: readonly BarRecord[];
|
|
eventsTable: Table;
|
|
}): MarketDataStore {
|
|
return {
|
|
bars(_q: BarsQuery): AsyncIterable<BarBatch> {
|
|
return {
|
|
async *[Symbol.asyncIterator]() {
|
|
yield { rows: [...params.bars] };
|
|
},
|
|
};
|
|
},
|
|
async events(_q: EventsQuery): Promise<Table> {
|
|
return params.eventsTable;
|
|
},
|
|
async universe(_q: UniverseQuery): Promise<number[]> {
|
|
return [];
|
|
},
|
|
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');
|
|
},
|
|
};
|
|
}
|
|
|
|
async function invoke(
|
|
server: ReturnType<typeof createMcpServer>,
|
|
args: Record<string, unknown>
|
|
): Promise<{
|
|
isError?: boolean;
|
|
text: string;
|
|
payload?: EventStudyResultPayload;
|
|
}> {
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 1,
|
|
method: 'tools/call',
|
|
params: { name: 'event_study', arguments: args },
|
|
})
|
|
);
|
|
const rpc = JSON.parse(raw!) as {
|
|
result: { content: Array<{ type: string; text: string }>; isError?: boolean };
|
|
};
|
|
const text = rpc.result.content[0]!.text;
|
|
return {
|
|
isError: rpc.result.isError,
|
|
text,
|
|
payload: rpc.result.isError ? undefined : (JSON.parse(text) as EventStudyResultPayload),
|
|
};
|
|
}
|
|
|
|
describe('MCP event_study QA edge cases', () => {
|
|
test('event released after a half-day close anchors to the next trading session, not the half-day', async () => {
|
|
const dates = makeBusinessDates('2023-05-01', 25);
|
|
const vaultCutoffDate = dates[24]!;
|
|
const vaultCutoffTs = utcMs(vaultCutoffDate, 0);
|
|
const listingIds = [101, 102, 103, 104, 105, 106];
|
|
|
|
// Make day index 8 a half-day (closes at 18:00 UTC = 13:00 ET instead of 21:00 UTC).
|
|
// Place 6 events across days 8 and 14, released at 19:00 UTC (after 18:00 UTC half-day close,
|
|
// before 21:00 UTC bar stamp). For half-day (index 8), events must anchor to index 9!
|
|
// Put a +10% jump on index 9 and +20% jump on index 15 (next day after 14, also half-day),
|
|
// and 0% return on index 8 and 14 so AAR at offset 0 proves next-session anchoring.
|
|
const halfDayIndices = new Set([8, 14]);
|
|
const jumpDayReturns = new Map<number, number>([
|
|
[9, 0.1],
|
|
[15, 0.2],
|
|
]);
|
|
|
|
const bars: BarRecord[] = [];
|
|
for (const id of listingIds) {
|
|
let price = 100;
|
|
for (let t = 0; t < 24; t += 1) {
|
|
const ret = jumpDayReturns.get(t) ?? 0;
|
|
price = Number((price * (1 + ret)).toFixed(6));
|
|
const ts = utcMs(dates[t]!, 21); // bars_1d always stamped 16:00 ET (21:00 UTC)
|
|
bars.push({
|
|
listingId: id,
|
|
ts,
|
|
open: price,
|
|
high: price,
|
|
low: price,
|
|
close: price,
|
|
volume: 10_000,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
|
|
const eventRows: TableRow[] = [];
|
|
for (let i = 0; i < 3; i += 1) {
|
|
// Released at 19:00 UTC on half-day index 8 -> anchors to index 9 (+10%)
|
|
eventRows.push({
|
|
listing_id: listingIds[i]!,
|
|
ts: utcMs(dates[8]!, 19),
|
|
known_at: utcMs(dates[8]!, 19),
|
|
known_at_source: 'exact',
|
|
kind: 'filing' as EventKind,
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
});
|
|
}
|
|
for (let i = 3; i < 6; i += 1) {
|
|
// Released at 19:00 UTC on half-day index 14 -> anchors to index 15 (+20%)
|
|
eventRows.push({
|
|
listing_id: listingIds[i]!,
|
|
ts: utcMs(dates[14]!, 19),
|
|
known_at: utcMs(dates[14]!, 19),
|
|
known_at_source: 'exact',
|
|
kind: 'filing' as EventKind,
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
});
|
|
}
|
|
|
|
const store = createPassThroughStore({
|
|
bars,
|
|
eventsTable: { columns: [...EVENTS_COLUMNS], rows: eventRows },
|
|
});
|
|
const ledger = createFakeLedger();
|
|
|
|
const resolveExchangeCalendars = async (
|
|
q: EventStudyExchangeCalendarQuery
|
|
): Promise<EventStudyExchangeCalendars> => {
|
|
const sessions = dates
|
|
.filter(d => d >= q.fromDate && d <= q.toDate)
|
|
.map((date, _idx) => {
|
|
const globalIdx = dates.indexOf(date);
|
|
const closeHour = halfDayIndices.has(globalIdx) ? 18 : 21;
|
|
return { date, closeTs: utcMs(date, closeHour) };
|
|
});
|
|
const listingCalendarId = new Map<number, string>();
|
|
for (const id of q.listingIds) {
|
|
listingCalendarId.set(id, 'XNYS');
|
|
}
|
|
return {
|
|
calendars: new Map([['XNYS', sessions]]),
|
|
listingCalendarId,
|
|
};
|
|
};
|
|
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const res = await invoke(server, {
|
|
listingIds,
|
|
from: dates[0]!,
|
|
to: dates[23]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 1,
|
|
postDays: 1,
|
|
benchmark: 'none',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
expect(res.isError).toBeUndefined();
|
|
expect(res.payload?.status).toBe('ok');
|
|
if (res.payload?.status !== 'ok') {
|
|
throw new Error('Expected ok');
|
|
}
|
|
|
|
// Offset -1 is the half-day itself (0% return); Offset 0 is the next session (mean of +10% and +20% = +15%).
|
|
const offsetMinus1 = res.payload.study.offsets.find(o => o.offset === -1)!;
|
|
const offset0 = res.payload.study.offsets.find(o => o.offset === 0)!;
|
|
expect(offsetMinus1.aar).toBeCloseTo(0, 8);
|
|
expect(offset0.aar).toBeCloseTo(0.15, 8);
|
|
});
|
|
|
|
test('intraday Vault cutoff excludes rows on the cutoff UTC day and handles start-on-cutoff-day safely', async () => {
|
|
const dates = makeBusinessDates('2023-06-01', 25);
|
|
const cutoffDate = dates[20]!;
|
|
// Intraday Vault cutoff at 12:00 UTC on cutoffDate
|
|
const vaultCutoffTs = utcMs(cutoffDate, 12);
|
|
const listingIds = [201, 202, 203, 204, 205, 206];
|
|
|
|
const bars: BarRecord[] = [];
|
|
for (const id of listingIds) {
|
|
let price = 50;
|
|
for (let t = 0; t < 22; t += 1) {
|
|
price = Number((price * (1 + (t % 3 === 0 ? 0.02 : -0.005))).toFixed(6));
|
|
const ts = t === 20 ? utcMs(dates[t]!, 10) : utcMs(dates[t]!, 21); // Bar on cutoff day at 10:00 UTC (< cutoffTs!)
|
|
bars.push({
|
|
listingId: id,
|
|
ts,
|
|
open: price,
|
|
high: price,
|
|
low: price,
|
|
close: price,
|
|
volume: 5_000,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
|
|
const baseEvents: TableRow[] = [
|
|
// 6 valid pre-cutoff events across 2 dates
|
|
...listingIds.slice(0, 3).map(id => ({
|
|
listing_id: id,
|
|
ts: utcMs(dates[6]!, 14),
|
|
known_at: utcMs(dates[6]!, 14),
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
})),
|
|
...listingIds.slice(3, 6).map(id => ({
|
|
listing_id: id,
|
|
ts: utcMs(dates[12]!, 14),
|
|
known_at: utcMs(dates[12]!, 14),
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
})),
|
|
];
|
|
|
|
const intradayCutoffEvents: TableRow[] = [
|
|
// Event on cutoff UTC day BEFORE intraday vaultCutoffTs (10:00 UTC < 12:00 UTC) -> MUST be excluded!
|
|
{
|
|
listing_id: listingIds[0]!,
|
|
ts: utcMs(cutoffDate, 10),
|
|
known_at: utcMs(cutoffDate, 10),
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// Valid ts earlier, but known_at on cutoff UTC day at 09:00 UTC (< 12:00 UTC) -> MUST be excluded!
|
|
{
|
|
listing_id: listingIds[1]!,
|
|
ts: utcMs(dates[10]!, 14),
|
|
known_at: utcMs(cutoffDate, 9),
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// Unrequested valid kind on cutoff day -> MUST NOT inflate vaultExcludedEvents
|
|
{
|
|
listing_id: listingIds[2]!,
|
|
ts: utcMs(cutoffDate, 10),
|
|
known_at: utcMs(cutoffDate, 10),
|
|
known_at_source: 'exact',
|
|
kind: 'ceo_post',
|
|
subtype: null,
|
|
payload_json: '{}',
|
|
},
|
|
];
|
|
|
|
const calendarCalls: EventStudyExchangeCalendarQuery[] = [];
|
|
const resolveExchangeCalendars = async (
|
|
q: EventStudyExchangeCalendarQuery
|
|
): Promise<EventStudyExchangeCalendars> => {
|
|
calendarCalls.push(q);
|
|
const sessions = dates
|
|
.filter(d => d >= q.fromDate && d <= q.toDate)
|
|
.map(date => ({ date, closeTs: utcMs(date, 21) }));
|
|
const listingCalendarId = new Map<number, string>();
|
|
for (const id of q.listingIds) {
|
|
listingCalendarId.set(id, 'XNYS');
|
|
}
|
|
return { calendars: new Map([['XNYS', sessions]]), listingCalendarId };
|
|
};
|
|
|
|
const store = createPassThroughStore({
|
|
bars,
|
|
eventsTable: {
|
|
columns: [...EVENTS_COLUMNS],
|
|
rows: [...baseEvents, ...intradayCutoffEvents],
|
|
},
|
|
});
|
|
const ledger = createFakeLedger();
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const res = await invoke(server, {
|
|
listingIds,
|
|
from: dates[0]!,
|
|
to: dates[21]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 2,
|
|
postDays: 2,
|
|
benchmark: 'none',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
expect(res.payload?.status).toBe('ok');
|
|
expect(res.payload?.vaultExcludedEvents).toBe(2);
|
|
expect(res.payload?.panelDiagnostics.vaultExcludedDates).toBe(2);
|
|
expect(res.payload?.eventCount).toBe(6);
|
|
expect(calendarCalls[0]!.toDate < cutoffDate).toBe(true);
|
|
|
|
// Request starting on the intraday cutoff day before vaultCutoffTs:
|
|
// returns insufficient_data cleanly without calling calendar resolver with inverted dates.
|
|
calendarCalls.length = 0;
|
|
const ledger2 = createFakeLedger();
|
|
const server2 = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store,
|
|
ledger: ledger2.executor,
|
|
vaultContext: { vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const startOnCutoffRes = await invoke(server2, {
|
|
listingIds,
|
|
from: `${cutoffDate}T01:00:00.000Z`,
|
|
to: `${cutoffDate}T11:00:00.000Z`,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 1,
|
|
postDays: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
expect(startOnCutoffRes.isError).toBeUndefined();
|
|
expect(startOnCutoffRes.payload?.status).toBe('insufficient_data');
|
|
expect(calendarCalls).toHaveLength(0);
|
|
expect(ledger2.insertCalls).toBe(0);
|
|
});
|
|
|
|
test('exact boundary timestamps (fromMs, toMs, asOfMs) and malformed ts rejection', async () => {
|
|
const dates = makeBusinessDates('2023-07-03', 20);
|
|
const vaultCutoffDate = dates[19]!;
|
|
const vaultCutoffTs = utcMs(vaultCutoffDate, 0);
|
|
const listingIds = [301, 302, 303, 304, 305, 306];
|
|
|
|
const bars: BarRecord[] = [];
|
|
for (const id of listingIds) {
|
|
let price = 30;
|
|
for (let t = 0; t < 19; t += 1) {
|
|
price = Number((price * (1 + (t % 2 === 0 ? 0.015 : -0.005))).toFixed(6));
|
|
const ts = utcMs(dates[t]!, 21);
|
|
bars.push({
|
|
listingId: id,
|
|
ts,
|
|
open: price,
|
|
high: price,
|
|
low: price,
|
|
close: price,
|
|
volume: 1_000,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
|
|
const fromIso = `${dates[2]}T00:00:00.000Z`;
|
|
const toIso = `${dates[15]}T23:59:59.999Z`;
|
|
const asOfIso = `${dates[14]}T21:00:00.000Z`;
|
|
const fromMs = Date.parse(fromIso);
|
|
const toMs = Date.parse(toIso);
|
|
const asOfMs = Date.parse(asOfIso);
|
|
|
|
const rows: TableRow[] = [
|
|
// Exact fromMs -> included
|
|
{
|
|
listing_id: listingIds[0]!,
|
|
ts: fromMs,
|
|
known_at: fromMs,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// fromMs - 1 -> excluded
|
|
{
|
|
listing_id: listingIds[1]!,
|
|
ts: fromMs - 1,
|
|
known_at: fromMs - 1,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// Exact asOfMs -> included
|
|
{
|
|
listing_id: listingIds[2]!,
|
|
ts: utcMs(dates[10]!, 14),
|
|
known_at: asOfMs,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// asOfMs + 1 -> excluded
|
|
{
|
|
listing_id: listingIds[3]!,
|
|
ts: utcMs(dates[10]!, 14),
|
|
known_at: asOfMs + 1,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// toMs + 1 -> excluded
|
|
{
|
|
listing_id: listingIds[4]!,
|
|
ts: toMs + 1,
|
|
known_at: asOfMs,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
];
|
|
|
|
const resolveExchangeCalendars = async (
|
|
q: EventStudyExchangeCalendarQuery
|
|
): Promise<EventStudyExchangeCalendars> => {
|
|
const sessions = dates
|
|
.filter(d => d >= q.fromDate && d <= q.toDate)
|
|
.map(date => ({ date, closeTs: utcMs(date, 21) }));
|
|
const listingCalendarId = new Map<number, string>();
|
|
for (const id of q.listingIds) {
|
|
listingCalendarId.set(id, 'XNYS');
|
|
}
|
|
return { calendars: new Map([['XNYS', sessions]]), listingCalendarId };
|
|
};
|
|
|
|
const store = createPassThroughStore({
|
|
bars,
|
|
eventsTable: { columns: [...EVENTS_COLUMNS], rows },
|
|
});
|
|
const ledger = createFakeLedger();
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const res = await invoke(server, {
|
|
listingIds,
|
|
from: fromIso,
|
|
to: toIso,
|
|
asOf: asOfIso,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 1,
|
|
postDays: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
// Only 2 events survived the exact boundaries (fromMs and asOfMs) -> insufficient_data (< 5)
|
|
expect(res.payload?.status).toBe('insufficient_data');
|
|
expect(res.payload?.eventCount).toBe(2);
|
|
expect(ledger.insertCalls).toBe(0);
|
|
|
|
// Malformed `ts` on an otherwise eligible event row must fail with sanitized EventPanelError
|
|
const malformedStore = createPassThroughStore({
|
|
bars,
|
|
eventsTable: {
|
|
columns: [...EVENTS_COLUMNS],
|
|
rows: [
|
|
{
|
|
listing_id: listingIds[0]!,
|
|
ts: 'not-a-timestamp' as unknown as number,
|
|
known_at: fromMs,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const malformedLedger = createFakeLedger();
|
|
const malformedServer = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: malformedStore,
|
|
ledger: malformedLedger.executor,
|
|
vaultContext: { vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const badRes = await invoke(malformedServer, {
|
|
listingIds,
|
|
from: fromIso,
|
|
to: toIso,
|
|
asOf: asOfIso,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 1,
|
|
postDays: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
|
|
expect(badRes.isError).toBe(true);
|
|
expect(badRes.text).toBe('EventPanelError: Event table data failed event panel validation.');
|
|
expect(malformedLedger.insertCalls).toBe(0);
|
|
});
|
|
|
|
test('microsecond-precision from rejects leaked boundary-millisecond event and matches clean run', async () => {
|
|
const dates = makeBusinessDates('2023-07-03', 24);
|
|
const vaultCutoffDate = dates[23]!;
|
|
const vaultCutoffTs = utcMs(vaultCutoffDate, 0);
|
|
const listingIds = [401, 402, 403, 404, 405, 406];
|
|
|
|
const bars: BarRecord[] = [];
|
|
for (let l = 0; l < listingIds.length; l += 1) {
|
|
const id = listingIds[l]!;
|
|
let price = 40 + l * 2;
|
|
for (let t = 0; t < 23; t += 1) {
|
|
// Distinct per-listing returns on dates[3] so admitting listingIds[1] at .123Z
|
|
// measurably shifts eventCount, eventsUsed, CAR, and ledger daily_series.
|
|
const ret =
|
|
t === 3
|
|
? l === 1
|
|
? 0.25
|
|
: 0.05
|
|
: t === 9
|
|
? 0.03 + l * 0.004
|
|
: t === 15
|
|
? -0.02 + l * 0.003
|
|
: 0.002;
|
|
price = Number((price * (1 + ret)).toFixed(6));
|
|
const ts = utcMs(dates[t]!, 21);
|
|
bars.push({
|
|
listingId: id,
|
|
ts,
|
|
open: price,
|
|
high: price,
|
|
low: price,
|
|
close: price,
|
|
volume: 10_000,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Researcher sets microsecond-precision start on half-day dates[2] (18:00 UTC close, 21:00 UTC bar stamp):
|
|
// bars from dates[2]..dates[22] enter the panel, so dates[3] (session index 1) has finite close-to-close returns.
|
|
// A leaked filing at 19:00:00.123Z (< .123456Z) would anchor to dates[3] and shift CAR/daily_series if admitted.
|
|
// A valid filing at 19:00:00.124Z (> .123456Z) must be admitted and anchored to dates[3].
|
|
const microFromIso = `${dates[2]}T19:00:00.123456Z`;
|
|
const leakedBoundaryMs = Date.parse(`${dates[2]}T19:00:00.123Z`);
|
|
const admittedNextMs = Date.parse(`${dates[2]}T19:00:00.124Z`);
|
|
|
|
const validRows: TableRow[] = [
|
|
// Admitted event at fromMs + 1 (.124Z) -> anchors to dates[3] (after dates[2] 18:00 UTC half-day close)
|
|
{
|
|
listing_id: listingIds[0]!,
|
|
ts: admittedNextMs,
|
|
known_at: admittedNextMs,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
},
|
|
// 3 events on dates[9]
|
|
...listingIds.slice(0, 3).map(id => ({
|
|
listing_id: id,
|
|
ts: utcMs(dates[9]!, 14),
|
|
known_at: utcMs(dates[9]!, 14),
|
|
known_at_source: 'exact',
|
|
kind: 'filing' as EventKind,
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
})),
|
|
// 3 events on dates[15]
|
|
...listingIds.slice(3, 6).map(id => ({
|
|
listing_id: id,
|
|
ts: utcMs(dates[15]!, 14),
|
|
known_at: utcMs(dates[15]!, 14),
|
|
known_at_source: 'exact',
|
|
kind: 'filing' as EventKind,
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
})),
|
|
];
|
|
|
|
// Leaked out-of-window filing at .123Z (strictly before .123456Z) on listingIds[1] (+25% on dates[3]).
|
|
const leakedRow: TableRow = {
|
|
listing_id: listingIds[1]!,
|
|
ts: leakedBoundaryMs,
|
|
known_at: leakedBoundaryMs,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
};
|
|
|
|
const resolveExchangeCalendars = async (
|
|
q: EventStudyExchangeCalendarQuery
|
|
): Promise<EventStudyExchangeCalendars> => {
|
|
const sessions = dates
|
|
.filter(d => d >= q.fromDate && d <= q.toDate)
|
|
.map(date => ({
|
|
date,
|
|
closeTs: utcMs(date, date === dates[2] ? 18 : 21),
|
|
}));
|
|
const listingCalendarId = new Map<number, string>();
|
|
for (const id of q.listingIds) {
|
|
listingCalendarId.set(id, 'XNYS');
|
|
}
|
|
return { calendars: new Map([['XNYS', sessions]]), listingCalendarId };
|
|
};
|
|
|
|
const runWithRows = async (rows: readonly TableRow[]) => {
|
|
const store = createPassThroughStore({
|
|
bars,
|
|
eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...rows] },
|
|
});
|
|
const ledger = createFakeLedger();
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store,
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
const res = await invoke(server, {
|
|
listingIds,
|
|
from: microFromIso,
|
|
to: dates[22]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 0,
|
|
postDays: 1,
|
|
benchmark: 'none',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
});
|
|
return { res, ledger };
|
|
};
|
|
|
|
const leaky = await runWithRows([leakedRow, ...validRows]);
|
|
const clean = await runWithRows(validRows);
|
|
|
|
expect(leaky.res.isError).toBeUndefined();
|
|
expect(clean.res.isError).toBeUndefined();
|
|
expect(leaky.res.payload?.status).toBe('ok');
|
|
expect(clean.res.payload?.status).toBe('ok');
|
|
if (leaky.res.payload?.status !== 'ok' || clean.res.payload?.status !== 'ok') {
|
|
throw new Error('Expected ok payloads');
|
|
}
|
|
|
|
// Leaked .123Z row must be excluded; admitted .124Z row + 6 later events = 7 anchored & used events.
|
|
expect(leaky.res.payload.eventCount).toBe(7);
|
|
expect(clean.res.payload.eventCount).toBe(7);
|
|
expect(leaky.res.payload.study.diagnostics.eventsUsed).toBe(7);
|
|
expect(clean.res.payload.study.diagnostics.eventsUsed).toBe(7);
|
|
expect(leaky.res.payload.study.offsets).toEqual(clean.res.payload.study.offsets);
|
|
expect(leaky.res.payload.trial.expressionHash).toBe(clean.res.payload.trial.expressionHash);
|
|
expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Quant QA additions (T-133): exact benchmark economics, late-revised bars,
|
|
// subtype-filter accounting, resolver contract edges, and microsecond upper bounds.
|
|
// Fixture "qa-t133-v1": 6 listings, weekday sessions, flat prices except
|
|
// explicit jump days; gross close-to-close returns, raw adjustment, no costs.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const QA_LISTINGS = [701, 702, 703, 704, 705, 706];
|
|
|
|
function qaXnysResolver(dates: readonly string[]) {
|
|
const calls: EventStudyExchangeCalendarQuery[] = [];
|
|
const resolve = (q: EventStudyExchangeCalendarQuery): EventStudyExchangeCalendars => {
|
|
calls.push(q);
|
|
const sessions = dates
|
|
.filter(d => d >= q.fromDate && d <= q.toDate)
|
|
.map(date => ({ date, closeTs: utcMs(date, 21) }));
|
|
const listingCalendarId = new Map<number, string>();
|
|
for (const id of q.listingIds) {
|
|
listingCalendarId.set(id, 'XNYS');
|
|
}
|
|
return { calendars: new Map([['XNYS', sessions]]), listingCalendarId };
|
|
};
|
|
return { calls, resolve };
|
|
}
|
|
|
|
/** Flat 100 prices; `jumps` maps `${listingIndex}:${dayIndex}` -> daily return. */
|
|
function qaBars(dates: readonly string[], days: number, jumps: ReadonlyMap<string, number>) {
|
|
const bars: BarRecord[] = [];
|
|
for (let l = 0; l < QA_LISTINGS.length; l += 1) {
|
|
let price = 100;
|
|
for (let t = 0; t < days; t += 1) {
|
|
price = Number((price * (1 + (jumps.get(`${l}:${t}`) ?? 0))).toFixed(6));
|
|
const ts = utcMs(dates[t]!, 21);
|
|
bars.push({
|
|
listingId: QA_LISTINGS[l]!,
|
|
ts,
|
|
open: price,
|
|
high: price,
|
|
low: price,
|
|
close: price,
|
|
volume: 1_000,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
return bars;
|
|
}
|
|
|
|
function qaEvent(l: number, ts: number, extra?: Partial<TableRow>): TableRow {
|
|
return {
|
|
listing_id: QA_LISTINGS[l]!,
|
|
ts,
|
|
known_at: ts,
|
|
known_at_source: 'exact',
|
|
kind: 'filing',
|
|
subtype: '8-K',
|
|
payload_json: '{}',
|
|
...extra,
|
|
};
|
|
}
|
|
|
|
function qaServer(params: {
|
|
bars: readonly BarRecord[];
|
|
rows: readonly TableRow[];
|
|
vaultCutoffTs: number;
|
|
resolveExchangeCalendars: (
|
|
q: EventStudyExchangeCalendarQuery
|
|
) => EventStudyExchangeCalendars | Promise<EventStudyExchangeCalendars>;
|
|
}) {
|
|
const ledger = createFakeLedger();
|
|
const server = createMcpServer({
|
|
name: 'research-mcp',
|
|
version: '1.0.0',
|
|
tools: [
|
|
createEventStudyTool({
|
|
store: createPassThroughStore({
|
|
bars: params.bars,
|
|
eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...params.rows] },
|
|
}),
|
|
ledger: ledger.executor,
|
|
vaultContext: { vaultCutoffTs: params.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
resolveExchangeCalendars: params.resolveExchangeCalendars,
|
|
}),
|
|
],
|
|
});
|
|
return { server, ledger };
|
|
}
|
|
|
|
describe('MCP event_study QA additions', () => {
|
|
// Day 6: listings 0-2 get +10% with events; day 12: listings 3-5 get +20% with events.
|
|
// Other listings are flat, so the equal-weight benchmark on day 6 is 0.05 and on day 12 is 0.10.
|
|
const dates = makeBusinessDates('2023-03-01', 22);
|
|
const vaultCutoffTs = utcMs(dates[21]!, 0);
|
|
const jumps = new Map<string, number>([
|
|
['0:6', 0.1],
|
|
['1:6', 0.1],
|
|
['2:6', 0.1],
|
|
['3:12', 0.2],
|
|
['4:12', 0.2],
|
|
['5:12', 0.2],
|
|
]);
|
|
const bars = qaBars(dates, 21, jumps);
|
|
const eventRows: TableRow[] = [
|
|
...[0, 1, 2].map(l => qaEvent(l, utcMs(dates[6]!, 14))),
|
|
...[3, 4, 5].map(l => qaEvent(l, utcMs(dates[12]!, 14))),
|
|
];
|
|
const baseArgs = {
|
|
listingIds: QA_LISTINGS,
|
|
from: dates[0]!,
|
|
to: dates[20]!,
|
|
event: { kinds: ['filing'] },
|
|
preDays: 1,
|
|
postDays: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
test('benchmark "none" reports raw event-day returns and "equal_weight" subtracts the cross-sectional mean', async () => {
|
|
const none = qaServer({
|
|
bars,
|
|
rows: eventRows,
|
|
vaultCutoffTs,
|
|
resolveExchangeCalendars: qaXnysResolver(dates).resolve,
|
|
});
|
|
const ew = qaServer({
|
|
bars,
|
|
rows: eventRows,
|
|
vaultCutoffTs,
|
|
resolveExchangeCalendars: qaXnysResolver(dates).resolve,
|
|
});
|
|
|
|
const resNone = await invoke(none.server, { ...baseArgs, benchmark: 'none' });
|
|
const resEw = await invoke(ew.server, { ...baseArgs, benchmark: 'equal_weight' });
|
|
|
|
if (resNone.payload?.status !== 'ok' || resEw.payload?.status !== 'ok') {
|
|
throw new Error(`Expected ok payloads: ${resNone.text} | ${resEw.text}`);
|
|
}
|
|
const at = (p: typeof resNone.payload, offset: number) =>
|
|
p.study.offsets.find(o => o.offset === offset)!;
|
|
|
|
// none: mean(+10% x3, +20% x3) = 0.15; flat neighbours.
|
|
expect(at(resNone.payload, 0).aar).toBeCloseTo(0.15, 10);
|
|
expect(at(resNone.payload, -1).aar).toBeCloseTo(0, 10);
|
|
expect(at(resNone.payload, 1).aar).toBeCloseTo(0, 10);
|
|
// equal_weight: mean(0.10-0.05 x3, 0.20-0.10 x3) = 0.075.
|
|
expect(at(resEw.payload, 0).aar).toBeCloseTo(0.075, 10);
|
|
expect(at(resEw.payload, 0).n).toBe(6);
|
|
expect(resNone.payload.study.hasBenchmark).toBe(false);
|
|
expect(resEw.payload.study.hasBenchmark).toBe(true);
|
|
expect(none.ledger.insertCalls).toBe(1);
|
|
expect(ew.ledger.insertCalls).toBe(1);
|
|
expect(resNone.payload.trial.expressionHash).not.toBe(resEw.payload.trial.expressionHash);
|
|
});
|
|
|
|
test('a late-revised bar (knownAt > asOf) leaked by the store is dropped before the panel', async () => {
|
|
const asOfIso = `${dates[18]!}T21:00:00.000Z`;
|
|
// Same (listing, ts) as an original bar but a different close and knownAt after asOf.
|
|
// If admitted, the panel would throw duplicate_bar or change returns.
|
|
const revised: BarRecord = {
|
|
...bars.find(b => b.listingId === QA_LISTINGS[0] && b.ts === utcMs(dates[6]!, 21))!,
|
|
close: 999,
|
|
open: 999,
|
|
high: 999,
|
|
low: 999,
|
|
knownAt: utcMs(dates[19]!, 12),
|
|
};
|
|
const clean = qaServer({
|
|
bars,
|
|
rows: eventRows,
|
|
vaultCutoffTs,
|
|
resolveExchangeCalendars: qaXnysResolver(dates).resolve,
|
|
});
|
|
const leaky = qaServer({
|
|
bars: [...bars, revised],
|
|
rows: eventRows,
|
|
vaultCutoffTs,
|
|
resolveExchangeCalendars: qaXnysResolver(dates).resolve,
|
|
});
|
|
|
|
const resClean = await invoke(clean.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' });
|
|
const resLeaky = await invoke(leaky.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' });
|
|
|
|
expect(resLeaky.isError).toBeUndefined();
|
|
if (resLeaky.payload?.status !== 'ok' || resClean.payload?.status !== 'ok') {
|
|
throw new Error(`Expected ok payloads: ${resLeaky.text}`);
|
|
}
|
|
expect(resLeaky.payload.study.offsets).toEqual(resClean.payload.study.offsets);
|
|
expect(resLeaky.payload.panelDiagnostics).toEqual(resClean.payload.panelDiagnostics);
|
|
expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series);
|
|
});
|
|
|
|
test('subtype filter drops null and non-matching subtypes (even in the Vault) without counting Vault exclusions', async () => {
|
|
const noise: TableRow[] = [
|
|
qaEvent(0, utcMs(dates[9]!, 14), { subtype: null }),
|
|
qaEvent(1, utcMs(dates[9]!, 14), { subtype: '10-Q' }),
|
|
// Non-matching subtype on the cutoff day: filtered as unrequested, not as a Vault exclusion.
|
|
qaEvent(2, utcMs(dates[21]!, 14), { subtype: '10-K' }),
|
|
// Matching subtype on the cutoff day: a genuine Vault exclusion.
|
|
qaEvent(3, utcMs(dates[21]!, 14)),
|
|
];
|
|
const { server, ledger } = qaServer({
|
|
bars,
|
|
rows: [...eventRows, ...noise],
|
|
vaultCutoffTs,
|
|
resolveExchangeCalendars: qaXnysResolver(dates).resolve,
|
|
});
|
|
|
|
const res = await invoke(server, {
|
|
...baseArgs,
|
|
event: { kinds: ['filing'], subtypes: ['8-K'] },
|
|
benchmark: 'none',
|
|
});
|
|
|
|
if (res.payload?.status !== 'ok') {
|
|
throw new Error(`Expected ok: ${res.text}`);
|
|
}
|
|
expect(res.payload.eventCount).toBe(6);
|
|
expect(res.payload.vaultExcludedEvents).toBe(1);
|
|
expect(res.payload.event.subtypes).toEqual(['8-K']);
|
|
expect(res.payload.study.offsets.find(o => o.offset === 0)!.aar).toBeCloseTo(0.15, 10);
|
|
expect(ledger.insertCalls).toBe(1);
|
|
});
|
|
|
|
test('synchronous calendar resolver is accepted and a non-Error throw maps to the fixed resolver message', async () => {
|
|
const sync = qaServer({
|
|
bars,
|
|
rows: eventRows,
|
|
vaultCutoffTs,
|
|
resolveExchangeCalendars: qaXnysResolver(dates).resolve,
|
|
});
|
|
const syncRes = await invoke(sync.server, { ...baseArgs, benchmark: 'none' });
|
|
expect(syncRes.payload?.status).toBe('ok');
|
|
|
|
const SECRET = 'SECRET_CAL_DSN_55120';
|
|
const failing = qaServer({
|
|
bars,
|
|
rows: eventRows,
|
|
vaultCutoffTs,
|
|
resolveExchangeCalendars: () => {
|
|
throw `postgres://calendar:${SECRET}@db/cal`;
|
|
},
|
|
});
|
|
const failRes = await invoke(failing.server, { ...baseArgs, benchmark: 'none' });
|
|
expect(failRes.isError).toBe(true);
|
|
expect(failRes.text).toBe('Error: Exchange calendar resolution failed.');
|
|
expect(failRes.text).not.toContain(SECRET);
|
|
expect(failing.ledger.insertCalls).toBe(0);
|
|
|
|
const rejecting = qaServer({
|
|
bars,
|
|
rows: eventRows,
|
|
vaultCutoffTs,
|
|
resolveExchangeCalendars: () => Promise.reject(new TypeError(`/srv/cal/${SECRET}.parquet`)),
|
|
});
|
|
const rejectRes = await invoke(rejecting.server, { ...baseArgs, benchmark: 'none' });
|
|
expect(rejectRes.isError).toBe(true);
|
|
expect(rejectRes.text).toBe('Error: Exchange calendar resolution failed.');
|
|
expect(rejectRes.text).not.toContain(SECRET);
|
|
});
|
|
|
|
test('microsecond-precision to/asOf keep rows at the boundary millisecond and drop the next millisecond', async () => {
|
|
// to/asOf at dates[14] 15:00:00.123456Z. Base events (days 6, 12) are inside the window.
|
|
const boundaryIso = `${dates[14]!}T15:00:00.123456Z`;
|
|
const boundaryMs = Date.parse(`${dates[14]!}T15:00:00.123Z`);
|
|
const extra: TableRow[] = [
|
|
qaEvent(0, boundaryMs), // ts == toMs, known_at == asOfMs (.123 <= .123456) -> kept
|
|
qaEvent(1, boundaryMs + 1), // .124 > .123456 -> dropped
|
|
qaEvent(2, utcMs(dates[10]!, 14), { known_at: boundaryMs + 1 }), // known after asOf -> dropped
|
|
];
|
|
const { server } = qaServer({
|
|
bars,
|
|
rows: [...eventRows, ...extra],
|
|
vaultCutoffTs,
|
|
resolveExchangeCalendars: qaXnysResolver(dates).resolve,
|
|
});
|
|
|
|
const res = await invoke(server, {
|
|
...baseArgs,
|
|
to: boundaryIso,
|
|
asOf: boundaryIso,
|
|
benchmark: 'none',
|
|
});
|
|
|
|
expect(res.isError).toBeUndefined();
|
|
expect(res.payload?.effectiveTo).toBe(boundaryIso);
|
|
expect(res.payload?.effectiveAsOf).toBe(boundaryIso);
|
|
// The boundary-ms event passes the defensive filter and reaches the panel, which drops it
|
|
// as after-last-session (its dates[14] close is after asOf). The .124 rows never reach the
|
|
// panel: if they did, droppedAfterLastSession would be > 1 or eventCount would change.
|
|
expect(res.payload?.panelDiagnostics.droppedAfterLastSession).toBe(1);
|
|
expect(res.payload?.eventCount).toBe(6);
|
|
expect(res.payload?.study.diagnostics.eventsUsed).toBe(6);
|
|
expect(res.payload?.vaultExcludedEvents).toBe(0);
|
|
});
|
|
});
|