diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index 090e9e32..8a803e12 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -14,10 +14,14 @@ import { type TableRow, type VaultFenceContext, } from '../../market-data-store'; -import { UNIVERSE_REFS } from '../../market-data-store-duckdb'; +import { + FUNDAMENTALS_PIT_VALUE_FIELDS, + type FundamentalsPitValueField, + UNIVERSE_REFS, +} from '../../market-data-store-duckdb'; import { SHORTS_SIGNAL_FIELDS, - type ShortsSignalField, + type SignalObservation, type SignalPanelDiagnostics, SignalPanelError, type SignalPanelErrorCode, @@ -44,8 +48,8 @@ import { UNIVERSE_MARKETS, type UniverseMarket, } from '../../trial-ledger'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; +import type { JsonSchemaObject, JsonSchemaProperty, McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool, zodObjectToJsonSchema } from '../server'; import { EXCLUSIVE_LISTING_SELECTOR_MESSAGE, MCP_MAX_LISTING_IDS, @@ -53,6 +57,7 @@ import { createUniverseFieldSchema, fenceVaultQueryBounds, formatMappedStoreError, + formatUtcIsoWithMicros, hasExclusiveListingSelector, isValidUtcBoundString, resolvePreStartUniverseDate, @@ -69,6 +74,9 @@ export const ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS = 252; /** Maximum number of latest dated observations exposed in the tool response preview. */ export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100; +/** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */ +export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120; + 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}$/; @@ -84,22 +92,37 @@ const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC const shortsSignalSpecSchema = z .object({ - source: z.literal('shorts').describe('Signal data source (currently "shorts").'), + source: z.literal('shorts').describe('Signal data source ("shorts").'), field: z .enum(SHORTS_SIGNAL_FIELDS) .describe('Short-interest field to evaluate (shares_short, net_change, or pct_float).'), }) .strict() - .describe('Discriminated signal source and field specification.'); + .describe('Short-interest signal specification.'); -/** - * Strict Zod input schema for the `analyze_signal` 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 analyzeSignalInputSchema = z +const fundamentalsSignalSpecSchema = z + .object({ + source: z.literal('fundamentals').describe('Signal data source ("fundamentals").'), + field: z + .enum(FUNDAMENTALS_PIT_VALUE_FIELDS) + .describe( + 'Point-in-time fundamentals value field to evaluate (revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, ttm_revenue, ttm_net_income, or ttm_operating_cash_flow).' + ), + allowEstimatedLag: z + .boolean() + .default(false) + .describe( + 'Whether to include fundamentals snapshots with estimated publication lag (default false).' + ), + }) + .strict() + .describe('Point-in-time fundamentals signal specification.'); + +const signalSpecSchema = z + .discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema]) + .describe('Discriminated signal source and field specification ("shorts" or "fundamentals").'); + +const analyzeSignalSharedFieldsSchema = z .object({ listingIds: createListingIdsFieldSchema( 'Explicit INT32 listing IDs to study (mutually exclusive with universe).' @@ -118,7 +141,6 @@ export const analyzeSignalInputSchema = z .describe( 'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.' ), - signal: shortsSignalSpecSchema, horizonSessions: z .number() .int() @@ -159,6 +181,19 @@ export const analyzeSignalInputSchema = z .default('raw') .describe('Bar price adjustment mode (default raw).'), }) + .strict(); + +/** + * Strict Zod input schema for the `analyze_signal` 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 analyzeSignalInputSchema = analyzeSignalSharedFieldsSchema + .extend({ + signal: signalSpecSchema, + }) .strict() .superRefine((data, ctx) => { if (!hasExclusiveListingSelector(data)) { @@ -185,18 +220,62 @@ export const analyzeSignalInputSchema = z message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`, }); } - } else if (data.signal.source === 'shorts' && data.universeMarket === 'FX') { + } else if (data.universeMarket === 'FX') { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['universeMarket'], message: - 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', + data.signal.source === 'shorts' + ? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).' + : 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', }); } }); export type AnalyzeSignalInput = z.infer; +function buildAnalyzeSignalJsonSchema(): JsonSchemaObject { + const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema); + const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema); + const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema); + const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? { + type: 'boolean' as const, + default: false, + }; + const signalProperty: JsonSchemaProperty = { + type: 'object', + description: signalSpecSchema.description, + properties: { + source: { + type: 'string', + enum: ['shorts', 'fundamentals'], + description: 'Signal data source ("shorts" or "fundamentals").', + }, + field: { + type: 'string', + enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS], + description: 'Signal field name valid for the chosen source.', + }, + allowEstimatedLag: allowEstimatedLagProp, + }, + required: ['source', 'field'], + additionalProperties: false, + anyOf: [shortsBranch, fundamentalsBranch], + }; + + return { + type: 'object', + properties: { + ...sharedSchema.properties, + signal: signalProperty, + }, + required: [...(sharedSchema.required ?? []), 'signal'], + additionalProperties: false, + }; +} + +const ANALYZE_SIGNAL_JSON_SCHEMA: JsonSchemaObject = buildAnalyzeSignalJsonSchema(); + /** Server-side injected configuration for {@link createAnalyzeSignalTool}. */ export interface AnalyzeSignalToolOptions { readonly store: MarketDataStore; @@ -250,10 +329,7 @@ interface AnalyzeSignalResultBase { readonly scope: 'vault_fenced'; readonly vaultCutoffTs: number; readonly vaultCutoffDate: string; - readonly signal: { - readonly source: 'shorts'; - readonly field: ShortsSignalField; - }; + readonly signal: AnalyzeSignalInput['signal']; readonly horizonSessions: number; readonly adjustment: 'raw' | 'split' | 'total'; readonly universeMarket: UniverseMarket; @@ -463,6 +539,127 @@ function filterEligibleShortsTable( }; } +function deriveMonthlySnapshotDates(bars: readonly BarRecord[]): string[] { + const latestByMonth = new Map(); + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i]; + if ( + typeof bar !== 'object' || + bar === null || + typeof bar.ts !== 'number' || + !Number.isFinite(bar.ts) + ) { + continue; + } + const sessionDate = utcDateOf(bar.ts); + const monthKey = sessionDate.slice(0, 7); + const prev = latestByMonth.get(monthKey); + if (prev === undefined || sessionDate > prev) { + latestByMonth.set(monthKey, sessionDate); + } + } + return [...latestByMonth.values()].sort(); +} + +function resolveSnapshotAsOf( + snapshotDate: string, + fencedAsOfMs: number, + canonicalAsOf: string +): { readonly asOf: string; readonly asOfMs: number } { + const snapshotDayEndMs = Date.parse(`${snapshotDate}T23:59:59.999Z`); + if (fencedAsOfMs <= snapshotDayEndMs) { + return { + asOf: canonicalAsOf, + asOfMs: fencedAsOfMs, + }; + } + return { + asOf: formatUtcIsoWithMicros(snapshotDayEndMs, 999), + asOfMs: snapshotDayEndMs, + }; +} + +function appendEligibleFundamentalsObservations(params: { + readonly table: Table; + readonly field: FundamentalsPitValueField; + readonly listingIdSet: ReadonlySet; + readonly snapshotAsOfMs: number; + readonly fencedAsOfMs: number; + readonly vaultCutoffTs: number; + readonly seenKeys: Set; + readonly out: SignalObservation[]; +}): void { + const { + table, + field, + listingIdSet, + snapshotAsOfMs, + fencedAsOfMs, + vaultCutoffTs, + seenKeys, + out, + } = params; + + if ( + typeof table !== 'object' || + table === null || + !Array.isArray(table.columns) || + !Array.isArray(table.rows) + ) { + throw new SignalPanelError( + 'invalid_input', + 'Expected a fundamentals Table object with array columns and rows.' + ); + } + + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i]; + if (typeof row !== 'object' || row === null) { + continue; + } + + const listingId = row.listing_id; + if ( + typeof listingId !== 'number' || + !Number.isSafeInteger(listingId) || + !listingIdSet.has(listingId) + ) { + continue; + } + + const knownAt = row.effective_known_at; + if ( + typeof knownAt !== 'number' || + !Number.isFinite(knownAt) || + !Number.isSafeInteger(knownAt) + ) { + continue; + } + if (knownAt > snapshotAsOfMs || knownAt > fencedAsOfMs || knownAt >= vaultCutoffTs) { + continue; + } + + const rawValue = row[field]; + if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { + continue; + } + + const normalizedListingId = listingId === 0 ? 0 : listingId; + const normalizedKnownAt = knownAt === 0 ? 0 : knownAt; + const normalizedValue = rawValue === 0 ? 0 : rawValue; + const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; + if (seenKeys.has(dedupeKey)) { + continue; + } + seenKeys.add(dedupeKey); + out.push({ + listingId: normalizedListingId, + knownAt: normalizedKnownAt, + value: normalizedValue, + }); + } +} + function buildCanonicalStudyExpression(params: { readonly input: AnalyzeSignalInput; readonly listingIds: readonly number[]; @@ -479,6 +676,9 @@ function buildCanonicalStudyExpression(params: { version: 1, signalSource: input.signal.source, signalField: input.signal.field, + ...(input.signal.source === 'fundamentals' + ? { allowEstimatedLag: input.signal.allowEstimatedLag } + : {}), horizonSessions: input.horizonSessions, maxSignalAgeSessions: input.maxSignalAgeSessions ?? null, adjustment: input.adjustment, @@ -553,10 +753,11 @@ function validateFactoryOptions(options: AnalyzeSignalToolOptions): number { options.store === null || typeof options.store.bars !== 'function' || typeof options.store.shortsAsOf !== 'function' || + typeof options.store.fundamentalsAsOf !== 'function' || typeof options.store.universe !== 'function' ) { throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, and `universe`.', + 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.', 'store' ); } @@ -602,8 +803,9 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT return defineMcpTool({ name: 'analyze_signal', description: - 'Run a Vault-fenced cross-sectional short-interest signal study and record eligible trials to trial_ledger.', + 'Run a Vault-fenced cross-sectional short-interest or point-in-time fundamentals signal study and record eligible trials to trial_ledger.', inputSchema: analyzeSignalInputSchema, + jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA, async handler(input: AnalyzeSignalInput): Promise { try { const fenced = fenceVaultQueryBounds( @@ -633,14 +835,23 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT listingIds = sortAndDedupeListingIds(input.listingIds ?? []); } + const signalEcho: AnalyzeSignalInput['signal'] = + input.signal.source === 'shorts' + ? { + source: 'shorts', + field: input.signal.field, + } + : { + source: 'fundamentals', + field: input.signal.field, + allowEstimatedLag: input.signal.allowEstimatedLag, + }; + const basePayloadFields = { scope: 'vault_fenced' as const, vaultCutoffTs, vaultCutoffDate: fenced.vaultCutoffDate, - signal: { - source: input.signal.source, - field: input.signal.field, - }, + signal: signalEcho, horizonSessions: input.horizonSessions, adjustment: input.adjustment, universeMarket: input.universeMarket, @@ -684,13 +895,6 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT }) ); - const rawShortsTable = await store.shortsAsOf({ - listingIds, - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - asOf: fenced.canonicalAsOf, - }); - const listingIdSet = new Set(listingIds); const eligibleBars = filterEligibleBars( rawBars, @@ -702,17 +906,65 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT fenced.vaultCutoffDate ); - const eligibleShortsTable = filterEligibleShortsTable( - rawShortsTable, - listingIdSet, - utcDateOf(fenced.fromMs), - utcDateOf(fenced.toMs), - fenced.asOfMs, - vaultCutoffTs, - fenced.vaultCutoffDate - ); + let signals: SignalObservation[]; + if (input.signal.source === 'shorts') { + const rawShortsTable = await store.shortsAsOf({ + listingIds, + from: fenced.canonicalFrom, + to: fenced.canonicalTo, + asOf: fenced.canonicalAsOf, + }); + const eligibleShortsTable = filterEligibleShortsTable( + rawShortsTable, + listingIdSet, + utcDateOf(fenced.fromMs), + utcDateOf(fenced.toMs), + fenced.asOfMs, + vaultCutoffTs, + fenced.vaultCutoffDate + ); + signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); + } else { + const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); + if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) { + return { + content: [ + { + type: 'text', + text: `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.`, + }, + ], + isError: true, + }; + } + + signals = []; + const seenKeys = new Set(); + for (const snapshotDate of snapshotDates) { + const snapshot = resolveSnapshotAsOf( + snapshotDate, + fenced.asOfMs, + fenced.canonicalAsOf + ); + const rawTable = await store.fundamentalsAsOf({ + listingIds, + fields: [input.signal.field], + asOf: snapshot.asOf, + allowEstimatedLag: input.signal.allowEstimatedLag, + }); + appendEligibleFundamentalsObservations({ + table: rawTable, + field: input.signal.field, + listingIdSet, + snapshotAsOfMs: snapshot.asOfMs, + fencedAsOfMs: fenced.asOfMs, + vaultCutoffTs, + seenKeys, + out: signals, + }); + } + } - const signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); const built = buildForwardReturnPanel({ bars: eligibleBars, signals, diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index e7840a38..40c52efd 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -10,11 +10,14 @@ import { } from '../src/market-data-store'; import { type BarsQuery, + FUNDAMENTALS_PIT_VALUE_FIELDS, + type FundamentalsAsOfQuery, MarketDataStoreNotImplementedError, type ShortsAsOfQuery, type UniverseQuery, } from '../src/market-data-store-duckdb'; import { + ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS, ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS, ANALYZE_SIGNAL_MAX_LISTING_IDS, ANALYZE_SIGNAL_MAX_SERIES_POINTS, @@ -23,9 +26,13 @@ import { createMcpServer, createQueryDataTool, } from '../src/mcp/index'; -import { buildForwardReturnPanel, shortsTableToSignalRows } from '../src/signal-panel'; +import { + type SignalObservation, + buildForwardReturnPanel, + shortsTableToSignalRows, +} from '../src/signal-panel'; import { analyzeSignal } from '../src/signal-study'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; +import { type TrialLedgerExecutor, canonicalExpressionHash } from '../src/trial-ledger'; const SEED = 20261129; const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; @@ -280,6 +287,7 @@ function buildCeoShortsFixture(options?: { interface FakeStoreState { readonly barsCalls: BarsQuery[]; readonly shortsCalls: ShortsAsOfQuery[]; + readonly fundamentalsCalls: FundamentalsAsOfQuery[]; readonly universeCalls: UniverseQuery[]; readonly store: MarketDataStore; } @@ -287,15 +295,18 @@ interface FakeStoreState { function createFakeStore(options?: { bars?: readonly BarRecord[]; shortsTable?: Table; + fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise; universeIds?: readonly number[]; universeResolver?: (q: UniverseQuery) => number[]; leaky?: boolean; barsError?: Error; shortsError?: Error; + fundamentalsError?: Error; universeError?: Error; }): FakeStoreState { const barsCalls: BarsQuery[] = []; const shortsCalls: ShortsAsOfQuery[] = []; + const fundamentalsCalls: FundamentalsAsOfQuery[] = []; const universeCalls: UniverseQuery[] = []; const allBars = options?.bars ?? []; @@ -394,7 +405,14 @@ function createFakeStore(options?: { crossSection() { throw new MarketDataStoreNotImplementedError('crossSection'); }, - fundamentalsAsOf() { + async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ + fundamentalsCalls.push(q); + if (options?.fundamentalsError !== undefined) { + throw options.fundamentalsError; + } + if (options?.fundamentalsResolver !== undefined) { + return options.fundamentalsResolver(q); + } throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); }, events() { @@ -408,7 +426,7 @@ function createFakeStore(options?: { }, }; - return { barsCalls, shortsCalls, universeCalls, store }; + return { barsCalls, shortsCalls, fundamentalsCalls, universeCalls, store }; } async function callAnalyzeSignal(params: { @@ -1593,3 +1611,1058 @@ describe('MCP analyze_signal tool', () => { expect(dsrFailLedger.rows).toHaveLength(1); }); }); + +interface FundamentalsPitFixtureRow { + readonly listing_id: number; + readonly effective_known_at: number; + readonly known_at_source: string; + readonly has_estimated_lag: boolean; + readonly period_end: string; + readonly fiscal_period: string; + readonly currency: string; + readonly period_known_at: number; + readonly revenue: number | null; + readonly net_income: number | null; + readonly operating_cash_flow: number | null; + readonly total_assets: number | null; + readonly total_equity: number | null; + readonly shares_outstanding: number | null; + readonly ttm_revenue: number | null; + readonly ttm_net_income: number | null; + readonly ttm_operating_cash_flow: number | null; + readonly ttm_period_end: string | null; + readonly ttm_currency: string | null; + readonly ttm_has_estimated_lag: boolean; +} + +const FUNDAMENTALS_TTM_FIELDS = new Set([ + 'ttm_revenue', + 'ttm_net_income', + 'ttm_operating_cash_flow', +]); + +function queryFundamentalsFixtureRows( + rows: readonly FundamentalsPitFixtureRow[], + q: FundamentalsAsOfQuery +): Table { + const idSet = new Set(q.listingIds); + const asOfMs = Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf); + const allowEstimatedLag = q.allowEstimatedLag ?? false; + + const latestByListing = new Map(); + for (const row of rows) { + if (!idSet.has(row.listing_id) || row.effective_known_at > asOfMs) { + continue; + } + const prev = latestByListing.get(row.listing_id); + if (prev === undefined || row.effective_known_at > prev.effective_known_at) { + latestByListing.set(row.listing_id, row); + } + } + + const hasTtm = q.fields.some(f => FUNDAMENTALS_TTM_FIELDS.has(f)); + const columns: string[] = [ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + ...q.fields, + ...(hasTtm ? ['ttm_period_end', 'ttm_currency', 'ttm_has_estimated_lag'] : []), + ]; + + const outRows: TableRow[] = []; + const sortedIds = [...latestByListing.keys()].sort((a, b) => a - b); + for (const lid of sortedIds) { + const selected = latestByListing.get(lid)!; + if (!allowEstimatedLag && selected.has_estimated_lag) { + continue; + } + const projected: Record = { + listing_id: selected.listing_id, + effective_known_at: selected.effective_known_at, + known_at_source: selected.known_at_source, + has_estimated_lag: selected.has_estimated_lag, + period_end: selected.period_end, + fiscal_period: selected.fiscal_period, + currency: selected.currency, + period_known_at: selected.period_known_at, + }; + for (const field of q.fields) { + const val = selected[field as keyof FundamentalsPitFixtureRow] as number | null; + if (FUNDAMENTALS_TTM_FIELDS.has(field)) { + projected[field] = allowEstimatedLag || !selected.ttm_has_estimated_lag ? val : null; + } else { + projected[field] = val; + } + } + if (hasTtm) { + projected.ttm_period_end = + allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_period_end : null; + projected.ttm_currency = + allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_currency : null; + projected.ttm_has_estimated_lag = selected.ttm_has_estimated_lag; + } + outRows.push(projected); + } + + return { columns, rows: outRows }; +} + +function makeFundamentalsRow(params: { + listingId: number; + effectiveKnownAt: number; + periodEnd: string; + fiscalPeriod: string; + revenue: number; + ttmRevenue: number; + hasEstimatedLag?: boolean; + ttmHasEstimatedLag?: boolean; +}): FundamentalsPitFixtureRow { + const hasEstimatedLag = params.hasEstimatedLag ?? false; + const ttmHasEstimatedLag = params.ttmHasEstimatedLag ?? false; + return { + listing_id: params.listingId, + effective_known_at: params.effectiveKnownAt, + known_at_source: hasEstimatedLag ? 'estimated_lag' : 'sec_edgar_filing', + has_estimated_lag: hasEstimatedLag, + period_end: params.periodEnd, + fiscal_period: params.fiscalPeriod, + currency: 'USD', + period_known_at: params.effectiveKnownAt, + revenue: params.revenue, + net_income: Number((params.revenue * 0.15).toFixed(2)), + operating_cash_flow: Number((params.revenue * 0.2).toFixed(2)), + total_assets: Number((params.revenue * 4.0).toFixed(2)), + total_equity: Number((params.revenue * 1.8).toFixed(2)), + shares_outstanding: 10_000_000, + ttm_revenue: params.ttmRevenue, + ttm_net_income: Number((params.ttmRevenue * 0.15).toFixed(2)), + ttm_operating_cash_flow: Number((params.ttmRevenue * 0.2).toFixed(2)), + ttm_period_end: params.periodEnd, + ttm_currency: 'USD', + ttm_has_estimated_lag: ttmHasEstimatedLag, + }; +} + +// Seeded fundamentals study fixture metadata (pinned for reproducibility): +// - Dataset ID: `synthetic:mcp-analyze-signal-fundamentals:seed-20261202:v1` +// - Tool version: `mcp:analyze_signal:v1` +// - Seed: `20261202` (Mulberry32 PRNG) +// - Universe: 12 synthetic US equity listings (`70001..70012`, USD, 21:00 UTC close) +// - Pre-Vault window: 2023-01-02..2023-06-30 (130 business sessions), Vault cutoff: 2023-07-03T00:00:00.000Z +// - Adjustment: `raw`, horizon: `5` sessions, modeled execution/transaction costs: `0` +// - Ownership: Quant research owns evidence; Director owns adoption. +const FUNDAMENTALS_FIXTURE_SEED = 20261202; + +function buildFundamentalsStudyFixture(): { + readonly listingIds: number[]; + readonly allDates: string[]; + readonly preCutoffSessions: number; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly bars: BarRecord[]; + readonly fundamentalsRows: FundamentalsPitFixtureRow[]; +} { + const rand = createSeededRng(FUNDAMENTALS_FIXTURE_SEED); + const listingCount = 12; + const preCutoffSessions = 130; + const postCutoffSessions = 10; + const allDates = makeBusinessDates('2023-01-02', preCutoffSessions + postCutoffSessions); + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i); + + const fundamentalsRows: FundamentalsPitFixtureRow[] = []; + // Monthly PIT releases across 6 pre-cutoff months + 1 post-cutoff release + const releaseDates = [ + { date: '2023-01-10', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, + { date: '2023-02-15', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, + { date: '2023-04-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, + { date: '2023-05-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, + { date: vaultCutoffDate, periodEnd: '2023-06-30', fiscalPeriod: 'Q2' }, + ]; + + const activeScore = new Float64Array(listingCount); + for (let rIdx = 0; rIdx < releaseDates.length; rIdx += 1) { + const rel = releaseDates[rIdx]!; + const knownAt = makeUtcMs(rel.date, 13); // 08:00 ET pre-close + for (let l = 0; l < listingCount; l += 1) { + const rev = 100 + l * 25 + rIdx * 10 + Math.round((rand() * 2 - 1) * 40); + const ttm = rev * 4 + (l % 3) * 15; + fundamentalsRows.push( + makeFundamentalsRow({ + listingId: listingIds[l]!, + effectiveKnownAt: knownAt, + periodEnd: rel.periodEnd, + fiscalPeriod: rel.fiscalPeriod, + revenue: rev, + ttmRevenue: ttm, + }) + ); + } + } + + const prices = new Float64Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + prices[l] = 20 + l * 3; + } + + const bars: BarRecord[] = []; + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingCount; l += 1) { + activeScore[l] = (l - listingCount / 2) / listingCount; + const dailyRet = 0.002 * activeScore[l]! + (rand() * 2 - 1) * 0.01; + prices[l] = Math.max(1.0, prices[l]! * (1 + dailyRet)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 80_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + return { + listingIds, + allDates, + preCutoffSessions, + vaultCutoffDate, + vaultCutoffTs, + bars, + fundamentalsRows, + }; +} + +describe('MCP analyze_signal tool — fundamentals source', () => { + test('tools/list advertises strict signal discriminated branches and rejects invalid fundamentals inputs with zero store/ledger calls', async () => { + const cutoffTs = makeUtcMs('2025-03-31', 0); + const fakeStore = createFakeStore(); + const fakeLedger = createFakeTrialLedger(); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createAnalyzeSignalTool({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultContext: { vaultCutoffTs: cutoffTs }, + principalId: AGENT_PRINCIPAL, + }), + ], + }); + + const listRaw = await server.handleMessage( + JSON.stringify({ jsonrpc: '2.0', id: 'list-fund', method: 'tools/list' }) + ); + const listParsed = JSON.parse(listRaw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + properties: { + signal: { + type: string; + additionalProperties: boolean; + properties: Record; + anyOf: { + additionalProperties: boolean; + properties: Record; + }[]; + }; + }; + }; + }[]; + }; + }; + + const tool = listParsed.result.tools[0]!; + expect(tool.description).toContain('fundamentals'); + expect(tool.description).toContain('short-interest'); + + const signalSchema = tool.inputSchema.properties.signal; + expect(signalSchema.type).toBe('object'); + expect(signalSchema.additionalProperties).toBe(false); + expect(Object.keys(signalSchema.properties).sort()).toEqual([ + 'allowEstimatedLag', + 'field', + 'source', + ]); + expect(signalSchema.anyOf).toHaveLength(2); + expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false); + expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts'); + expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false); + expect(signalSchema.anyOf[1]?.properties.source?.const).toBe('fundamentals'); + expect(signalSchema.anyOf[1]?.properties.field?.enum).toEqual([...FUNDAMENTALS_PIT_VALUE_FIELDS]); + expect(signalSchema.anyOf[1]?.properties.allowEstimatedLag?.default).toBe(false); + + const validBase = { + listingIds: [70_001, 70_002], + from: '2023-01-02', + to: '2023-06-30', + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const invalidCases: readonly [string, Record][] = [ + ['unknown fundamentals field', { ...validBase, signal: { source: 'fundamentals', field: 'ebitda_fake' } }], + ['shorts field on fundamentals source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }], + ['fundamentals field on shorts source', { ...validBase, signal: { source: 'shorts', field: 'ttm_revenue' } }], + ['unknown signal.source', { ...validBase, signal: { source: 'macro', field: 'ttm_revenue' } }], + [ + 'unknown nested key in fundamentals signal', + { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', extraKey: true } }, + ], + [ + 'allowEstimatedLag on shorts source', + { ...validBase, signal: { source: 'shorts', field: 'net_change', allowEstimatedLag: false } }, + ], + [ + 'non-boolean allowEstimatedLag string', + { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 'true' } }, + ], + [ + 'non-boolean allowEstimatedLag number', + { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 1 } }, + ], + ['fundamentals study with FX universeMarket', { ...validBase, universeMarket: 'FX' }], + ]; + + for (const [_label, args] of invalidCases) { + const store = createFakeStore(); + const ledger = createFakeTrialLedger(); + const res = await callAnalyzeSignal({ + store: store.store, + ledger: ledger.executor, + vaultCutoffTs: cutoffTs, + args, + }); + expect(res.isError).toBe(true); + expect(res.text).toContain('Invalid arguments for tool "analyze_signal":'); + expect(store.barsCalls).toHaveLength(0); + expect(store.shortsCalls).toHaveLength(0); + expect(store.fundamentalsCalls).toHaveLength(0); + expect(store.universeCalls).toHaveLength(0); + expect(ledger.insertCalls).toBe(0); + } + }); + + test('executes fundamentals study, records canonical fundamentals expressionHash, forwards allowEstimatedLag verbatim, and preserves identity on append-only retry', async () => { + const fixture = buildFundamentalsStudyFixture(); + const from = fixture.allDates[0]!; + const to = fixture.allDates[fixture.preCutoffSessions - 1]!; + + const store = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const sharedLedger = createFakeTrialLedger(); + + const baseArgs = { + listingIds: fixture.listingIds, + from, + to, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + campaignId: CAMPAIGN_UUID, + hypothesisId: HYPOTHESIS_UUID, + }; + + const res1 = await callAnalyzeSignal({ + store: store.store, + ledger: sharedLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + principalId: AGENT_PRINCIPAL, + args: baseArgs, + }); + expect(res1.isError).toBe(false); + const payload1 = JSON.parse(res1.text) as AnalyzeSignalResultPayload; + expect(payload1.status).toBe('ok'); + if (payload1.status !== 'ok') { + return; + } + + expect(payload1.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: false, + }); + expect(sharedLedger.rows).toHaveLength(1); + expect(sharedLedger.rows[0]?.stage).toBe('signal_ic'); + expect(sharedLedger.rows[0]?.principal_id).toBe(AGENT_PRINCIPAL); + + // Verify canonical expression prefix `mcp:analyze_signal:v1:fundamentals:` via canonicalExpressionHash + const expectedHash = canonicalExpressionHash({ + expression: 'mcp:analyze_signal:v1:fundamentals:ttm_revenue', + params: { + version: 1, + signalSource: 'fundamentals', + signalField: 'ttm_revenue', + allowEstimatedLag: false, + horizonSessions: 5, + maxSignalAgeSessions: null, + adjustment: 'raw', + ledgerSeries: 'rank_ic', + effectiveFrom: payload1.effectiveFrom, + effectiveTo: payload1.effectiveTo, + effectiveAsOf: payload1.effectiveAsOf, + }, + universe: { + kind: 'listingIds', + listingIds: fixture.listingIds, + }, + horizon: '5d', + sampleStart: payload1.trial.sampleStart, + sampleEnd: payload1.trial.sampleEnd, + }); + expect(payload1.trial.expressionHash).toBe(expectedHash); + expect(sharedLedger.rows[0]?.expression_hash).toBe(expectedHash); + + // Default allowEstimatedLag === false forwarded verbatim to every fundamentalsAsOf call + expect(store.fundamentalsCalls.length).toBeGreaterThan(0); + expect(store.shortsCalls).toHaveLength(0); + for (const call of store.fundamentalsCalls) { + expect(call.fields).toEqual(['ttm_revenue']); + expect(call.allowEstimatedLag).toBe(false); + } + + // Re-running identical request against the SAME ledger appends under append-only rules with one distinct expression_hash + const res2 = await callAnalyzeSignal({ + store: store.store, + ledger: sharedLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + principalId: AGENT_PRINCIPAL, + args: baseArgs, + }); + expect(res2.isError).toBe(false); + const payload2 = JSON.parse(res2.text) as AnalyzeSignalResultPayload; + expect(payload2.status).toBe('ok'); + if (payload2.status !== 'ok') { + return; + } + expect(payload2.trial.expressionHash).toBe(payload1.trial.expressionHash); + expect(new Set(sharedLedger.rows.map(r => r.expression_hash)).size).toBe(1); + + // Explicit allowEstimatedLag: false and reordered/duplicated listingIds preserve identity + const explicitFalseStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const explicitFalseLedger = createFakeTrialLedger(); + const reorderedIds = [...fixture.listingIds].reverse(); + reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[2]!); + const resExplicitFalse = await callAnalyzeSignal({ + store: explicitFalseStore.store, + ledger: explicitFalseLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + listingIds: reorderedIds, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: false }, + }, + }); + const payloadExplicitFalse = JSON.parse(resExplicitFalse.text) as AnalyzeSignalResultPayload; + expect(payloadExplicitFalse.status).toBe('ok'); + if (payloadExplicitFalse.status === 'ok') { + expect(payloadExplicitFalse.trial.expressionHash).toBe(payload1.trial.expressionHash); + } + expect(explicitFalseStore.fundamentalsCalls.every(c => c.allowEstimatedLag === false)).toBe(true); + + // allowEstimatedLag: true forwards true verbatim and changes expressionHash + const lagTrueStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const lagTrueLedger = createFakeTrialLedger(); + const resLagTrue = await callAnalyzeSignal({ + store: lagTrueStore.store, + ledger: lagTrueLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, + }, + }); + const payloadLagTrue = JSON.parse(resLagTrue.text) as AnalyzeSignalResultPayload; + expect(payloadLagTrue.status).toBe('ok'); + if (payloadLagTrue.status === 'ok') { + expect(payloadLagTrue.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: true, + }); + expect(payloadLagTrue.trial.expressionHash).not.toBe(payload1.trial.expressionHash); + } + expect(lagTrueStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); + + // Different field changes expressionHash + const otherFieldStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const otherFieldLedger = createFakeTrialLedger(); + const resOtherField = await callAnalyzeSignal({ + store: otherFieldStore.store, + ledger: otherFieldLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + signal: { source: 'fundamentals', field: 'revenue' }, + }, + }); + const payloadOtherField = JSON.parse(resOtherField.text) as AnalyzeSignalResultPayload; + expect(payloadOtherField.status).toBe('ok'); + if (payloadOtherField.status === 'ok') { + expect(payloadOtherField.trial.expressionHash).not.toBe(payload1.trial.expressionHash); + } + + // Shorts study over the same window/listings produces a distinct expressionHash + const shortsRows: TableRow[] = fixture.listingIds.map((lid, i) => ({ + listing_id: lid, + report_date: from, + known_at: makeUtcMs(from, 12), + shares_short: 100_000 + i * 5_000, + net_change: (i - 5) * 1_000, + pct_float: 0.03 + i * 0.005, + source: 'ceoShorts', + })); + const shortsStore = createFakeStore({ + bars: fixture.bars, + shortsTable: { columns: SHORTS_COLUMNS, rows: shortsRows }, + }); + const shortsLedger = createFakeTrialLedger(); + const resShorts = await callAnalyzeSignal({ + store: shortsStore.store, + ledger: shortsLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + signal: { source: 'shorts', field: 'net_change' }, + }, + }); + const payloadShorts = JSON.parse(resShorts.text) as AnalyzeSignalResultPayload; + expect(payloadShorts.status).toBe('ok'); + if (payloadShorts.status === 'ok') { + expect(payloadShorts.trial.expressionHash).not.toBe(payload1.trial.expressionHash); + } + }); + + test('queries month-end snapshots in ascending order from unsorted bars, preserves earlier explicit asOf, enforces 120-snapshot cap, and handles empty bars', async () => { + // 1. Unsorted bars spanning 3 UTC months (2 full + 1 partial final month) with earlier intraday asOf + const janDates = ['2023-01-10', '2023-01-31']; + const febDates = ['2023-02-14', '2023-02-28']; + const marDates = ['2023-03-08', '2023-03-15']; + const unsortedDates = [...marDates, ...janDates, ...febDates].reverse(); + const bars: BarRecord[] = []; + for (const date of unsortedDates) { + const ts = makeUtcMs(date, 21); + for (const lid of [101, 102]) { + bars.push({ + listingId: lid, + ts, + open: 10, + high: 10, + low: 10, + close: 10, + volume: 100, + vwap: 10, + knownAt: ts, + }); + } + } + + const cutoffTs = makeUtcMs('2023-04-01', 0); + const storeOrder = createFakeStore({ + bars, + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const ledgerOrder = createFakeTrialLedger(); + + // Earlier explicit asOf on 2023-03-15T22:30:00.123456Z (after 21:00 bar close, before day end) + const explicitAsOf = '2023-03-15T22:30:00.123456Z'; + const orderRes = await callAnalyzeSignal({ + store: storeOrder.store, + ledger: ledgerOrder.executor, + vaultCutoffTs: cutoffTs, + args: { + listingIds: [102, 101], + from: '2023-01-01', + to: '2023-03-31', + asOf: explicitAsOf, + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(orderRes.isError).toBe(false); + expect(storeOrder.fundamentalsCalls.map(c => c.asOf)).toEqual([ + '2023-01-31T23:59:59.999999Z', + '2023-02-28T23:59:59.999999Z', + explicitAsOf, + ]); + expect(storeOrder.fundamentalsCalls.every(c => c.listingIds[0] === 101 && c.listingIds[1] === 102)).toBe(true); + + // 2. Empty eligible bar sample -> 0 fundamentalsAsOf calls, insufficient_data, 0 ledger writes + const emptyBarsStore = createFakeStore({ + bars: [], + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const emptyBarsLedger = createFakeTrialLedger(); + const emptyRes = await callAnalyzeSignal({ + store: emptyBarsStore.store, + ledger: emptyBarsLedger.executor, + vaultCutoffTs: cutoffTs, + args: { + listingIds: [101, 102], + from: '2023-01-01', + to: '2023-03-31', + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(emptyRes.isError).toBe(false); + const emptyPayload = JSON.parse(emptyRes.text) as AnalyzeSignalResultPayload; + expect(emptyPayload.status).toBe('insufficient_data'); + if (emptyPayload.status === 'insufficient_data') { + expect(emptyPayload.reason).toBe('too_few_observations'); + } + expect(emptyBarsStore.fundamentalsCalls).toHaveLength(0); + expect(emptyBarsLedger.rows).toHaveLength(0); + + // 3. Exactly 120 eligible UTC months is accepted; 121 is rejected with 0 fundamentals calls and 0 ledger inserts + function makeMonthlyBars(monthCount: number): BarRecord[] { + const out: BarRecord[] = []; + for (let m = 0; m < monthCount; m += 1) { + const year = 2010 + Math.floor(m / 12); + const month = (m % 12) + 1; + const date = `${year}-${String(month).padStart(2, '0')}-15`; + const ts = makeUtcMs(date, 21); + out.push({ + listingId: 101, + ts, + open: 10, + high: 10, + low: 10, + close: 10, + volume: 100, + vwap: 10, + knownAt: ts, + }); + } + return out; + } + + const capCutoffTs = makeUtcMs('2025-01-01', 0); + const exactCapStore = createFakeStore({ + bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS), + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const exactCapLedger = createFakeTrialLedger(); + const exactCapRes = await callAnalyzeSignal({ + store: exactCapStore.store, + ledger: exactCapLedger.executor, + vaultCutoffTs: capCutoffTs, + args: { + listingIds: [101], + from: '2010-01-01', + to: '2024-12-31', + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(exactCapRes.isError).toBe(false); + expect(exactCapStore.fundamentalsCalls).toHaveLength(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS); + + const overCapStore = createFakeStore({ + bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS + 1), + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const overCapLedger = createFakeTrialLedger(); + const overCapRes = await callAnalyzeSignal({ + store: overCapStore.store, + ledger: overCapLedger.executor, + vaultCutoffTs: capCutoffTs, + args: { + listingIds: [101], + from: '2010-01-01', + to: '2024-12-31', + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(overCapRes.isError).toBe(true); + expect(overCapRes.text).toBe( + `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.` + ); + expect(overCapStore.fundamentalsCalls).toHaveLength(0); + expect(overCapLedger.insertCalls).toBe(0); + expect(overCapLedger.rows).toHaveLength(0); + }); + + test('restatement replay prevents look-ahead: dates before Q1 restatement use originally known values and appending a future revision leaves prior output unchanged', async () => { + // Explicit deterministic restatement fixture: + // - 6 listings across 2023-01-02..2023-05-31 (108 sessions), Vault cutoff 2023-06-01T00:00:00Z + // - Original Q1 known 2023-01-12T13:00Z (period_end 2022-12-31) + // - Original Q2 known 2023-02-15T13:00Z (period_end 2023-01-31) + // - Q1 restatement known 2023-04-12T13:00Z (AFTER Q2!): period_end stays 2023-01-31 (Q2), + // while ttm_revenue flips cross-sectional ordering for listings 0..5. + // - Unchanged months (March, May) re-emit identical (listing_id, effective_known_at) -> deduped cleanly. + const listingIds = [80_001, 80_002, 80_003, 80_004, 80_005, 80_006]; + const allDates = makeBusinessDates('2023-01-02', 112); + const preCutoffDates = allDates.filter(d => d < '2023-06-01'); + const vaultCutoffDate = '2023-06-01'; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const q1KnownAt = makeUtcMs('2023-01-12', 13); + const q2KnownAt = makeUtcMs('2023-02-15', 13); + const q1RestatedKnownAt = makeUtcMs('2023-04-12', 13); + const futureRevisionKnownAt = makeUtcMs('2023-06-15', 13); // post-cutoff + + const rand = createSeededRng(20261203); + const bars: BarRecord[] = []; + const prices = new Float64Array(listingIds.length).fill(50); + for (let t = 0; t < preCutoffDates.length; t += 1) { + const date = preCutoffDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingIds.length; l += 1) { + const ret = (l - 2.5) * 0.0015 + (rand() * 2 - 1) * 0.008; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const 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, + }); + } + } + + const basePitRows: FundamentalsPitFixtureRow[] = []; + const expectedDirectObs: SignalObservation[] = []; + + for (let l = 0; l < listingIds.length; l += 1) { + const lid = listingIds[l]!; + const q1Val = 100 + l * 20; + const q2Val = 120 + l * 25; + // Restatement reverses cross-sectional rank ordering after 2023-04-12 + const restatedVal = 300 - l * 30; + + basePitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: q1KnownAt, + periodEnd: '2022-12-31', + fiscalPeriod: 'Q1', + revenue: q1Val / 4, + ttmRevenue: q1Val, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: q2KnownAt, + periodEnd: '2023-01-31', + fiscalPeriod: 'Q2', + revenue: q2Val / 4, + ttmRevenue: q2Val, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: q1RestatedKnownAt, + periodEnd: '2023-01-31', + fiscalPeriod: 'Q2', + revenue: q2Val / 4, + ttmRevenue: restatedVal, + }) + ); + + expectedDirectObs.push( + { listingId: lid, knownAt: q1KnownAt, value: q1Val }, + { listingId: lid, knownAt: q2KnownAt, value: q2Val }, + { listingId: lid, knownAt: q1RestatedKnownAt, value: restatedVal } + ); + } + + // 1. Direct baseline using independently specified eligible observations + const directLedger = createFakeTrialLedger(); + const directBuilt = buildForwardReturnPanel({ + bars, + signals: expectedDirectObs, + horizonSessions: 5, + vaultCutoffDate, + }); + const directStudy = await analyzeSignal(directLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_restatement_baseline', + params: { field: 'ttm_revenue', horizonSessions: 5 }, + universe: listingIds, + horizon: '5d', + }, + panel: directBuilt.panel, + vaultCutoffDate, + }); + expect(directStudy.status).toBe('ok'); + if (directStudy.status !== 'ok') { + return; + } + + // 2. MCP handler run on base rows (before future revision is appended) + const args = { + listingIds, + from: preCutoffDates[0]!, + to: preCutoffDates[preCutoffDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const mcpStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(basePitRows, q), + }); + const mcpLedger = createFakeTrialLedger(); + const mcpRes = await callAnalyzeSignal({ + store: mcpStore.store, + ledger: mcpLedger.executor, + vaultCutoffTs, + args, + }); + expect(mcpRes.isError).toBe(false); + const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; + expect(mcpPayload.status).toBe('ok'); + if (mcpPayload.status !== 'ok') { + return; + } + + // Exact parity between MCP handler and direct baseline (dates, rankIc, ledger daily_series) + expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); + expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); + expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); + expect(mcpPayload.trial.sampleStart).toBe(directStudy.trial.sampleStart); + expect(mcpPayload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd); + // Forward return endpoint remains strictly before vaultCutoffDate + const sampleEndIdx = preCutoffDates.indexOf(mcpPayload.trial.sampleEnd); + expect(sampleEndIdx).toBeGreaterThanOrEqual(0); + expect(sampleEndIdx + 5).toBeLessThan(preCutoffDates.length); + expect(preCutoffDates[sampleEndIdx + 5]! < vaultCutoffDate).toBe(true); + + // Confirm pre-restatement dates (between 2023-02-15 and 2023-04-11) actually differ from a look-ahead study + // that wrongly substitutes the restated values onto Q2's earlier known_at! + const lookAheadObs = expectedDirectObs.map(o => + o.knownAt === q2KnownAt + ? { ...o, value: 300 - (o.listingId - 80_001) * 30 } + : o + ); + const lookAheadBuilt = buildForwardReturnPanel({ + bars, + signals: lookAheadObs, + horizonSessions: 5, + vaultCutoffDate, + }); + const lookAheadLedger = createFakeTrialLedger(); + const lookAheadStudy = await analyzeSignal(lookAheadLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'look_ahead_counterfactual', + params: { field: 'ttm_revenue', horizonSessions: 5 }, + universe: listingIds, + horizon: '5d', + }, + panel: lookAheadBuilt.panel, + vaultCutoffDate, + }); + expect(lookAheadStudy.status).toBe('ok'); + expect(mcpLedger.rows[0]?.daily_series).not.toEqual(lookAheadLedger.rows[0]?.daily_series); + + // 3. Append a future revision (post-cutoff) and verify all prior dated outputs & ledger rows remain bit-identical + const rowsWithFutureRevision: FundamentalsPitFixtureRow[] = [ + ...basePitRows, + ...listingIds.map((lid, l) => + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: futureRevisionKnownAt, + periodEnd: '2023-01-31', + fiscalPeriod: 'Q2', + revenue: 999, + ttmRevenue: 9_999 + l, + }) + ), + ]; + const futureStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(rowsWithFutureRevision, q), + }); + const futureLedger = createFakeTrialLedger(); + const futureRes = await callAnalyzeSignal({ + store: futureStore.store, + ledger: futureLedger.executor, + vaultCutoffTs, + args, + }); + expect(futureRes.isError).toBe(false); + expect(futureRes.text).toBe(mcpRes.text); + expect(futureLedger.rows).toEqual(mcpLedger.rows); + }); + + test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { + const fixture = buildFundamentalsStudyFixture(); + const from = fixture.allDates[0]!; + const postCutoffDate = fixture.allDates[fixture.allDates.length - 1]!; + + const cleanStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const leakyStore = createFakeStore({ + bars: fixture.bars, + leaky: true, + fundamentalsResolver: q => { + const cleanTable = queryFundamentalsFixtureRows(fixture.fundamentalsRows, q); + const snapAsOfMs = Date.parse(q.asOf); + const poisonedRows: TableRow[] = [ + // 1. effective_known_at strictly after individual snapshot asOf (but before vaultCutoffTs) + { + listing_id: fixture.listingIds[0]!, + effective_known_at: snapAsOfMs + 60_000, + ttm_revenue: 999_999, + }, + // 2. effective_known_at at exact vaultCutoffTs + { + listing_id: fixture.listingIds[1]!, + effective_known_at: fixture.vaultCutoffTs, + ttm_revenue: 888_888, + }, + // 3. effective_known_at after vaultCutoffTs + { + listing_id: fixture.listingIds[2]!, + effective_known_at: fixture.vaultCutoffTs + 86_400_000, + ttm_revenue: 777_777, + }, + // 4. unrequested listing_id + { + listing_id: 999_999, + effective_known_at: makeUtcMs(from, 12), + ttm_revenue: 666_666, + }, + // 5. non-safe-integer effective_known_at (float & NaN) + { + listing_id: fixture.listingIds[3]!, + effective_known_at: makeUtcMs(from, 12) + 0.5, + ttm_revenue: 555_555, + }, + { + listing_id: fixture.listingIds[3]!, + effective_known_at: Number.NaN, + ttm_revenue: 555_555, + }, + // 6. null, NaN, and Infinity field values + { + listing_id: fixture.listingIds[4]!, + effective_known_at: makeUtcMs(from, 12), + ttm_revenue: null, + }, + { + listing_id: fixture.listingIds[4]!, + effective_known_at: makeUtcMs(from, 12) + 1_000, + ttm_revenue: Number.NaN, + }, + { + listing_id: fixture.listingIds[4]!, + effective_known_at: makeUtcMs(from, 12) + 2_000, + ttm_revenue: Number.POSITIVE_INFINITY, + }, + ]; + return { + columns: cleanTable.columns, + rows: [...cleanTable.rows, ...poisonedRows], + }; + }, + }); + + const cleanLedger = createFakeTrialLedger(); + const leakyLedger = createFakeTrialLedger(); + const args = { + listingIds: fixture.listingIds, + from, + to: postCutoffDate, + asOf: postCutoffDate, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const cleanRes = await callAnalyzeSignal({ + store: cleanStore.store, + ledger: cleanLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + const leakyRes = await callAnalyzeSignal({ + store: leakyStore.store, + ledger: leakyLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + + expect(cleanRes.isError).toBe(false); + expect(leakyRes.isError).toBe(false); + expect(leakyRes.text).toBe(cleanRes.text); + expect(leakyLedger.rows).toEqual(cleanLedger.rows); + + // Every fundamentalsAsOf call's asOf is strictly before vaultCutoffTs + expect(cleanStore.fundamentalsCalls.length).toBeGreaterThan(0); + for (const call of [...cleanStore.fundamentalsCalls, ...leakyStore.fundamentalsCalls]) { + expect(Date.parse(call.asOf)).toBeLessThan(fixture.vaultCutoffTs); + } + + // Malformed fundamentals table -> sanitized SignalPanelError with zero ledger writes + const badTableStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: () => ({ columns: null, rows: null } as unknown as Table), + }); + const badTableLedger = createFakeTrialLedger(); + const badTableRes = await callAnalyzeSignal({ + store: badTableStore.store, + ledger: badTableLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + expect(badTableRes.isError).toBe(true); + expect(badTableRes.text).toBe('SignalPanelError: Invalid signal panel input.'); + expect(badTableLedger.rows).toHaveLength(0); + }); +}); diff --git a/libs/research/test/mcp-copilot-server.test.ts b/libs/research/test/mcp-copilot-server.test.ts index 2bc4ab24..8bd18a11 100644 --- a/libs/research/test/mcp-copilot-server.test.ts +++ b/libs/research/test/mcp-copilot-server.test.ts @@ -217,6 +217,7 @@ interface CopilotStudyFixture { readonly postCutoffDate: string; readonly bars: readonly BarRecord[]; readonly shortsTable: Table; + readonly fundamentalsRows: readonly TableRow[]; readonly eventsTable: Table; readonly symbols: readonly SymbolSearchRow[]; readonly exchangeCalendars: EventStudyExchangeCalendars; @@ -238,8 +239,42 @@ function buildCopilotStudyFixture(): CopilotStudyFixture { const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); const bars: BarRecord[] = []; const shortsRows: TableRow[] = []; + const fundamentalsRows: TableRow[] = []; const eventRows: TableRow[] = []; + const fundamentalReleaseIndices = [0, 22, 44, 64]; + for (let rIdx = 0; rIdx < fundamentalReleaseIndices.length; rIdx += 1) { + const t = fundamentalReleaseIndices[rIdx]!; + const relDate = allDates[t]!; + const effectiveKnownAt = makeUtcMs(relDate, 13); // 08:00 ET pre-close + for (let l = 0; l < listingCount; l += 1) { + const revenue = 250 + ((l * 7 + rIdx * 5) % listingCount) * 40 + rIdx * 15; + const ttmRevenue = revenue * 4 + ((l + rIdx) % 4) * 25; + fundamentalsRows.push({ + listing_id: listingIds[l]!, + effective_known_at: effectiveKnownAt, + known_at_source: 'sec_edgar_filing', + has_estimated_lag: false, + period_end: relDate, + fiscal_period: `Q${(rIdx % 4) + 1}`, + currency: 'USD', + period_known_at: effectiveKnownAt, + revenue, + net_income: Number((revenue * 0.14).toFixed(2)), + operating_cash_flow: Number((revenue * 0.19).toFixed(2)), + total_assets: Number((revenue * 3.8).toFixed(2)), + total_equity: Number((revenue * 1.7).toFixed(2)), + shares_outstanding: 10_000_000, + ttm_revenue: ttmRevenue, + ttm_net_income: Number((ttmRevenue * 0.14).toFixed(2)), + ttm_operating_cash_flow: Number((ttmRevenue * 0.19).toFixed(2)), + ttm_period_end: relDate, + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }); + } + } + const eventDayIndices = [12, 20, 28, 38, 48, 58]; const eventSet = new Set(); for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { @@ -362,6 +397,7 @@ function buildCopilotStudyFixture(): CopilotStudyFixture { columns: [...SHORTS_COLUMNS], rows: shortsRows, }, + fundamentalsRows, eventsTable: { columns: [...EVENTS_COLUMNS], rows: eventRows, @@ -378,6 +414,7 @@ interface FakeMarketDataStoreHandle { readonly store: MarketDataStore; readonly getBarsCalls: () => number; readonly getShortsCalls: () => number; + readonly getFundamentalsCalls: () => number; readonly getEventsCalls: () => number; readonly getUniverseCalls: () => number; } @@ -391,6 +428,7 @@ function createFakeMarketDataStore( const leaky = options?.leakyVaultRows ?? false; let barsCalls = 0; let shortsCalls = 0; + let fundamentalsCalls = 0; let eventsCalls = 0; let universeCalls = 0; @@ -537,8 +575,63 @@ function createFakeMarketDataStore( async crossSection() { throw new MarketDataStoreNotImplementedError('crossSection'); }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + async fundamentalsAsOf(q): Promise
{ + fundamentalsCalls += 1; + const idSet = new Set(q.listingIds); + const asOfMs = parseBoundMs(q.asOf, true); + const allowEstimatedLag = q.allowEstimatedLag ?? false; + const latestByListing = new Map(); + + for (const row of fixture.fundamentalsRows) { + const listingId = row.listing_id as number; + const knownAt = row.effective_known_at as number; + if (!idSet.has(listingId) || knownAt > asOfMs) { + continue; + } + const prev = latestByListing.get(listingId); + if (prev === undefined || knownAt > (prev.effective_known_at as number)) { + latestByListing.set(listingId, row); + } + } + + const rows: TableRow[] = []; + for (const lid of [...latestByListing.keys()].sort((a, b) => a - b)) { + const row = latestByListing.get(lid)!; + if (!allowEstimatedLag && row.has_estimated_lag === true) { + continue; + } + rows.push(row); + } + + if (leaky) { + rows.push({ + listing_id: fixture.listingIds[0]!, + effective_known_at: fixture.vaultCutoffTs, + known_at_source: 'sec_edgar_filing', + has_estimated_lag: false, + period_end: fixture.vaultCutoffDate, + fiscal_period: 'Q4', + currency: 'USD', + period_known_at: fixture.vaultCutoffTs, + revenue: 999_999, + ttm_revenue: 999_999, + }); + } + + return { + columns: [ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + ...q.fields, + ], + rows, + }; }, async macroAsOf() { throw new MarketDataStoreNotImplementedError('macroAsOf'); @@ -552,6 +645,7 @@ function createFakeMarketDataStore( store, getBarsCalls: () => barsCalls, getShortsCalls: () => shortsCalls, + getFundamentalsCalls: () => fundamentalsCalls, getEventsCalls: () => eventsCalls, getUniverseCalls: () => universeCalls, }; @@ -763,13 +857,14 @@ describe('createResearchCopilotMcpServer', () => { } }); - test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal -> event_study -> read_knowledge -> file_finding in one stdio session', async () => { + test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal (shorts + fundamentals) -> event_study -> read_knowledge -> file_finding in one stdio session', async () => { const fixture = buildCopilotStudyFixture(); - const { serverOptions, ledger, findings } = buildComposedServerOptions(fixture); + const { serverOptions, storeHandle, ledger, findings } = buildComposedServerOptions(fixture); const server = createResearchCopilotMcpServer(serverOptions); const sink = createMemoryOutput(); - let signalTrialRef = ''; + let shortsTrialRef = ''; + let fundamentalsTrialRef = ''; async function* requestStream(): AsyncGenerator { yield `${JSON.stringify({ @@ -839,6 +934,25 @@ describe('createResearchCopilotMcpServer', () => { jsonrpc: '2.0', id: 6, method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: fixture.lastPreCutoffDate, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + adjustment: 'raw', + }, + }, + })}\n`; + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 7, + method: 'tools/call', params: { name: 'event_study', arguments: { @@ -858,7 +972,7 @@ describe('createResearchCopilotMcpServer', () => { yield `${JSON.stringify({ jsonrpc: '2.0', - id: 7, + id: 8, method: 'tools/call', params: { name: 'read_knowledge', @@ -866,28 +980,36 @@ describe('createResearchCopilotMcpServer', () => { }, })}\n`; - // Decode the earlier analyze_signal response written by runStdioServer before - // constructing the file_finding call so the trialRef is dynamically linked. - expect(sink.lines.length).toBeGreaterThanOrEqual(5); - const signalResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope; - const signalPayload = decodeToolJson(signalResp); - expect(signalPayload.status).toBe('ok'); - if (signalPayload.status !== 'ok') { - throw new Error('Expected analyze_signal status to be ok.'); + // Decode both earlier analyze_signal responses written by runStdioServer before + // constructing the file_finding call so both trialRefs are dynamically linked. + expect(sink.lines.length).toBeGreaterThanOrEqual(6); + const shortsResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope; + const shortsPayload = decodeToolJson(shortsResp); + expect(shortsPayload.status).toBe('ok'); + if (shortsPayload.status !== 'ok') { + throw new Error('Expected shorts analyze_signal status to be ok.'); } - signalTrialRef = String(signalPayload.trial.trialId); + shortsTrialRef = String(shortsPayload.trial.trialId); + + const fundamentalsResp = JSON.parse(sink.lines[5]!) as JsonRpcResponseEnvelope; + const fundamentalsPayload = decodeToolJson(fundamentalsResp); + expect(fundamentalsPayload.status).toBe('ok'); + if (fundamentalsPayload.status !== 'ok') { + throw new Error('Expected fundamentals analyze_signal status to be ok.'); + } + fundamentalsTrialRef = String(fundamentalsPayload.trial.trialId); yield `${JSON.stringify({ jsonrpc: '2.0', - id: 8, + id: 9, method: 'tools/call', params: { name: 'file_finding', arguments: { kind: 'finding', - title: 'Short-interest net_change study on synthetic US_EQ panel', + title: 'Short-interest and fundamentals signal studies on synthetic US_EQ panel', summary: `Dataset ${FIXTURE_DATASET_ID}, raw close-to-close returns, zero modeled costs, pre-Vault window ${fixture.firstDate}..${fixture.lastPreCutoffDate}.`, - trialRefs: [signalTrialRef], + trialRefs: [shortsTrialRef, fundamentalsTrialRef], evidenceRefs: [FIXTURE_DATASET_ID], idempotencyKey: 'copilot-e2e-finding-1', }, @@ -899,10 +1021,10 @@ describe('createResearchCopilotMcpServer', () => { const rawOut = sink.text(); expect(rawOut.endsWith('\n')).toBe(true); - expect(sink.lines).toHaveLength(8); + expect(sink.lines).toHaveLength(9); const responses = sink.lines.map(line => JSON.parse(line) as JsonRpcResponseEnvelope); - expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); for (const resp of responses) { expect(resp.error).toBeUndefined(); } @@ -933,16 +1055,34 @@ describe('createResearchCopilotMcpServer', () => { expect(queryPayload.truncated).toBe(true); expect(queryPayload.rows.every(r => r.ts < fixture.vaultCutoffTs)).toBe(true); - // 5. analyze_signal - const signalPayload = decodeToolJson(responses[4]!); - expect(signalPayload.status).toBe('ok'); - if (signalPayload.status !== 'ok') { - throw new Error('Expected analyze_signal status to be ok.'); + // 5. analyze_signal (shorts) + const shortsSignalPayload = decodeToolJson(responses[4]!); + expect(shortsSignalPayload.status).toBe('ok'); + if (shortsSignalPayload.status !== 'ok') { + throw new Error('Expected shorts analyze_signal status to be ok.'); } - expect(String(signalPayload.trial.trialId)).toBe(signalTrialRef); + expect(shortsSignalPayload.signal).toEqual({ source: 'shorts', field: 'net_change' }); + expect(String(shortsSignalPayload.trial.trialId)).toBe(shortsTrialRef); - // 6. event_study - const eventPayload = decodeToolJson(responses[5]!); + // 6. analyze_signal (fundamentals) + const fundamentalsSignalPayload = decodeToolJson(responses[5]!); + expect(fundamentalsSignalPayload.status).toBe('ok'); + if (fundamentalsSignalPayload.status !== 'ok') { + throw new Error('Expected fundamentals analyze_signal status to be ok.'); + } + expect(fundamentalsSignalPayload.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: false, + }); + expect(String(fundamentalsSignalPayload.trial.trialId)).toBe(fundamentalsTrialRef); + expect(fundamentalsSignalPayload.trial.expressionHash).not.toBe( + shortsSignalPayload.trial.expressionHash + ); + expect(storeHandle.getFundamentalsCalls()).toBeGreaterThan(0); + + // 7. event_study + const eventPayload = decodeToolJson(responses[6]!); expect(eventPayload.status).toBe('ok'); if (eventPayload.status !== 'ok') { throw new Error('Expected event_study status to be ok.'); @@ -950,27 +1090,29 @@ describe('createResearchCopilotMcpServer', () => { expect(eventPayload.benchmark).toBe('equal_weight'); expect(eventPayload.study.hasBenchmark).toBe(true); - // 7. read_knowledge - const knowledgePayload = decodeToolJson(responses[6]!); + // 8. read_knowledge + const knowledgePayload = decodeToolJson(responses[7]!); expect(knowledgePayload.rowCount).toBe(1); expect(knowledgePayload.rows[0]?.id).toBe('card-dsr-01'); - // 8. file_finding - const findingPayload = decodeToolJson(responses[7]!); + // 9. file_finding + const findingPayload = decodeToolJson(responses[8]!); expect(findingPayload).toEqual({ id: FIXED_FINDING_ID, createdAt: FIXED_NOW_ISO, created: true, }); - // Verify trial_ledger recorded both stages under AGENT_PRINCIPAL and matches responses. - expect(ledger.rows).toHaveLength(2); - expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'event_study']); + // Verify trial_ledger recorded both signal_ic trials (distinct hashes) and event_study under AGENT_PRINCIPAL. + expect(ledger.rows).toHaveLength(3); + expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']); expect(ledger.rows.every(r => r.principal_id === AGENT_PRINCIPAL)).toBe(true); - expect(ledger.rows[0]?.trial_id).toBe(String(signalPayload.trial.trialId)); - expect(ledger.rows[1]?.trial_id).toBe(String(eventPayload.trial.trialId)); + expect(ledger.rows[0]?.trial_id).toBe(String(shortsSignalPayload.trial.trialId)); + expect(ledger.rows[1]?.trial_id).toBe(String(fundamentalsSignalPayload.trial.trialId)); + expect(ledger.rows[2]?.trial_id).toBe(String(eventPayload.trial.trialId)); + expect(ledger.rows[0]?.expression_hash).not.toBe(ledger.rows[1]?.expression_hash); - // Verify FindingWritePort recorded exactly one pending_review finding referencing signal trial. + // Verify FindingWritePort recorded exactly one pending_review finding referencing both signal trials. expect(findings.appendCalls).toHaveLength(1); expect(findings.stored).toHaveLength(1); expect(findings.stored[0]).toMatchObject({ @@ -978,7 +1120,7 @@ describe('createResearchCopilotMcpServer', () => { createdAt: findingPayload.createdAt, kind: 'finding', status: 'pending_review', - trialRefs: [signalTrialRef], + trialRefs: [shortsTrialRef, fundamentalsTrialRef], evidenceRefs: [FIXTURE_DATASET_ID], }); });