diff --git a/libs/research/README.md b/libs/research/README.md index fd8e76ad..ffb83567 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -212,8 +212,14 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`createQueryDataTool({ store, vaultContext })`** — Wraps an injected `MarketDataStore` for explicit `listingIds` (max `QUERY_DATA_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref, with bounded output rows (`QUERY_DATA_DEFAULT_LIMIT = 500`, hard max `QUERY_DATA_MAX_LIMIT = 5_000`). - Always enforces `scope: 'vault_fenced'` via `applyVaultFence` before any store call, omits `scope` / `vault_evaluation_only` from the strict schema (rejecting unknown keys with zero store calls), drops any post-cutoff row (`ts >= vaultCutoffTs` or `knownAt >= vaultCutoffTs`) as defense in depth, and maps `VaultHoldoutFenceError`, `VaultScopeNotAuthorizedError`, `MarketDataStoreValidationError`, `MarketDataStoreNotImplementedError`, and `AdjFactorsSnapshotError` to `isError: true` responses naming the error class. +### `event_study` Tool (Vault-Fenced) + +- **`createEventStudyTool({ store, ledger, vaultContext, principalId, resolveExchangeCalendars })`** — Runs a Vault-fenced event study over daily bars and point-in-time `events` (`filing`, `earnings`, `ceo_post`, `corporate_action`, with optional exact `subtypes` filter) for explicit `listingIds` (max `EVENT_STUDY_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref matching `universeMarket`, across `[-preDays, +postDays]` (`0–60` sessions each; `horizonBucket` must match `postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'`). +- **Injected exchange calendars:** `resolveExchangeCalendars({ listingIds, fromDate, toDate })` supplies actual exchange session close timestamps (including half-days) for `buildEventStudyInput` so events are anchored without synthesizing calendars from bars. +- **Returns, benchmark & Vault fence:** Models daily close-to-close returns with no execution or transaction costs (`adjustment` defaults to `'raw'`; `benchmark` defaults to `'equal_weight'` using available eligible listing returns, or `'none'` for unbenchmarked returns). Enforces `scope: 'vault_fenced'`, clamps `to`/`asOf` strictly below `vaultCutoffTs`, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or with `known_at > asOf`), and writes eligible trials exclusively to the injected `trial_ledger` (`stage = 'event_study'`) under the server-injected `principalId`. + ### Remaining M2 MCP Items (Later Tasks) -- Additional research tools: `search_symbols`, `analyze_signal`, `event_study`, `file_finding`, and `read_knowledge`. +- Additional research tools: `search_symbols`, `analyze_signal`, `file_finding`, and `read_knowledge`. - SSE/HTTP transport wrapper in `apps/stock/web-api`. - Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters. diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 1838886b..6a966bc9 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -2,4 +2,5 @@ export * from './protocol'; export * from './server'; export * from './stdio'; export * from './tools/analyze-signal'; +export * from './tools/event-study'; export * from './tools/query-data'; diff --git a/libs/research/src/mcp/tools/event-study.ts b/libs/research/src/mcp/tools/event-study.ts new file mode 100644 index 00000000..23faad0e --- /dev/null +++ b/libs/research/src/mcp/tools/event-study.ts @@ -0,0 +1,999 @@ +import type { + EventStudyDiagnostics, + EventStudyRecencyResult, + EventStudyResult, + NeweyWestResult, +} from '@stock-bot/calculations'; +import { z } from 'zod'; +import { + type EventPanelDiagnostics, + EventPanelError, + type EventPanelErrorCode, + type EventStudyBenchmarkMode, + type EventStudyExchangeCalendars, + buildEventStudyInput, + eventsTableToEventRows, +} from '../../event-panel'; +import { + type BarRecord, + type EventKind, + type MarketDataStore, + MarketDataStoreValidationError, + type Table, + type TableRow, + type VaultFenceContext, +} from '../../market-data-store'; +import { EVENT_KINDS } from '../../market-data-store-duckdb'; +import { collectBars } from '../../signal-panel'; +import { + type RunEventStudyInsufficientDataReason, + SignalStudyError, + type SignalStudyErrorCode, + type SignalStudyExpression, + type StudyTrialSummary, + runEventStudy, +} from '../../signal-study'; +import { + type ClusterDeflatedSharpeResult, + HORIZON_BUCKETS, + type HorizonBucket, + TrialLedgerError, + type TrialLedgerErrorCode, + type TrialLedgerExecutor, + UNIVERSE_MARKETS, + type UniverseMarket, +} from '../../trial-ledger'; +import type { McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool } from '../server'; +import { + EXCLUSIVE_LISTING_SELECTOR_MESSAGE, + MAX_ECMASCRIPT_EPOCH_MS, + MCP_MAX_LISTING_IDS, + MS_PER_DAY, + createListingIdsFieldSchema, + createUniverseFieldSchema, + fenceVaultQueryBounds, + formatMappedStoreError, + hasExclusiveListingSelector, + isValidUtcBoundString, + resolvePreStartUniverseDate, + utcDateOf, + validateVaultCutoffTs, +} from './vault-fenced-input'; + +/** Hard maximum number of explicit `listingIds` accepted by `event_study`. */ +export const EVENT_STUDY_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS; + +/** Hard maximum pre-event window length in trading sessions. */ +export const EVENT_STUDY_MAX_PRE_DAYS = 60; + +/** Hard maximum post-event window length in trading sessions. */ +export const EVENT_STUDY_MAX_POST_DAYS = 60; + +const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const AGENT_PRINCIPAL_RE = + /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +const UTC_BOUND_ERROR_MESSAGE = + 'Expected YYYY-MM-DD calendar date or UTC ISO-8601 timestamp with timezone offset.'; +const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); + +function canonicalDailyHorizonBucket(postDays: number): HorizonBucket { + return postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'; +} + +function isValidEpochMs(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isFinite(value) && + Number.isSafeInteger(value) && + Math.abs(value) < MAX_ECMASCRIPT_EPOCH_MS + ); +} + +const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE); + +const eventFilterSpecSchema = z + .object({ + kinds: z + .array(z.enum(EVENT_KINDS)) + .min(1) + .describe( + 'Non-empty list of event kinds to include (filing, earnings, ceo_post, or corporate_action).' + ), + subtypes: z + .array(z.string().min(1)) + .min(1) + .optional() + .describe('Optional non-empty exact-match allow-list of event subtypes.'), + }) + .strict() + .describe('Event kind and optional subtype filter specification.'); + +/** + * Strict Zod input schema for the `event_study` MCP tool. + * + * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and + * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them + * or any other unknown top-level or nested key. + */ +export const eventStudyInputSchema = z + .object({ + listingIds: createListingIdsFieldSchema( + 'Explicit INT32 listing IDs to study (mutually exclusive with universe).' + ), + universe: createUniverseFieldSchema( + 'Survivorship-free universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).' + ), + from: utcBoundStringSchema.describe( + 'Inclusive study start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.' + ), + to: utcBoundStringSchema.describe( + 'Inclusive study end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.' + ), + asOf: utcBoundStringSchema + .optional() + .describe( + 'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.' + ), + event: eventFilterSpecSchema, + preDays: z + .number() + .int() + .min(0) + .max(EVENT_STUDY_MAX_PRE_DAYS) + .describe( + `Pre-event window in trading sessions (0–${EVENT_STUDY_MAX_PRE_DAYS}).` + ), + postDays: z + .number() + .int() + .min(0) + .max(EVENT_STUDY_MAX_POST_DAYS) + .describe( + `Post-event window in trading sessions (0–${EVENT_STUDY_MAX_POST_DAYS}).` + ), + benchmark: z + .enum(['equal_weight', 'none']) + .default('equal_weight') + .describe( + 'Benchmark return mode: equal_weight (cross-sectional mean of eligible listing returns) or none (default equal_weight).' + ), + adjustment: z + .enum(['raw', 'split', 'total']) + .default('raw') + .describe('Bar price adjustment mode (default raw).'), + universeMarket: z + .enum(UNIVERSE_MARKETS) + .describe('Relatedness-cluster market bucket recorded in trial_ledger.'), + horizonBucket: z + .enum(HORIZON_BUCKETS) + .describe('Relatedness-cluster horizon bucket recorded in trial_ledger.'), + campaignId: z + .string() + .regex(LEDGER_UUID_RE, 'Expected a UUID string.') + .optional() + .describe('Optional research campaign UUID recorded in trial_ledger.'), + hypothesisId: z + .string() + .regex(LEDGER_UUID_RE, 'Expected a UUID string.') + .optional() + .describe('Optional research hypothesis UUID recorded in trial_ledger.'), + }) + .strict() + .superRefine((data, ctx) => { + if (!hasExclusiveListingSelector(data)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: EXCLUSIVE_LISTING_SELECTOR_MESSAGE, + }); + } + + const expectedBucket = canonicalDailyHorizonBucket(data.postDays); + if (data.horizonBucket !== expectedBucket) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['horizonBucket'], + message: `Daily postDays=${data.postDays} requires horizonBucket "${expectedBucket}".`, + }); + } + + if (data.universe !== undefined && data.universeMarket !== data.universe) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['universeMarket'], + message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`, + }); + } + }); + +export type EventStudyToolInput = z.infer; + +/** Query passed to the server-injected exchange-calendar resolver. */ +export interface EventStudyExchangeCalendarQuery { + readonly listingIds: readonly number[]; + readonly fromDate: string; + readonly toDate: string; +} + +/** Server-injected exchange-calendar resolver returning actual session close calendars. */ +export type EventStudyExchangeCalendarResolver = ( + query: EventStudyExchangeCalendarQuery +) => Promise | EventStudyExchangeCalendars; + +/** Server-side injected configuration for {@link createEventStudyTool}. */ +export interface EventStudyToolOptions { + readonly store: MarketDataStore; + readonly ledger: TrialLedgerExecutor; + readonly vaultContext: Pick; + readonly principalId: string; + readonly resolveExchangeCalendars: EventStudyExchangeCalendarResolver; +} + +/** Projected CAR/AAR summary for one relative offset in `[-preDays, +postDays]`. */ +export interface EventStudyOffsetSummary { + readonly offset: number; + readonly n: number; + readonly aar: number; + readonly caar: number; + readonly caarFromZero: number | null; +} + +/** Bounded date-clustered CAR summary without raw per-date typed arrays. */ +export interface EventStudyClusteredSummary { + readonly nDates: number; + readonly carMean: number; + readonly neweyWest: NeweyWestResult; +} + +/** Bounded summary projection of {@link EventStudyResult}. */ +export interface EventStudySummary { + readonly preDays: number; + readonly postDays: number; + readonly hasBenchmark: boolean; + readonly offsets: readonly EventStudyOffsetSummary[]; + readonly clustered: EventStudyClusteredSummary | null; + readonly recency: EventStudyRecencyResult | null; + readonly diagnostics: EventStudyDiagnostics; +} + +interface EventStudyResultBase { + readonly scope: 'vault_fenced'; + readonly vaultCutoffTs: number; + readonly vaultCutoffDate: string; + readonly event: { + readonly kinds: readonly EventKind[]; + readonly subtypes: readonly string[] | null; + }; + readonly preDays: number; + readonly postDays: number; + readonly benchmark: EventStudyBenchmarkMode; + readonly adjustment: 'raw' | 'split' | 'total'; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly fromMs: number; + readonly toMs: number; + readonly asOfMs: number; + readonly effectiveFrom: string; + readonly effectiveTo: string; + readonly effectiveAsOf: string; + readonly clampedTo: boolean; + readonly clampedAsOf: boolean; + readonly listingCount: number; + readonly eventCount: number; + readonly vaultExcludedEvents: number; + readonly panelDiagnostics: EventPanelDiagnostics; + readonly study: EventStudySummary; +} + +/** Structured JSON payload serialized into the `event_study` MCP text result. */ +export type EventStudyResultPayload = + | (EventStudyResultBase & { + readonly status: 'ok'; + readonly trial: StudyTrialSummary; + readonly deflatedSharpe: ClusterDeflatedSharpeResult; + }) + | (EventStudyResultBase & { + readonly status: 'insufficient_data'; + readonly reason: RunEventStudyInsufficientDataReason; + }); + +class ExchangeCalendarResolverError extends Error { + override readonly name = 'ExchangeCalendarResolverError'; + override readonly cause?: unknown; + + constructor(cause: unknown) { + super('Exchange calendar resolution failed.', { cause }); + this.cause = cause; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +const ZERO_EVENT_PANEL_DIAGNOSTICS: EventPanelDiagnostics = { + vaultExcludedDates: 0, + vaultExcludedEvents: 0, + droppedUnknownListing: 0, + droppedAfterLastSession: 0, + droppedMissingCalendarSession: 0, + duplicateEvents: 0, + duplicateBars: 0, + nonPositiveCloseReturns: 0, +}; + +const ZERO_EVENT_STUDY_DIAGNOSTICS: EventStudyDiagnostics = { + eventsIn: 0, + eventsUsed: 0, + droppedUnknownEntity: 0, + droppedWindowOutOfRange: 0, + droppedMissingReturns: 0, + duplicateEventsCollapsed: 0, +}; + +const EVENT_PANEL_ERROR_MESSAGES: Readonly> = { + invalid_input: 'Invalid event panel input.', + invalid_date: 'Invalid event panel date.', + invalid_bar: 'Market bar data failed event panel validation.', + invalid_event: 'Event table data failed event panel validation.', + invalid_option: 'Invalid event panel option.', + duplicate_bar: 'Conflicting duplicate daily bars detected.', +}; + +const SIGNAL_STUDY_ERROR_MESSAGES: Readonly> = { + invalid_request: 'Invalid event study request.', + empty_panel: 'Event study session grid is empty.', + invalid_date: 'Invalid event study date.', + unsorted_dates: 'Event study session dates are not strictly ascending.', + duplicate_date: 'Duplicate date detected in event study session grid.', + invalid_panel: 'Event study panel failed validation.', + invalid_option: 'Invalid event study option.', + dsr_read_failed: 'Trial was recorded, but cluster deflated Sharpe evaluation failed.', +}; + +const TRIAL_LEDGER_ERROR_MESSAGES: Readonly>> = { + VAULT_FENCE_VIOLATION: 'Sample window violates the Vault holdout cutoff.', + INVALID_PRINCIPAL: 'Invalid trial ledger principal.', + INVALID_UUID: 'Invalid trial ledger UUID.', + INVALID_SAMPLE_WINDOW: 'Invalid trial ledger sample window.', + INVALID_DATE: 'Invalid trial ledger date.', + SERIES_TOO_SHORT: 'Observation series is too short for trial ledger recording.', + ZERO_VARIANCE_SERIES: 'Observation series has zero variance.', + TRIAL_NOT_FOUND: 'Recorded trial could not be found in trial ledger.', +}; + +function sortAndDedupeListingIds(ids: readonly number[]): number[] { + return [...new Set(ids)].sort((a, b) => a - b); +} + +function sortAndDedupeStrings(items: readonly T[]): T[] { + return [...new Set(items)].sort() as T[]; +} + +function makeEmptyStudySummary( + preDays: number, + postDays: number, + hasBenchmark: boolean +): EventStudySummary { + return { + preDays, + postDays, + hasBenchmark, + offsets: [], + clustered: null, + recency: null, + diagnostics: ZERO_EVENT_STUDY_DIAGNOSTICS, + }; +} + +function projectStudySummary(study: EventStudyResult): EventStudySummary { + if (study.status === 'insufficient_data') { + return { + preDays: study.preDays, + postDays: study.postDays, + hasBenchmark: study.hasBenchmark, + offsets: [], + clustered: null, + recency: null, + diagnostics: study.diagnostics, + }; + } + + return { + preDays: study.preDays, + postDays: study.postDays, + hasBenchmark: study.hasBenchmark, + offsets: study.offsets.map(o => ({ + offset: o.offset, + n: o.n, + aar: o.aar, + caar: o.caar, + caarFromZero: o.caarFromZero, + })), + clustered: { + nDates: study.clustered.nDates, + carMean: study.clustered.carMean, + neweyWest: study.clustered.neweyWest, + }, + recency: study.recency, + diagnostics: study.diagnostics, + }; +} + +function filterEligibleBars( + bars: readonly BarRecord[], + listingIdSet: ReadonlySet, + fromMs: number, + toMs: number, + asOfMs: number, + vaultCutoffTs: number, + vaultCutoffDate: string +): BarRecord[] { + const eligible: BarRecord[] = []; + for (let i = 0; i < bars.length; i += 1) { + const row = bars[i]; + if (typeof row !== 'object' || row === null) { + eligible.push(row as unknown as BarRecord); + continue; + } + if (isValidEpochMs(row.ts)) { + if ( + row.ts < fromMs || + row.ts > toMs || + row.ts > asOfMs || + row.ts >= vaultCutoffTs || + utcDateOf(row.ts) >= vaultCutoffDate + ) { + continue; + } + } + if (isValidEpochMs(row.knownAt)) { + if ( + row.knownAt > asOfMs || + row.knownAt >= vaultCutoffTs || + utcDateOf(row.knownAt) >= vaultCutoffDate + ) { + continue; + } + } + if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) { + continue; + } + eligible.push(row); + } + return eligible; +} + +function filterEligibleEventsTable(params: { + readonly table: Table; + readonly listingIdSet: ReadonlySet; + readonly kindSet: ReadonlySet; + readonly subtypeSet: ReadonlySet | null; + readonly fromMs: number; + readonly toMs: number; + readonly asOfMs: number; + readonly vaultCutoffTs: number; + readonly vaultCutoffDate: string; +}): { readonly table: Table; readonly prePanelVaultExcludedEvents: number } { + const { + table, + listingIdSet, + kindSet, + subtypeSet, + fromMs, + toMs, + asOfMs, + vaultCutoffTs, + vaultCutoffDate, + } = params; + + if ( + typeof table !== 'object' || + table === null || + !Array.isArray(table.columns) || + !Array.isArray(table.rows) + ) { + return { table, prePanelVaultExcludedEvents: 0 }; + } + + const eligibleRows: TableRow[] = []; + let prePanelVaultExcludedEvents = 0; + + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i]; + if (typeof row !== 'object' || row === null || Array.isArray(row)) { + eligibleRows.push(row as TableRow); + continue; + } + + const listingId = row.listing_id; + if (typeof listingId === 'number' && !listingIdSet.has(listingId)) { + continue; + } + + // Drop valid but unrequested kinds/subtypes without counting them as Vault exclusions. + // Malformed kind/subtype values fall through so eventsTableToEventRows rejects them. + const kind = row.kind; + if (typeof kind === 'string' && EVENT_KIND_SET.has(kind) && !kindSet.has(kind)) { + continue; + } + if (subtypeSet !== null) { + const subtype = row.subtype; + if (subtype === null || (typeof subtype === 'string' && !subtypeSet.has(subtype))) { + continue; + } + } + + const knownAt = row.known_at; + const knownAtInVault = + isValidEpochMs(knownAt) && + (knownAt >= vaultCutoffTs || utcDateOf(knownAt) >= vaultCutoffDate); + + const ts = row.ts; + const tsInVault = + isValidEpochMs(ts) && + (ts >= vaultCutoffTs || utcDateOf(ts) >= vaultCutoffDate); + + if (knownAtInVault || tsInVault) { + prePanelVaultExcludedEvents += 1; + continue; + } + + if (isValidEpochMs(knownAt) && knownAt > asOfMs) { + continue; + } + + if (isValidEpochMs(ts)) { + if (ts < fromMs || ts > toMs) { + continue; + } + } else { + throw new EventPanelError( + 'invalid_event', + `Invalid ts in events table row[${i}]: ${String(ts)}.` + ); + } + + eligibleRows.push(row); + } + + return { + table: { + columns: table.columns, + rows: eligibleRows, + }, + prePanelVaultExcludedEvents, + }; +} + +function buildCanonicalEventStudyExpression(params: { + readonly input: EventStudyToolInput; + readonly canonicalKinds: readonly EventKind[]; + readonly canonicalSubtypes: readonly string[] | undefined; + readonly listingIds: readonly number[]; + readonly universeSnapshotDate: string | null; + readonly effectiveFrom: string; + readonly effectiveTo: string; + readonly effectiveAsOf: string; +}): SignalStudyExpression { + const { + input, + canonicalKinds, + canonicalSubtypes, + listingIds, + universeSnapshotDate, + effectiveFrom, + effectiveTo, + effectiveAsOf, + } = params; + + return { + expression: `mcp:event_study:v1:${canonicalKinds.join(',')}`, + params: { + version: 1, + kinds: canonicalKinds, + subtypes: canonicalSubtypes ?? null, + preDays: input.preDays, + postDays: input.postDays, + benchmark: input.benchmark, + adjustment: input.adjustment, + effectiveFrom, + effectiveTo, + effectiveAsOf, + }, + universe: + input.universe !== undefined + ? { + kind: 'universe', + ref: input.universe, + snapshotDate: universeSnapshotDate, + listingIds, + } + : { + kind: 'listingIds', + listingIds, + }, + horizon: `${input.postDays}d`, + }; +} + +function formatMappedEventStudyError(err: unknown): McpToolCallResult { + const storeMapped = formatMappedStoreError(err); + if (storeMapped !== null) { + return storeMapped; + } + + if (err instanceof ExchangeCalendarResolverError) { + return { + content: [{ type: 'text', text: 'Error: Exchange calendar resolution failed.' }], + isError: true, + }; + } + + if (err instanceof EventPanelError) { + const detail = Object.prototype.hasOwnProperty.call(EVENT_PANEL_ERROR_MESSAGES, err.code) + ? EVENT_PANEL_ERROR_MESSAGES[err.code] + : 'Event panel construction failed.'; + return { + content: [{ type: 'text', text: `EventPanelError: ${detail}` }], + isError: true, + }; + } + + if (err instanceof SignalStudyError) { + const detail = Object.prototype.hasOwnProperty.call(SIGNAL_STUDY_ERROR_MESSAGES, err.code) + ? SIGNAL_STUDY_ERROR_MESSAGES[err.code] + : 'Event study execution failed.'; + return { + content: [{ type: 'text', text: `SignalStudyError: ${detail}` }], + isError: true, + }; + } + + if (err instanceof TrialLedgerError) { + const detail = + Object.prototype.hasOwnProperty.call(TRIAL_LEDGER_ERROR_MESSAGES, err.code) && + TRIAL_LEDGER_ERROR_MESSAGES[err.code] !== undefined + ? TRIAL_LEDGER_ERROR_MESSAGES[err.code] + : 'Trial ledger operation failed.'; + return { + content: [{ type: 'text', text: `TrialLedgerError: ${detail}` }], + isError: true, + }; + } + + return { + content: [{ type: 'text', text: 'Error: Tool execution failed.' }], + isError: true, + }; +} + +function validateFactoryOptions(options: EventStudyToolOptions): number { + if (typeof options !== 'object' || options === null) { + throw new MarketDataStoreValidationError( + 'Invalid `options`: expected an EventStudyToolOptions object.', + 'options' + ); + } + + if ( + typeof options.store !== 'object' || + options.store === null || + typeof options.store.bars !== 'function' || + typeof options.store.events !== 'function' || + typeof options.store.universe !== 'function' + ) { + throw new MarketDataStoreValidationError( + 'Invalid `store`: expected a MarketDataStore implementing `bars`, `events`, and `universe`.', + 'store' + ); + } + + if ( + typeof options.ledger !== 'object' || + options.ledger === null || + typeof options.ledger.query !== 'function' + ) { + throw new SignalStudyError( + 'invalid_request', + 'Invalid `ledger`: expected a TrialLedgerExecutor implementing `query`.' + ); + } + + if (typeof options.resolveExchangeCalendars !== 'function') { + throw new EventPanelError( + 'invalid_option', + 'Invalid `resolveExchangeCalendars`: expected a function.' + ); + } + + if ( + typeof options.principalId !== 'string' || + (options.principalId !== 'operator' && !AGENT_PRINCIPAL_RE.test(options.principalId)) + ) { + throw new TrialLedgerError( + 'INVALID_PRINCIPAL', + `Invalid \`principalId\`: "${String(options.principalId)}".` + ); + } + + return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); +} + +/** + * Creates the Vault-fenced `event_study` MCP tool backed by an injected + * {@link MarketDataStore}, {@link TrialLedgerExecutor}, and exchange-calendar + * resolver. + * + * Enforces `scope: 'vault_fenced'`, fences bounds before any dependency call, + * resolves named universes strictly prior to the study start date, filters + * bars and events defensively against the effective window and Vault cutoff, + * anchors events using actual exchange close calendars, runs `runEventStudy` + * under the injected research principal, and returns a bounded summary payload. + */ +export function createEventStudyTool(options: EventStudyToolOptions): McpToolEntry { + const vaultCutoffTs = validateFactoryOptions(options); + const { store, ledger, principalId, resolveExchangeCalendars } = options; + + return defineMcpTool({ + name: 'event_study', + description: + 'Run a Vault-fenced event study over daily bars and point-in-time events and record eligible trials to trial_ledger.', + inputSchema: eventStudyInputSchema, + async handler(input: EventStudyToolInput): Promise { + try { + const fenced = fenceVaultQueryBounds( + { + from: input.from, + to: input.to, + asOf: input.asOf, + }, + vaultCutoffTs + ); + + const canonicalKinds = sortAndDedupeStrings(input.event.kinds); + const canonicalSubtypes = + input.event.subtypes !== undefined + ? sortAndDedupeStrings(input.event.subtypes) + : undefined; + + let listingIds: number[]; + let universeSnapshotDate: string | null = null; + + if (input.universe !== undefined) { + universeSnapshotDate = resolvePreStartUniverseDate( + fenced.fromMs, + fenced.asOfMs, + fenced.asOfSubMs + ); + const resolved = await store.universe({ + ref: input.universe, + date: universeSnapshotDate, + }); + listingIds = sortAndDedupeListingIds(resolved); + } else { + listingIds = sortAndDedupeListingIds(input.listingIds ?? []); + } + + const hasBenchmark = input.benchmark === 'equal_weight'; + const basePayloadFields = { + scope: 'vault_fenced' as const, + vaultCutoffTs, + vaultCutoffDate: fenced.vaultCutoffDate, + event: { + kinds: canonicalKinds, + subtypes: canonicalSubtypes ?? null, + }, + preDays: input.preDays, + postDays: input.postDays, + benchmark: input.benchmark, + adjustment: input.adjustment, + universeMarket: input.universeMarket, + horizonBucket: input.horizonBucket, + fromMs: fenced.fromMs, + toMs: fenced.toMs, + asOfMs: fenced.asOfMs, + effectiveFrom: fenced.canonicalFrom, + effectiveTo: fenced.canonicalTo, + effectiveAsOf: fenced.canonicalAsOf, + clampedTo: fenced.clampedTo, + clampedAsOf: fenced.clampedAsOf, + listingCount: listingIds.length, + }; + + if (listingIds.length === 0) { + const payload: EventStudyResultPayload = { + ...basePayloadFields, + status: 'insufficient_data', + reason: 'below_min_events', + eventCount: 0, + vaultExcludedEvents: 0, + panelDiagnostics: ZERO_EVENT_PANEL_DIAGNOSTICS, + study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), + }; + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } + + const rawBars = await collectBars( + store.bars({ + listingIds, + timeframe: '1d', + from: fenced.canonicalFrom, + to: fenced.canonicalTo, + adjustment: input.adjustment, + asOf: fenced.canonicalAsOf, + scope: 'vault_fenced', + }) + ); + + const rawEventsTable = await store.events({ + kinds: canonicalKinds, + listingIds, + from: fenced.canonicalFrom, + to: fenced.canonicalTo, + asOf: fenced.canonicalAsOf, + }); + + const listingIdSet = new Set(listingIds); + const kindSet = new Set(canonicalKinds); + const subtypeSet = canonicalSubtypes !== undefined ? new Set(canonicalSubtypes) : null; + + const eligibleBars = filterEligibleBars( + rawBars, + listingIdSet, + fenced.fromMs, + fenced.toMs, + fenced.asOfMs, + vaultCutoffTs, + fenced.vaultCutoffDate + ); + + const { table: eligibleEventsTable, prePanelVaultExcludedEvents } = + filterEligibleEventsTable({ + table: rawEventsTable, + listingIdSet, + kindSet, + subtypeSet, + fromMs: fenced.fromMs, + toMs: fenced.toMs, + asOfMs: fenced.asOfMs, + vaultCutoffTs, + vaultCutoffDate: fenced.vaultCutoffDate, + }); + + const events = eventsTableToEventRows(eligibleEventsTable, { + kinds: canonicalKinds, + ...(canonicalSubtypes !== undefined ? { subtypes: canonicalSubtypes } : {}), + }); + + const fromDate = utcDateOf(fenced.fromMs); + const toDate = utcDateOf(fenced.toMs); + const asOfDate = utcDateOf(fenced.asOfMs); + const vaultCutoffDayStartMs = Math.floor(vaultCutoffTs / MS_PER_DAY) * MS_PER_DAY; + const lastPreVaultDate = utcDateOf(vaultCutoffDayStartMs - MS_PER_DAY); + const calendarToDate = [toDate, asOfDate, lastPreVaultDate].reduce((a, b) => + a < b ? a : b + ); + + if (fromDate > calendarToDate) { + const panelDiagnostics: EventPanelDiagnostics = { + ...ZERO_EVENT_PANEL_DIAGNOSTICS, + vaultExcludedEvents: prePanelVaultExcludedEvents, + droppedUnknownListing: events.length, + }; + const payload: EventStudyResultPayload = { + ...basePayloadFields, + status: 'insufficient_data', + reason: 'below_min_events', + eventCount: 0, + vaultExcludedEvents: prePanelVaultExcludedEvents, + panelDiagnostics, + study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), + }; + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } + + let exchangeCalendars: EventStudyExchangeCalendars; + try { + exchangeCalendars = await resolveExchangeCalendars({ + listingIds, + fromDate, + toDate: calendarToDate, + }); + } catch (err: unknown) { + if (err instanceof EventPanelError) { + throw err; + } + throw new ExchangeCalendarResolverError(err); + } + + const built = buildEventStudyInput({ + bars: eligibleBars, + events, + vaultCutoffDate: fenced.vaultCutoffDate, + benchmark: input.benchmark, + exchangeCalendars, + }); + + const combinedPanelDiagnostics: EventPanelDiagnostics = { + ...built.diagnostics, + vaultExcludedEvents: prePanelVaultExcludedEvents + built.diagnostics.vaultExcludedEvents, + }; + + if (built.input.sessionDates.length === 0) { + const payload: EventStudyResultPayload = { + ...basePayloadFields, + status: 'insufficient_data', + reason: 'below_min_events', + eventCount: 0, + vaultExcludedEvents: combinedPanelDiagnostics.vaultExcludedEvents, + panelDiagnostics: combinedPanelDiagnostics, + study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), + }; + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } + + const expression = buildCanonicalEventStudyExpression({ + input, + canonicalKinds, + canonicalSubtypes, + listingIds, + universeSnapshotDate, + effectiveFrom: fenced.canonicalFrom, + effectiveTo: fenced.canonicalTo, + effectiveAsOf: fenced.canonicalAsOf, + }); + + const studyResult = await runEventStudy(ledger, { + principalId, + ...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}), + ...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}), + universeMarket: input.universeMarket, + horizonBucket: input.horizonBucket, + expression, + input: built.input, + vaultCutoffDate: fenced.vaultCutoffDate, + options: { + preDays: input.preDays, + postDays: input.postDays, + }, + }); + + const totalVaultExcludedEvents = + combinedPanelDiagnostics.vaultExcludedEvents + studyResult.vaultExcludedEvents; + const studySummary = projectStudySummary(studyResult.study); + + const payload: EventStudyResultPayload = + studyResult.status === 'ok' + ? { + ...basePayloadFields, + status: 'ok', + eventCount: built.input.events.length, + vaultExcludedEvents: totalVaultExcludedEvents, + panelDiagnostics: combinedPanelDiagnostics, + study: studySummary, + trial: studyResult.trial, + deflatedSharpe: studyResult.deflatedSharpe, + } + : { + ...basePayloadFields, + status: 'insufficient_data', + reason: studyResult.reason, + eventCount: built.input.events.length, + vaultExcludedEvents: totalVaultExcludedEvents, + panelDiagnostics: combinedPanelDiagnostics, + study: studySummary, + }; + + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } catch (err: unknown) { + return formatMappedEventStudyError(err); + } + }, + }); +} diff --git a/libs/research/test/mcp-event-study-qa.test.ts b/libs/research/test/mcp-event-study-qa.test.ts new file mode 100644 index 00000000..7ebe7ab6 --- /dev/null +++ b/libs/research/test/mcp-event-study-qa.test.ts @@ -0,0 +1,658 @@ +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>(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 { + return { + async *[Symbol.asyncIterator]() { + yield { rows: [...params.bars] }; + }, + }; + }, + async events(_q: EventsQuery): Promise { + return params.eventsTable; + }, + async universe(_q: UniverseQuery): Promise { + 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, + args: Record +): 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([ + [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 => { + 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(); + 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 => { + 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(); + 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?.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 => { + const sessions = dates + .filter(d => d >= q.fromDate && d <= q.toDate) + .map(date => ({ date, closeTs: utcMs(date, 21) })); + const listingCalendarId = new Map(); + 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); + }); +}); diff --git a/libs/research/test/mcp-event-study.test.ts b/libs/research/test/mcp-event-study.test.ts new file mode 100644 index 00000000..5782c0ff --- /dev/null +++ b/libs/research/test/mcp-event-study.test.ts @@ -0,0 +1,1419 @@ +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, + 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>(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(); + 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 { + 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
{ + eventsCalls.push(q); + if (options?.eventsError !== undefined) { + throw options.eventsError; + } + const kinds = new Set(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 { + 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; +} { + const calls: EventStudyExchangeCalendarQuery[] = []; + const hourUtc = options?.hourUtc ?? 21; + + return { + calls, + async resolveExchangeCalendars( + q: EventStudyExchangeCalendarQuery + ): Promise { + 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(); + for (const id of q.listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { + calendars: new Map([['XNYS', sessions]]), + listingCalendarId, + }; + }, + }; +} + +async function callEventStudy( + server: ReturnType, + args: Record, + id = 1 +): Promise<{ + rpc: Record; + 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; + 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); + + 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>; + }; + }>; + }; + }; + + 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 }; + expect(eventSchema.additionalProperties).toBe(false); + }); + + 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) => { + 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; + }; + + 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; + 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.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; + 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[] = [ + { ...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, 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[1]; + calError?: unknown; + ledgerOpts?: Parameters[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); + } + }); +});