T-143: M2.2c — tools/curate-etl: Zstd Parquet writer for fundamentals_pit/year=YYYY/part.parquet (flat latest-period + TTM snapshot rows from FundamentalsSnapshot<i32>) with restatement round-trip test (no new crates, no CLI/bench changes)

This commit is contained in:
Studio 2026-12-01 22:14:56 -05:00
commit 1a318f0773
10 changed files with 5355 additions and 2 deletions

View file

@ -217,9 +217,9 @@ Schemas:
- **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`.
- **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`.
- **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, <standardized statement columns...>)`.
- **`fundamentals_pit/year=YYYY/part.parquet`**: Wide pre-resolved point-in-time snapshots keyed by `(listing_id INT32, effective_known_at TIMESTAMPTZ)` where each row computes:
- **`fundamentals_pit/year=YYYY/part.parquet`**: Pre-resolved point-in-time snapshots partitioned by the UTC year of `effective_known_at`, sorted and unique by `(listing_id, effective_known_at)`: `(listing_id INT32 NOT NULL, effective_known_at TIMESTAMPTZ NOT NULL, known_at_source VARCHAR NOT NULL, has_estimated_lag BOOLEAN NOT NULL, period_end DATE NOT NULL, fiscal_period VARCHAR NOT NULL, currency VARCHAR NOT NULL, period_known_at TIMESTAMPTZ NOT NULL, revenue DOUBLE, net_income DOUBLE, operating_cash_flow DOUBLE, total_assets DOUBLE, total_equity DOUBLE, shares_outstanding DOUBLE, ttm_period_end DATE, ttm_currency VARCHAR, ttm_revenue DOUBLE, ttm_net_income DOUBLE, ttm_operating_cash_flow DOUBLE, ttm_has_estimated_lag BOOLEAN)` (all `ttm_*` columns are `NULL` when 4 consecutive standalone quarters in one currency are unavailable). Each snapshot computes:
$$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$
forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2.
forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2; the physical Parquet row flattens the latest visible resolved period (`periods[0]`) alongside the precomputed `ttm_*` columns (lagged slots `periods[1..]` are omitted).
- **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`.
- **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`.
- **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`.

View file

@ -224,6 +224,10 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
- **Review status & Vault safety:** Server-controlled metadata (`id`, UTC ISO `createdAt`, and initial `status: 'pending_review'`) cannot be supplied by callers; director approval occurs out-of-band. Every unique `trialRef` is verified via the injected read-only `trialLookup.hasResearchVisibleTrial(ref)` before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only in `title` and `summary` and keep Vault holdout observations out of filing text.
- **Idempotency & receipts:** `FindingWritePort` exposes only `appendFinding(record, idempotencyKey?)` with atomic `created` / `replayed` / `conflict` semantics comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs`. Retries with the same key and normalized payload return the original `{ id, createdAt, created: false }` without appending; key reuse with a different payload returns a fixed `isError: true` conflict error with zero writes; unkeyed calls are independent. Filed records extend `FindingRecord` and can be read back by receipt ID via `read_knowledge`.
### Copilot Server
- **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions.
### Remaining M2 MCP Items (Later Tasks)
- SSE/HTTP transport wrapper in `apps/stock/web-api`.

View file

@ -0,0 +1,110 @@
import { type McpServer, type McpServerOptions, createMcpServer } from './server';
import { type AnalyzeSignalToolOptions, createAnalyzeSignalTool } from './tools/analyze-signal';
import { type EventStudyToolOptions, createEventStudyTool } from './tools/event-study';
import { type FileFindingToolOptions, createFileFindingTool } from './tools/file-finding';
import { type QueryDataToolOptions, createQueryDataTool } from './tools/query-data';
import { type ReadKnowledgeToolOptions, createReadKnowledgeTool } from './tools/read-knowledge';
import { type SearchSymbolsToolOptions, createSearchSymbolsTool } from './tools/search-symbols';
/**
* Fixed, documented registration order of the six MCP tools exposed by
* {@link createResearchCopilotMcpServer}.
*/
export const RESEARCH_COPILOT_TOOL_NAMES = Object.freeze([
'search_symbols',
'query_data',
'analyze_signal',
'event_study',
'file_finding',
'read_knowledge',
] as const);
/**
* Composed server options for {@link createResearchCopilotMcpServer}.
*
* Shares the common Vault-fenced `MarketDataStore`, `vaultContext`,
* `TrialLedgerExecutor`, and `principalId` across the tools that consume them
* while passing each tool's remaining injected ports unchanged.
*/
export interface ResearchCopilotMcpServerOptions
extends Pick<McpServerOptions, 'name' | 'version'>,
Pick<QueryDataToolOptions, 'store' | 'vaultContext'>,
Pick<AnalyzeSignalToolOptions, 'ledger' | 'principalId'> {
readonly searchSymbols: Omit<SearchSymbolsToolOptions, 'vaultContext'>;
readonly eventStudy: Pick<EventStudyToolOptions, 'resolveExchangeCalendars'>;
readonly fileFinding: FileFindingToolOptions;
readonly readKnowledge: ReadKnowledgeToolOptions;
}
/**
* Composes all six research MCP tools (`search_symbols`, `query_data`,
* `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`) into a
* single transport-agnostic {@link McpServer}.
*
* Keeps the shared `store`, `vaultContext`, `ledger`, and `principalId`
* authoritative across tools and fails closed if any tool is duplicated,
* missing, unexpected, or out of order.
*/
export function createResearchCopilotMcpServer(
options: ResearchCopilotMcpServerOptions
): McpServer {
if (typeof options !== 'object' || options === null) {
throw new Error('Invalid `options`: expected a ResearchCopilotMcpServerOptions object.');
}
if (typeof options.searchSymbols !== 'object' || options.searchSymbols === null) {
throw new Error('Invalid `searchSymbols`: expected a SearchSymbolsToolOptions object.');
}
if (typeof options.eventStudy !== 'object' || options.eventStudy === null) {
throw new Error('Invalid `eventStudy`: expected an EventStudyToolOptions object.');
}
const tools = [
createSearchSymbolsTool({
...options.searchSymbols,
vaultContext: options.vaultContext,
}),
createQueryDataTool({
store: options.store,
vaultContext: options.vaultContext,
}),
createAnalyzeSignalTool({
store: options.store,
ledger: options.ledger,
vaultContext: options.vaultContext,
principalId: options.principalId,
}),
createEventStudyTool({
store: options.store,
ledger: options.ledger,
vaultContext: options.vaultContext,
principalId: options.principalId,
resolveExchangeCalendars: options.eventStudy.resolveExchangeCalendars,
}),
createFileFindingTool(options.fileFinding),
createReadKnowledgeTool(options.readKnowledge),
];
const server = createMcpServer({
name: options.name,
version: options.version,
tools,
});
const registered = server.listTools();
if (registered.length !== RESEARCH_COPILOT_TOOL_NAMES.length) {
throw new Error(
`Research copilot MCP server expected ${RESEARCH_COPILOT_TOOL_NAMES.length} tools, got ${registered.length}.`
);
}
for (let i = 0; i < RESEARCH_COPILOT_TOOL_NAMES.length; i += 1) {
const expectedName = RESEARCH_COPILOT_TOOL_NAMES[i];
const actualName = registered[i]?.name;
if (actualName !== expectedName) {
throw new Error(
`Research copilot MCP server tool mismatch at index ${i}: expected "${expectedName}", got "${String(actualName)}".`
);
}
}
return server;
}

View file

@ -1,3 +1,4 @@
export * from './copilot-server';
export * from './protocol';
export * from './server';
export * from './stdio';

View file

@ -0,0 +1,740 @@
import { describe, expect, spyOn, test } from 'bun:test';
import type { EventStudyExchangeCalendars } from '../src/event-panel';
import type {
BarBatch,
BarRecord,
BarsQuery,
EventsQuery,
MarketDataStore,
ShortsAsOfQuery,
Table,
TableRow,
} from '../src/market-data-store';
import { EVENTS_COLUMNS, MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb';
import {
type AnalyzeSignalResultPayload,
type EventStudyResultPayload,
type FileFindingResultPayload,
type FiledFindingRecord,
type FindingWritePort,
type KnowledgePort,
type McpServer,
RESEARCH_COPILOT_TOOL_NAMES,
type ReadKnowledgeResultPayload,
type ResearchCopilotMcpServerOptions,
type SearchSymbolsResultPayload,
type StdioOutput,
areFiledFindingPayloadsEqual,
createResearchCopilotMcpServer,
runStdioServer,
} from '../src/mcp/index';
import * as analyzeSignalToolModule from '../src/mcp/tools/analyze-signal';
import * as queryDataToolModule from '../src/mcp/tools/query-data';
import type { TrialLedgerExecutor } from '../src/trial-ledger';
// QA fixture for T-144 (composed research copilot MCP server), pinned for reproducibility:
// - Dataset ID: `synthetic:mcp-copilot-qa:seed-424242:v1` (Mulberry32 seed 424242)
// - Universe: 12 synthetic XNYS listings (`60001..60012`), daily bars at 21:00 UTC
// - Sessions: 60 pre-cutoff + 6 post-cutoff weekdays starting 2023-01-02;
// vault cutoff = 00:00 UTC on session index 60
// - Shorts reported every 5 sessions (indices 0,5,...), known_at = 22:00 UTC on report+3,
// so the first actionable signal session is index 4 (first close strictly after known_at)
// - Study assumptions: raw close-to-close returns, zero modeled costs, 5-session horizon,
// event_study equal-weight benchmark on 8-K filings
const FIXTURE_DATASET_ID = 'synthetic:mcp-copilot-qa:seed-424242:v1';
const SEED = 424242;
const LISTING_COUNT = 12;
const PRE_CUTOFF_SESSIONS = 60;
const POST_CUTOFF_SESSIONS = 6;
const HORIZON = 5;
const AGENT_PRINCIPAL = 'agent:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
const FIXED_NOW_MS = Date.parse('2024-07-01T09:00:00.000Z');
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[] = [];
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): number {
return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`);
}
/** Parses store bound strings (date-only, ms or µs ISO) to epoch ms, truncating sub-ms digits. */
function boundMs(raw: string, endOfDay: boolean): number {
if (raw.length === 10) {
return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`);
}
const m = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z$/.exec(raw);
if (m === null) {
throw new Error(`Unparseable bound: ${raw}`);
}
const frac = (m[2] ?? '').padEnd(3, '0').slice(0, 3);
return Date.parse(`${m[1]}.${frac}Z`);
}
interface Fixture {
readonly listingIds: readonly number[];
readonly dates: readonly string[];
readonly cutoffDate: string;
readonly cutoffTs: number;
readonly lastPreDate: string;
readonly lastDate: string;
readonly bars: readonly BarRecord[];
readonly shorts: Table;
readonly events: Table;
readonly calendars: EventStudyExchangeCalendars;
}
function buildFixture(): Fixture {
const rand = createSeededRng(SEED);
const dates = makeBusinessDates('2023-01-02', PRE_CUTOFF_SESSIONS + POST_CUTOFF_SESSIONS);
const listingIds = Array.from({ length: LISTING_COUNT }, (_, i) => 60_001 + i);
const cutoffDate = dates[PRE_CUTOFF_SESSIONS]!;
const bars: BarRecord[] = [];
const shortsRows: TableRow[] = [];
const eventRows: TableRow[] = [];
const eventDays = [10, 18, 26, 34, 42, 50, 62];
const eventKey = new Set<string>();
eventDays.forEach((t, e) => {
const ts = utcMs(dates[t]!, 14);
for (let k = 0; k < 2; k += 1) {
const l = (e * 2 + k) % LISTING_COUNT;
eventKey.add(`${t}:${l}`);
eventRows.push({
listing_id: listingIds[l]!,
ts,
known_at: ts,
known_at_source: 'exact',
kind: 'filing',
subtype: '8-K',
payload_json: '{}',
});
}
});
const prices = listingIds.map((_, l) => 20 + l * 3);
for (let t = 0; t < dates.length; t += 1) {
const date = dates[t]!;
if (t % 5 === 0 && t + 3 < dates.length) {
for (let l = 0; l < LISTING_COUNT; l += 1) {
shortsRows.push({
listing_id: listingIds[l]!,
report_date: date,
known_at: utcMs(dates[t + 3]!, 22),
shares_short: 200_000 + l * 1_000 + Math.round(rand() * 5_000),
net_change: Math.round((rand() * 2 - 1) * 15_000),
pct_float: Number((0.01 + rand() * 0.05).toFixed(4)),
source: 'ceoShorts',
});
}
}
const closeTs = utcMs(date, 21);
for (let l = 0; l < LISTING_COUNT; l += 1) {
const drift = eventKey.has(`${t}:${l}`) || eventKey.has(`${t - 1}:${l}`) ? 0.008 : 0;
prices[l] = Math.max(1, prices[l]! * (1 + drift + (rand() * 2 - 1) * 0.01));
const close = Number(prices[l]!.toFixed(4));
bars.push({
listingId: listingIds[l]!,
ts: closeTs,
open: close,
high: close,
low: close,
close,
volume: 10_000 + t,
vwap: close,
knownAt: closeTs,
});
}
}
return {
listingIds,
dates,
cutoffDate,
cutoffTs: utcMs(cutoffDate, 0),
lastPreDate: dates[PRE_CUTOFF_SESSIONS - 1]!,
lastDate: dates[dates.length - 1]!,
bars,
shorts: {
columns: [
'listing_id',
'report_date',
'known_at',
'shares_short',
'net_change',
'pct_float',
'source',
],
rows: shortsRows,
},
events: { columns: [...EVENTS_COLUMNS], rows: eventRows },
calendars: {
calendars: { XNYS: dates.map(date => ({ date, closeTs: utcMs(date, 21) })) },
listingCalendarId: new Map(listingIds.map(id => [id, 'XNYS'])),
},
};
}
interface RecordingStore {
readonly store: MarketDataStore;
readonly barsQueries: BarsQuery[];
readonly shortsQueries: ShortsAsOfQuery[];
readonly eventsQueries: EventsQuery[];
}
/** Honest in-memory store that records every query it receives. */
function createRecordingStore(fx: Fixture): RecordingStore {
const barsQueries: BarsQuery[] = [];
const shortsQueries: ShortsAsOfQuery[] = [];
const eventsQueries: EventsQuery[] = [];
const store: MarketDataStore = {
bars(q): AsyncIterable<BarBatch> {
barsQueries.push(q);
const ids = new Set(q.listingIds);
const from = boundMs(q.from, false);
const to = boundMs(q.to, true);
const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY;
const rows = fx.bars.filter(
r => ids.has(r.listingId) && r.ts >= from && r.ts <= to && r.knownAt <= asOf
);
return {
async *[Symbol.asyncIterator]() {
yield { rows };
},
};
},
async universe() {
return [...fx.listingIds];
},
async shortsAsOf(q) {
shortsQueries.push(q);
const ids = new Set(q.listingIds);
const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY;
const from = q.from.slice(0, 10);
const to = q.to.slice(0, 10);
return {
columns: fx.shorts.columns,
rows: fx.shorts.rows.filter(
r =>
ids.has(r.listing_id as number) &&
(r.report_date as string) >= from &&
(r.report_date as string) <= to &&
(r.known_at as number) <= asOf
),
};
},
async events(q) {
eventsQueries.push(q);
const ids = q.listingIds !== undefined ? new Set(q.listingIds) : null;
const from = boundMs(q.from, false);
const to = boundMs(q.to, true);
const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY;
return {
columns: fx.events.columns,
rows: fx.events.rows.filter(
r =>
(ids === null || ids.has(r.listing_id as number)) &&
q.kinds.includes(r.kind as never) &&
(r.ts as number) >= from &&
(r.ts as number) <= to &&
(r.known_at as number) <= asOf
),
};
},
async crossSection() {
throw new MarketDataStoreNotImplementedError('crossSection');
},
async fundamentalsAsOf() {
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
},
async macroAsOf() {
throw new MarketDataStoreNotImplementedError('macroAsOf');
},
async fx() {
throw new MarketDataStoreNotImplementedError('fx');
},
};
return { store, barsQueries, shortsQueries, eventsQueries };
}
interface LedgerRow {
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 createLedger(): { readonly executor: TrialLedgerExecutor; readonly rows: LedgerRow[] } {
const rows: LedgerRow[] = [];
const executor: TrialLedgerExecutor = {
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
const p = params ?? [];
if (text.trimStart().startsWith('INSERT INTO trial_ledger')) {
const id = rows.length + 1;
const row: LedgerRow = {
trial_id: String(id),
created_at: new Date(Date.UTC(2024, 6, 1, 0, 0, id)),
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: (p[13] as readonly number[]).map(v => Math.fround(v)),
};
rows.push(row);
return {
rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row],
rowCount: 1,
};
}
if (text.includes('WHERE trial_id = $1::bigint')) {
const m = rows.filter(r => r.trial_id === String(p[0]));
return { rows: m as unknown as Row[], rowCount: m.length };
}
if (text.includes('WHERE universe_market = $1')) {
const m = rows.filter(r => r.universe_market === p[0] && r.horizon_bucket === p[1]);
return { rows: m as unknown as Row[], rowCount: m.length };
}
return { rows: [], rowCount: 0 };
},
};
return { executor, rows };
}
interface Harness {
readonly options: ResearchCopilotMcpServerOptions;
readonly store: RecordingStore;
readonly ledger: ReturnType<typeof createLedger>;
readonly stored: FiledFindingRecord[];
readonly appendCalls: () => number;
}
function buildHarness(fx: Fixture): Harness {
const store = createRecordingStore(fx);
const ledger = createLedger();
const stored: FiledFindingRecord[] = [];
const byKey = new Map<string, FiledFindingRecord>();
let appends = 0;
let nextFinding = 1;
const writePort: FindingWritePort = {
async appendFinding(record, key) {
appends += 1;
if (key !== undefined) {
const prior = byKey.get(key);
if (prior !== undefined) {
return areFiledFindingPayloadsEqual(prior, record)
? { status: 'replayed', id: prior.id, createdAt: prior.createdAt }
: { status: 'conflict' };
}
}
const copy = { ...record, trialRefs: [...record.trialRefs], evidenceRefs: [...record.evidenceRefs] };
stored.push(copy);
if (key !== undefined) {
byKey.set(key, copy);
}
return { status: 'created', id: copy.id, createdAt: copy.createdAt };
},
};
const knowledge: KnowledgePort = {
async listLibraryCards() {
return [];
},
async listFindings() {
return stored;
},
async listProviderCaveats() {
return [];
},
};
const options: ResearchCopilotMcpServerOptions = {
name: 'copilot-qa',
version: '0.0.1',
store: store.store,
vaultContext: { vaultCutoffTs: fx.cutoffTs },
ledger: ledger.executor,
principalId: AGENT_PRINCIPAL,
searchSymbols: {
port: {
async searchSymbols() {
return fx.listingIds.map((listingId, i) => ({
listingId,
instrumentId: 90_000 + i,
ticker: i === 0 ? 'QAQA' : `QA${i}`,
classSuffix: null,
name: `QA Equity ${i}`,
mic: 'XNYS',
currency: 'USD',
isin: null,
firstBarDate: fx.dates[0]!,
lastBarDate: fx.lastDate,
delistedAt: null,
}));
},
},
},
eventStudy: { resolveExchangeCalendars: () => fx.calendars },
fileFinding: {
port: writePort,
trialLookup: {
hasResearchVisibleTrial: ref =>
ledger.rows.some(r => r.trial_id === ref && r.sample_end < fx.cutoffDate),
},
newId: () => `finding-qa-${nextFinding++}`,
now: () => FIXED_NOW_MS,
},
readKnowledge: { port: knowledge },
};
return { options, store, ledger, stored, appendCalls: () => appends };
}
interface ToolEnvelope {
readonly content: readonly { readonly text: string }[];
readonly isError?: boolean;
}
async function callTool(
server: McpServer,
name: string,
args: Record<string, unknown>
): Promise<ToolEnvelope> {
const raw = await server.handleMessage(
JSON.stringify({ jsonrpc: '2.0', id: name, method: 'tools/call', params: { name, arguments: args } })
);
const parsed = JSON.parse(raw!) as { result?: ToolEnvelope; error?: unknown };
expect(parsed.error).toBeUndefined();
return parsed.result!;
}
function okJson<T>(env: ToolEnvelope): T {
expect(env.isError).not.toBe(true);
return JSON.parse(env.content[0]!.text) as T;
}
function signalArgs(fx: Fixture, overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
listingIds: [...fx.listingIds],
from: fx.dates[0]!,
to: fx.lastPreDate,
signal: { source: 'shorts', field: 'net_change' },
horizonSessions: HORIZON,
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
adjustment: 'raw',
...overrides,
};
}
function eventArgs(fx: Fixture, overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
listingIds: [...fx.listingIds],
from: fx.dates[0]!,
to: fx.lastPreDate,
event: { kinds: ['filing'], subtypes: ['8-K'] },
preDays: 2,
postDays: 5,
benchmark: 'equal_weight',
adjustment: 'raw',
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
...overrides,
};
}
describe('createResearchCopilotMcpServer QA', () => {
test('straddling query_data, analyze_signal and event_study send only clamped pre-cutoff bounds to the store', async () => {
const fx = buildFixture();
const h = buildHarness(fx);
const server = createResearchCopilotMcpServer(h.options);
await callTool(server, 'query_data', {
listingIds: [fx.listingIds[0]!],
from: fx.dates[0]!,
to: fx.lastDate,
asOf: fx.lastDate,
timeframe: '1d',
adjustment: 'raw',
});
const sig = okJson<AnalyzeSignalResultPayload>(
await callTool(server, 'analyze_signal', signalArgs(fx, { to: fx.lastDate, asOf: fx.lastDate }))
);
const ev = okJson<EventStudyResultPayload>(
await callTool(server, 'event_study', eventArgs(fx, { to: fx.lastDate, asOf: fx.lastDate }))
);
expect(sig.status).toBe('ok');
expect(ev.status).toBe('ok');
expect(ev.clampedTo).toBe(true);
expect(ev.toMs).toBe(fx.cutoffTs - 1);
// query_data + analyze_signal + event_study each read bars once.
expect(h.store.barsQueries).toHaveLength(3);
expect(h.store.shortsQueries).toHaveLength(1);
expect(h.store.eventsQueries).toHaveLength(1);
const all: { readonly to: string; readonly asOf?: string }[] = [
...h.store.barsQueries,
...h.store.shortsQueries,
...h.store.eventsQueries,
];
for (const q of all) {
expect(q.to.startsWith(new Date(fx.cutoffTs - 1).toISOString().slice(0, 19))).toBe(true);
expect(boundMs(q.to, true)).toBe(fx.cutoffTs - 1);
expect(q.asOf).toBeDefined();
expect(boundMs(q.asOf!, true)).toBe(fx.cutoffTs - 1);
}
for (const q of h.store.barsQueries) {
expect(q.scope).toBe('vault_fenced');
}
// Event-study trial stays pre-cutoff too.
expect(h.ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'event_study']);
for (const row of h.ledger.rows) {
expect(row.sample_end < fx.cutoffDate).toBe(true);
}
});
test('analyze_signal trial covers the exact pinned formation window (first actionable session through cutoff minus horizon)', async () => {
const fx = buildFixture();
const h = buildHarness(fx);
const server = createResearchCopilotMcpServer(h.options);
const sig = okJson<AnalyzeSignalResultPayload>(
await callTool(server, 'analyze_signal', signalArgs(fx, { to: fx.lastDate }))
);
expect(sig.status).toBe('ok');
if (sig.status !== 'ok') {
throw new Error('expected ok');
}
// First report (index 0) becomes known 22:00 UTC on index 3, after that day's 21:00 close,
// so the first eligible formation session is index 4. The last formation session whose
// 5-session forward endpoint is still pre-cutoff is index 59 - 5 = 54.
const expectedStart = fx.dates[4]!;
const expectedEnd = fx.dates[PRE_CUTOFF_SESSIONS - 1 - HORIZON]!;
expect(fx.dates[PRE_CUTOFF_SESSIONS - 1 - HORIZON + HORIZON]).toBe(fx.lastPreDate);
expect(h.ledger.rows).toHaveLength(1);
const row = h.ledger.rows[0]!;
expect(row.trial_id).toBe(String(sig.trial.trialId));
expect(row.principal_id).toBe(AGENT_PRINCIPAL);
expect(row.sample_start).toBe(expectedStart);
expect(row.sample_end).toBe(expectedEnd);
// One daily IC observation per formation session, none dropped.
expect(row.daily_series).toHaveLength(PRE_CUTOFF_SESSIONS - HORIZON - 4);
expect(row.n_obs).toBe(row.daily_series.length);
});
test('a replay on fresh servers with the same inputs produces an identical stdio transcript and ledger', async () => {
const fx = buildFixture();
async function runSession(): Promise<{ readonly lines: string[]; readonly ledger: LedgerRow[] }> {
const h = buildHarness(fx);
const server = createResearchCopilotMcpServer(h.options);
const lines: string[] = [];
let buf = '';
const output: StdioOutput = {
write(chunk: string) {
buf += chunk;
let i = buf.indexOf('\n');
while (i !== -1) {
lines.push(buf.slice(0, i));
buf = buf.slice(i + 1);
i = buf.indexOf('\n');
}
return true;
},
};
async function* input(): AsyncGenerator<string> {
const calls: [string, Record<string, unknown>][] = [
['analyze_signal', signalArgs(fx)],
['event_study', eventArgs(fx)],
];
let id = 1;
for (const [name, args] of calls) {
yield `${JSON.stringify({ jsonrpc: '2.0', id: id++, method: 'tools/call', params: { name, arguments: args } })}\n`;
}
yield `${JSON.stringify({
jsonrpc: '2.0',
id: id++,
method: 'tools/call',
params: {
name: 'file_finding',
arguments: {
kind: 'finding',
title: 'Replay finding',
summary: `Dataset ${FIXTURE_DATASET_ID}, pre-Vault only.`,
trialRefs: ['1'],
evidenceRefs: [FIXTURE_DATASET_ID],
},
},
})}\n`;
}
await runStdioServer(server, { input: input(), output });
return { lines, ledger: h.ledger.rows };
}
const a = await runSession();
const b = await runSession();
expect(a.lines).toHaveLength(3);
expect(b.lines).toEqual(a.lines);
expect(b.ledger).toEqual(a.ledger);
expect(JSON.parse(a.lines[2]!).result.isError).not.toBe(true);
});
test('file_finding through the composed server rejects unknown trial refs, replays idempotent retries, and read_knowledge reads the filed record back', async () => {
const fx = buildFixture();
const h = buildHarness(fx);
const server = createResearchCopilotMcpServer(h.options);
const unknown = await callTool(server, 'file_finding', {
kind: 'finding',
title: 'No trial yet',
summary: 'Should be rejected.',
trialRefs: ['999'],
});
expect(unknown.isError).toBe(true);
expect(h.appendCalls()).toBe(0);
const sig = okJson<AnalyzeSignalResultPayload>(await callTool(server, 'analyze_signal', signalArgs(fx)));
if (sig.status !== 'ok') {
throw new Error('expected ok');
}
const args = {
kind: 'finding',
title: 'Shorts net_change IC',
summary: `Dataset ${FIXTURE_DATASET_ID}.`,
trialRefs: [String(sig.trial.trialId)],
evidenceRefs: [FIXTURE_DATASET_ID],
idempotencyKey: 'qa-key-1',
};
const first = okJson<FileFindingResultPayload>(await callTool(server, 'file_finding', args));
const retry = okJson<FileFindingResultPayload>(await callTool(server, 'file_finding', args));
expect(first.created).toBe(true);
expect(retry).toEqual({ id: first.id, createdAt: first.createdAt, created: false });
expect(h.stored).toHaveLength(1);
const conflict = await callTool(server, 'file_finding', { ...args, title: 'Different title' });
expect(conflict.isError).toBe(true);
expect(h.stored).toHaveLength(1);
const read = okJson<ReadKnowledgeResultPayload>(
await callTool(server, 'read_knowledge', { source: 'findings', id: first.id })
);
expect(read.rowCount).toBe(1);
expect(read.rows[0]?.id).toBe(first.id);
});
test('shared vaultContext and store stay authoritative over stray per-tool overrides', async () => {
const fx = buildFixture();
const h = buildHarness(fx);
const throwingStore = new Proxy(
{},
{
get() {
throw new Error('per-tool store override must not be used');
},
}
);
const options = {
...h.options,
// Runtime callers can bypass the Omit/Pick types; the composed server must ignore these.
searchSymbols: {
...h.options.searchSymbols,
vaultContext: { vaultCutoffTs: utcMs(fx.lastDate, 23) + 86_400_000 },
},
eventStudy: { ...h.options.eventStudy, store: throwingStore, vaultContext: { vaultCutoffTs: 8.64e15 } },
} as unknown as ResearchCopilotMcpServerOptions;
const server = createResearchCopilotMcpServer(options);
const search = okJson<SearchSymbolsResultPayload>(
await callTool(server, 'search_symbols', { query: 'QAQA', limit: 5 })
);
expect(search.rows[0]?.lastBarDate).toBe(fx.cutoffDate);
const ev = okJson<EventStudyResultPayload>(
await callTool(server, 'event_study', eventArgs(fx, { to: fx.lastDate }))
);
expect(ev.status).toBe('ok');
expect(ev.toMs).toBe(fx.cutoffTs - 1);
expect(h.store.eventsQueries).toHaveLength(1);
});
test('rejects invalid option objects and out-of-order tool registration', () => {
const fx = buildFixture();
const h = buildHarness(fx);
expect(() => createResearchCopilotMcpServer(null as never)).toThrow(/Invalid `options`/);
expect(() =>
createResearchCopilotMcpServer({ ...h.options, searchSymbols: null } as never)
).toThrow(/Invalid `searchSymbols`/);
expect(() =>
createResearchCopilotMcpServer({ ...h.options, eventStudy: undefined } as never)
).toThrow(/Invalid `eventStudy`/);
const realQuery = queryDataToolModule.createQueryDataTool(h.options);
const realSignal = analyzeSignalToolModule.createAnalyzeSignalTool(h.options);
const qSpy = spyOn(queryDataToolModule, 'createQueryDataTool').mockImplementation(() => realSignal);
const sSpy = spyOn(analyzeSignalToolModule, 'createAnalyzeSignalTool').mockImplementation(
() => realQuery
);
try {
expect(() => createResearchCopilotMcpServer(h.options)).toThrow(
/index 1: expected "query_data", got "analyze_signal"/
);
} finally {
qSpy.mockRestore();
sSpy.mockRestore();
}
// Restored spies: composition succeeds again with the fixed order.
const server = createResearchCopilotMcpServer(h.options);
expect(server.listTools().map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]);
});
test('is importable through the @stock-bot/research/mcp package subpath', async () => {
const mod = await import('@stock-bot/research/mcp');
expect(mod.createResearchCopilotMcpServer).toBe(createResearchCopilotMcpServer);
expect(mod.RESEARCH_COPILOT_TOOL_NAMES).toBe(RESEARCH_COPILOT_TOOL_NAMES);
});
});

File diff suppressed because it is too large Load diff

View file

@ -24,6 +24,7 @@ pub mod parquet_adj;
pub mod parquet_bars;
pub mod parquet_corporate_actions;
pub mod parquet_events;
pub mod parquet_fundamentals;
pub mod parquet_fx;
mod parquet_publish;
pub mod parquet_shorts;
@ -160,6 +161,11 @@ pub use parquet_events::{
events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions,
EventsWriteStats, ParquetEventsError,
};
pub use parquet_fundamentals::{
fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitLatestPeriod,
FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats,
ParquetFundamentalsError,
};
pub use parquet_fx::{
fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats,
ParquetFxError,

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -363,6 +363,25 @@ fn next_column<'a>(
}
}
pub(crate) fn write_bool_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
values: &[bool],
def_levels: Option<&[i16]>,
) -> Result<(), ParquetError> {
let mut col = next_column(rg_writer)?;
match col.untyped() {
ColumnWriter::BoolColumnWriter(typed) => {
typed.write_batch(values, def_levels, None)?;
}
_ => {
return Err(ParquetError::General(
"expected BOOLEAN column writer".to_string(),
));
}
}
col.close()
}
pub(crate) fn write_i32_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
values: &[i32],