T-149: M2.1h — MCP copilot analyze_signal: add a Vault-fenced fundamentals signal source (point-in-time fundamentalsAsOf month-end snapshots → SignalObservations) + extend the headless stdio end-to-end test to run a fundamental AND a shorts study (pure, injected ports, no new deps)
This commit is contained in:
parent
5527cebc21
commit
ee6137c770
3 changed files with 1554 additions and 87 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -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<string>();
|
||||
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<Table> {
|
||||
fundamentalsCalls += 1;
|
||||
const idSet = new Set(q.listingIds);
|
||||
const asOfMs = parseBoundMs(q.asOf, true);
|
||||
const allowEstimatedLag = q.allowEstimatedLag ?? false;
|
||||
const latestByListing = new Map<number, TableRow>();
|
||||
|
||||
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<string> {
|
||||
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<AnalyzeSignalResultPayload>(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<AnalyzeSignalResultPayload>(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<AnalyzeSignalResultPayload>(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<AnalyzeSignalResultPayload>(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<AnalyzeSignalResultPayload>(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<EventStudyResultPayload>(responses[5]!);
|
||||
// 6. analyze_signal (fundamentals)
|
||||
const fundamentalsSignalPayload = decodeToolJson<AnalyzeSignalResultPayload>(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<EventStudyResultPayload>(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<ReadKnowledgeResultPayload>(responses[6]!);
|
||||
// 8. read_knowledge
|
||||
const knowledgePayload = decodeToolJson<ReadKnowledgeResultPayload>(responses[7]!);
|
||||
expect(knowledgePayload.rowCount).toBe(1);
|
||||
expect(knowledgePayload.rows[0]?.id).toBe('card-dsr-01');
|
||||
|
||||
// 8. file_finding
|
||||
const findingPayload = decodeToolJson<FileFindingResultPayload>(responses[7]!);
|
||||
// 9. file_finding
|
||||
const findingPayload = decodeToolJson<FileFindingResultPayload>(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],
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue