1595 lines
59 KiB
TypeScript
1595 lines
59 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import {
|
|
type BarBatch,
|
|
type BarRecord,
|
|
type MarketDataStore,
|
|
MarketDataStoreValidationError,
|
|
type Table,
|
|
type TableRow,
|
|
VaultScopeNotAuthorizedError,
|
|
} from '../src/market-data-store';
|
|
import {
|
|
type BarsQuery,
|
|
MarketDataStoreNotImplementedError,
|
|
type ShortsAsOfQuery,
|
|
type UniverseQuery,
|
|
} from '../src/market-data-store-duckdb';
|
|
import {
|
|
ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS,
|
|
ANALYZE_SIGNAL_MAX_LISTING_IDS,
|
|
ANALYZE_SIGNAL_MAX_SERIES_POINTS,
|
|
type AnalyzeSignalResultPayload,
|
|
createAnalyzeSignalTool,
|
|
createMcpServer,
|
|
createQueryDataTool,
|
|
} from '../src/mcp/index';
|
|
import { buildForwardReturnPanel, shortsTableToSignalRows } from '../src/signal-panel';
|
|
import { analyzeSignal } from '../src/signal-study';
|
|
import type { TrialLedgerExecutor } from '../src/trial-ledger';
|
|
|
|
const SEED = 20261129;
|
|
const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
|
const CAMPAIGN_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
|
const HYPOTHESIS_UUID = '12345678-1234-4123-8123-123456789abc';
|
|
|
|
function createSeededRng(seed: number): () => number {
|
|
let state = seed >>> 0;
|
|
return () => {
|
|
state = (state + 0x6d2b79f5) >>> 0;
|
|
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
|
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
|
};
|
|
}
|
|
|
|
function makeBusinessDates(startDate: string, count: number): string[] {
|
|
const out: string[] = new Array(count);
|
|
const current = new Date(`${startDate}T00:00:00.000Z`);
|
|
let written = 0;
|
|
while (written < count) {
|
|
const day = current.getUTCDay();
|
|
if (day !== 0 && day !== 6) {
|
|
out[written] = current.toISOString().slice(0, 10);
|
|
written += 1;
|
|
}
|
|
current.setUTCDate(current.getUTCDate() + 1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function makeUtcMs(date: string, hourUtc: number): number {
|
|
const [y, m, d] = date.split('-').map(Number);
|
|
return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0);
|
|
}
|
|
|
|
interface StoredTrialRow {
|
|
readonly trial_id: string;
|
|
readonly created_at: Date;
|
|
readonly principal_id: string;
|
|
readonly campaign_id: string | null;
|
|
readonly stage: string;
|
|
readonly universe_market: string;
|
|
readonly horizon_bucket: string;
|
|
readonly hypothesis_id: string | null;
|
|
readonly expression_hash: string;
|
|
readonly sample_start: string;
|
|
readonly sample_end: string;
|
|
readonly n_obs: number;
|
|
readonly sharpe_unann: number;
|
|
readonly skewness: number;
|
|
readonly kurtosis: number;
|
|
readonly daily_series: readonly number[];
|
|
}
|
|
|
|
function createFakeTrialLedger(options?: {
|
|
insertError?: Error;
|
|
dsrReadError?: Error;
|
|
}): {
|
|
executor: TrialLedgerExecutor;
|
|
rows: StoredTrialRow[];
|
|
insertCalls: number;
|
|
selectCalls: number;
|
|
} {
|
|
const rows: StoredTrialRow[] = [];
|
|
let nextTrialId = 1;
|
|
const state = {
|
|
rows,
|
|
insertCalls: 0,
|
|
selectCalls: 0,
|
|
executor: null as unknown as TrialLedgerExecutor,
|
|
};
|
|
|
|
state.executor = {
|
|
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
|
const trimmed = text.trimStart();
|
|
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
|
state.insertCalls += 1;
|
|
if (options?.insertError !== undefined) {
|
|
throw options.insertError;
|
|
}
|
|
const p = params ?? [];
|
|
const trialId = nextTrialId++;
|
|
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId));
|
|
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
|
const stored: StoredTrialRow = {
|
|
trial_id: String(trialId),
|
|
created_at: createdAt,
|
|
principal_id: p[0] as string,
|
|
campaign_id: (p[1] as string | null) ?? null,
|
|
stage: p[2] as string,
|
|
universe_market: p[3] as string,
|
|
horizon_bucket: p[4] as string,
|
|
hypothesis_id: (p[5] as string | null) ?? null,
|
|
expression_hash: p[6] as string,
|
|
sample_start: p[7] as string,
|
|
sample_end: p[8] as string,
|
|
n_obs: p[9] as number,
|
|
sharpe_unann: p[10] as number,
|
|
skewness: p[11] as number,
|
|
kurtosis: p[12] as number,
|
|
daily_series: dailySeries,
|
|
};
|
|
rows.push(stored);
|
|
return {
|
|
rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row],
|
|
rowCount: 1,
|
|
};
|
|
}
|
|
|
|
if (trimmed.startsWith('SELECT')) {
|
|
state.selectCalls += 1;
|
|
if (options?.dsrReadError !== undefined) {
|
|
throw options.dsrReadError;
|
|
}
|
|
if (text.includes('WHERE trial_id = $1::bigint')) {
|
|
const targetId = String(params?.[0]);
|
|
const matched = rows.filter(r => r.trial_id === targetId);
|
|
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
|
}
|
|
if (text.includes('WHERE universe_market = $1')) {
|
|
const market = params?.[0] as string;
|
|
const bucket = params?.[1] as string;
|
|
const matched = rows.filter(
|
|
r => r.universe_market === market && r.horizon_bucket === bucket
|
|
);
|
|
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
|
}
|
|
}
|
|
|
|
return { rows: [], rowCount: 0 };
|
|
},
|
|
};
|
|
|
|
return state;
|
|
}
|
|
|
|
interface CeoShortsFixture {
|
|
readonly listingIds: number[];
|
|
readonly allDates: string[];
|
|
readonly vaultCutoffDate: string;
|
|
readonly vaultCutoffTs: number;
|
|
readonly bars: BarRecord[];
|
|
readonly shortsTable: Table;
|
|
}
|
|
|
|
const SHORTS_COLUMNS = [
|
|
'listing_id',
|
|
'report_date',
|
|
'known_at',
|
|
'shares_short',
|
|
'net_change',
|
|
'pct_float',
|
|
'source',
|
|
] as const;
|
|
|
|
function buildCeoShortsFixture(options?: {
|
|
preCutoffSessions?: number;
|
|
postCutoffSessions?: number;
|
|
listingCount?: number;
|
|
poisonPostCutoff?: boolean;
|
|
}): CeoShortsFixture {
|
|
const rand = createSeededRng(SEED);
|
|
const listingCount = options?.listingCount ?? 28;
|
|
const preCutoffSessions = options?.preCutoffSessions ?? 140;
|
|
const postCutoffSessions = options?.postCutoffSessions ?? 10;
|
|
const poisonPostCutoff = options?.poisonPostCutoff ?? false;
|
|
|
|
const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions);
|
|
const vaultCutoffDate = allDates[preCutoffSessions]!;
|
|
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
|
|
|
|
const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i);
|
|
const bars: BarRecord[] = [];
|
|
const shortsRows: TableRow[] = [];
|
|
|
|
const PUBLICATION_LAG_SESSIONS = 4;
|
|
const activeNetChange = new Float64Array(listingCount);
|
|
const pendingByPublishIdx = new Map<number, (number | null)[]>();
|
|
const prices = new Float64Array(listingCount);
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
prices[l] = 10 + l * 1.5;
|
|
}
|
|
|
|
for (let t = 0; t < allDates.length; t += 1) {
|
|
const date = allDates[t]!;
|
|
const closeTs = makeUtcMs(date, 21); // 16:00 ET close
|
|
|
|
const released = pendingByPublishIdx.get(t - 1);
|
|
if (released !== undefined) {
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
const v = released[l];
|
|
if (v !== null && v !== undefined) {
|
|
activeNetChange[l] = v / 20_000;
|
|
}
|
|
}
|
|
}
|
|
|
|
const publishIdx = t + PUBLICATION_LAG_SESSIONS;
|
|
if (t % 10 === 0 && publishIdx < allDates.length) {
|
|
const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+4
|
|
const pending: (number | null)[] = [];
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
const isNullCell = t > 0 && (t + l) % 19 === 0;
|
|
const netChange = isNullCell ? null : Math.round((rand() * 2 - 1) * 20_000);
|
|
pending.push(netChange);
|
|
shortsRows.push({
|
|
listing_id: listingIds[l]!,
|
|
report_date: date,
|
|
known_at: reportKnownAt,
|
|
shares_short: 100_000 + l * 5_000 + Math.round(rand() * 10_000),
|
|
net_change: netChange,
|
|
pct_float: isNullCell ? null : Number((0.02 + rand() * 0.08).toFixed(4)),
|
|
source: 'ceoShorts',
|
|
});
|
|
}
|
|
pendingByPublishIdx.set(publishIdx, pending);
|
|
}
|
|
|
|
for (let l = 0; l < listingCount; l += 1) {
|
|
const dailyRet = -0.004 * activeNetChange[l]! + (rand() * 2 - 1) * 0.008;
|
|
prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet));
|
|
const isPostCutoff = date >= vaultCutoffDate;
|
|
const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6));
|
|
bars.push({
|
|
listingId: listingIds[l]!,
|
|
ts: closeTs,
|
|
open: closeVal,
|
|
high: closeVal,
|
|
low: closeVal,
|
|
close: closeVal,
|
|
volume: 50_000,
|
|
vwap: closeVal,
|
|
knownAt: closeTs,
|
|
});
|
|
}
|
|
}
|
|
|
|
return {
|
|
listingIds,
|
|
allDates,
|
|
vaultCutoffDate,
|
|
vaultCutoffTs,
|
|
bars,
|
|
shortsTable: {
|
|
columns: SHORTS_COLUMNS,
|
|
rows: shortsRows,
|
|
},
|
|
};
|
|
}
|
|
|
|
interface FakeStoreState {
|
|
readonly barsCalls: BarsQuery[];
|
|
readonly shortsCalls: ShortsAsOfQuery[];
|
|
readonly universeCalls: UniverseQuery[];
|
|
readonly store: MarketDataStore;
|
|
}
|
|
|
|
function createFakeStore(options?: {
|
|
bars?: readonly BarRecord[];
|
|
shortsTable?: Table;
|
|
universeIds?: readonly number[];
|
|
universeResolver?: (q: UniverseQuery) => number[];
|
|
leaky?: boolean;
|
|
barsError?: Error;
|
|
shortsError?: Error;
|
|
universeError?: Error;
|
|
}): FakeStoreState {
|
|
const barsCalls: BarsQuery[] = [];
|
|
const shortsCalls: ShortsAsOfQuery[] = [];
|
|
const universeCalls: UniverseQuery[] = [];
|
|
|
|
const allBars = options?.bars ?? [];
|
|
const allShorts = options?.shortsTable ?? { columns: SHORTS_COLUMNS, rows: [] };
|
|
const leaky = options?.leaky ?? false;
|
|
|
|
const store: MarketDataStore = {
|
|
bars(q: BarsQuery): AsyncIterable<BarBatch> {
|
|
barsCalls.push(q);
|
|
if (options?.barsError !== undefined) {
|
|
const err = options.barsError;
|
|
return {
|
|
[Symbol.asyncIterator]() {
|
|
return {
|
|
next() {
|
|
return Promise.reject(err);
|
|
},
|
|
};
|
|
},
|
|
};
|
|
}
|
|
|
|
const idSet = new Set(q.listingIds);
|
|
const fromMs = Date.parse(q.from.length === 10 ? `${q.from}T00:00:00.000Z` : q.from);
|
|
const toMs = Date.parse(q.to.length === 10 ? `${q.to}T23:59:59.999Z` : q.to);
|
|
const asOfMs =
|
|
q.asOf !== undefined
|
|
? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf)
|
|
: Number.POSITIVE_INFINITY;
|
|
|
|
const filtered = leaky
|
|
? [...allBars]
|
|
: allBars.filter(
|
|
row =>
|
|
idSet.has(row.listingId) &&
|
|
row.ts >= fromMs &&
|
|
row.ts <= toMs &&
|
|
row.ts <= asOfMs &&
|
|
row.knownAt <= asOfMs
|
|
);
|
|
|
|
return {
|
|
async *[Symbol.asyncIterator]() {
|
|
yield { rows: filtered };
|
|
},
|
|
};
|
|
},
|
|
|
|
async shortsAsOf(q: ShortsAsOfQuery): Promise<Table> {
|
|
shortsCalls.push(q);
|
|
if (options?.shortsError !== undefined) {
|
|
throw options.shortsError;
|
|
}
|
|
|
|
if (leaky) {
|
|
return {
|
|
columns: allShorts.columns,
|
|
rows: [...allShorts.rows],
|
|
};
|
|
}
|
|
|
|
const idSet = new Set(q.listingIds);
|
|
const fromDate = q.from.slice(0, 10);
|
|
const toDate = q.to.slice(0, 10);
|
|
const asOfMs =
|
|
q.asOf !== undefined
|
|
? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf)
|
|
: Number.POSITIVE_INFINITY;
|
|
|
|
const rows = allShorts.rows.filter(row => {
|
|
const lid = row.listing_id as number;
|
|
const reportDate = row.report_date as string | undefined;
|
|
const knownAt = row.known_at as number;
|
|
const inDateRange =
|
|
reportDate === undefined || (reportDate >= fromDate && reportDate <= toDate);
|
|
return idSet.has(lid) && inDateRange && knownAt <= asOfMs;
|
|
});
|
|
|
|
return {
|
|
columns: allShorts.columns,
|
|
rows,
|
|
};
|
|
},
|
|
|
|
async universe(q: UniverseQuery): Promise<number[]> {
|
|
universeCalls.push(q);
|
|
if (options?.universeError !== undefined) {
|
|
throw options.universeError;
|
|
}
|
|
if (options?.universeResolver !== undefined) {
|
|
return options.universeResolver(q);
|
|
}
|
|
return [...(options?.universeIds ?? [])];
|
|
},
|
|
|
|
crossSection() {
|
|
throw new MarketDataStoreNotImplementedError('crossSection');
|
|
},
|
|
fundamentalsAsOf() {
|
|
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
|
},
|
|
events() {
|
|
throw new MarketDataStoreNotImplementedError('events');
|
|
},
|
|
macroAsOf() {
|
|
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
|
},
|
|
fx() {
|
|
throw new MarketDataStoreNotImplementedError('fx');
|
|
},
|
|
};
|
|
|
|
return { barsCalls, shortsCalls, universeCalls, store };
|
|
}
|
|
|
|
async function callAnalyzeSignal(params: {
|
|
store: MarketDataStore;
|
|
ledger: TrialLedgerExecutor;
|
|
vaultCutoffTs: number;
|
|
principalId?: string;
|
|
args: Record<string, unknown>;
|
|
}): Promise<{
|
|
rawResponse: string;
|
|
isError: boolean;
|
|
text: string;
|
|
}> {
|
|
const tool = createAnalyzeSignalTool({
|
|
store: params.store,
|
|
ledger: params.ledger,
|
|
vaultContext: { vaultCutoffTs: params.vaultCutoffTs },
|
|
principalId: params.principalId ?? AGENT_PRINCIPAL,
|
|
});
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [tool],
|
|
});
|
|
|
|
const rawResponse = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'as-1',
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'analyze_signal',
|
|
arguments: params.args,
|
|
},
|
|
})
|
|
);
|
|
|
|
expect(rawResponse).not.toBeNull();
|
|
const parsed = JSON.parse(rawResponse as string) as {
|
|
result: {
|
|
isError?: boolean;
|
|
content: { type: string; text: string }[];
|
|
};
|
|
};
|
|
return {
|
|
rawResponse: rawResponse as string,
|
|
isError: parsed.result.isError === true,
|
|
text: parsed.result.content[0]?.text ?? '',
|
|
};
|
|
}
|
|
|
|
describe('MCP analyze_signal tool', () => {
|
|
test('tools/list advertises query_data and analyze_signal and omits server-controlled fields from analyze_signal schema', async () => {
|
|
const fixture = buildCeoShortsFixture({ preCutoffSessions: 20, postCutoffSessions: 5, listingCount: 6 });
|
|
const fakeStore = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable });
|
|
const fakeLedger = createFakeTrialLedger();
|
|
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [
|
|
createQueryDataTool({
|
|
store: fakeStore.store,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
}),
|
|
createAnalyzeSignalTool({
|
|
store: fakeStore.store,
|
|
ledger: fakeLedger.executor,
|
|
vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'list-1',
|
|
method: 'tools/list',
|
|
})
|
|
);
|
|
|
|
const parsed = JSON.parse(raw as string) as {
|
|
result: {
|
|
tools: {
|
|
name: string;
|
|
description: string;
|
|
inputSchema: {
|
|
type: string;
|
|
properties: Record<string, { additionalProperties?: boolean; properties?: Record<string, unknown> }>;
|
|
required?: string[];
|
|
additionalProperties: boolean;
|
|
};
|
|
}[];
|
|
};
|
|
};
|
|
|
|
const names = parsed.result.tools.map(t => t.name);
|
|
expect(names).toEqual(['query_data', 'analyze_signal']);
|
|
|
|
const analyzeTool = parsed.result.tools.find(t => t.name === 'analyze_signal');
|
|
expect(analyzeTool).toBeDefined();
|
|
expect(analyzeTool?.inputSchema.type).toBe('object');
|
|
expect(analyzeTool?.inputSchema.additionalProperties).toBe(false);
|
|
expect(analyzeTool?.inputSchema.properties.signal?.additionalProperties).toBe(false);
|
|
|
|
const propKeys = Object.keys(analyzeTool?.inputSchema.properties ?? {});
|
|
expect(propKeys).toContain('listingIds');
|
|
expect(propKeys).toContain('universe');
|
|
expect(propKeys).toContain('from');
|
|
expect(propKeys).toContain('to');
|
|
expect(propKeys).toContain('signal');
|
|
expect(propKeys).toContain('horizonSessions');
|
|
expect(propKeys).toContain('universeMarket');
|
|
expect(propKeys).toContain('horizonBucket');
|
|
|
|
for (const forbidden of ['scope', 'vault_evaluation_only', 'principalId', 'vaultCutoffDate']) {
|
|
expect(propKeys).not.toContain(forbidden);
|
|
expect(analyzeTool?.inputSchema.required ?? []).not.toContain(forbidden);
|
|
}
|
|
});
|
|
|
|
test('executes seeded ceoShorts fixture with parity to direct analyzeSignal and writes exactly one trial row under injected principal', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const fakeStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
});
|
|
const mcpLedger = createFakeTrialLedger();
|
|
|
|
const from = fixture.allDates[0]!;
|
|
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
|
|
|
const res = await callAnalyzeSignal({
|
|
store: fakeStore.store,
|
|
ledger: mcpLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
principalId: AGENT_PRINCIPAL,
|
|
args: {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
campaignId: CAMPAIGN_UUID,
|
|
hypothesisId: HYPOTHESIS_UUID,
|
|
},
|
|
});
|
|
|
|
expect(res.isError).toBe(false);
|
|
const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload;
|
|
expect(payload.status).toBe('ok');
|
|
if (payload.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
// Run direct research pipeline on the same pre-cutoff bars/shorts with a fresh isolated ledger
|
|
const directLedger = createFakeTrialLedger();
|
|
const preCutoffBars = fixture.bars.filter(b => b.ts < fixture.vaultCutoffTs);
|
|
const preCutoffShorts: Table = {
|
|
columns: fixture.shortsTable.columns,
|
|
rows: fixture.shortsTable.rows.filter(
|
|
r => (r.report_date as string) < fixture.vaultCutoffDate && (r.known_at as number) < fixture.vaultCutoffTs
|
|
),
|
|
};
|
|
const directSignals = shortsTableToSignalRows(preCutoffShorts, 'net_change');
|
|
const directBuilt = buildForwardReturnPanel({
|
|
bars: preCutoffBars,
|
|
signals: directSignals,
|
|
horizonSessions: 5,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
});
|
|
const directStudy = await analyzeSignal(directLedger.executor, {
|
|
principalId: AGENT_PRINCIPAL,
|
|
campaignId: CAMPAIGN_UUID,
|
|
hypothesisId: HYPOTHESIS_UUID,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
expression: {
|
|
expression: 'direct_reference',
|
|
params: { field: 'net_change', horizonSessions: 5 },
|
|
universe: fixture.listingIds,
|
|
horizon: '5d',
|
|
},
|
|
panel: directBuilt.panel,
|
|
vaultCutoffDate: fixture.vaultCutoffDate,
|
|
});
|
|
|
|
expect(directStudy.status).toBe('ok');
|
|
if (directStudy.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
// Parity between MCP payload and direct research pipeline
|
|
expect(payload.scope).toBe('vault_fenced');
|
|
expect(payload.vaultCutoffTs).toBe(fixture.vaultCutoffTs);
|
|
expect(payload.vaultCutoffDate).toBe(fixture.vaultCutoffDate);
|
|
expect(payload.panelDiagnostics).toEqual(directBuilt.diagnostics);
|
|
expect(payload.analysis.rankIc).toEqual(directStudy.analysis.rankIc);
|
|
expect(payload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc);
|
|
expect(payload.analysis.quantiles.spreadSummary).toEqual(
|
|
directStudy.analysis.quantiles.spreadSummary
|
|
);
|
|
expect(payload.analysis.turnover.meanTopTurnover).toBe(
|
|
directStudy.analysis.turnover.meanTopTurnover
|
|
);
|
|
expect(payload.analysis.recency).toEqual(directStudy.analysis.recency);
|
|
expect(payload.analysis.diagnostics).toEqual(directStudy.analysis.diagnostics);
|
|
expect(payload.trial.sampleStart).toBe(directStudy.trial.sampleStart);
|
|
expect(payload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd);
|
|
expect(payload.trial.sampleEnd < fixture.vaultCutoffDate).toBe(true);
|
|
expect(payload.trial.nObs).toBe(directStudy.trial.nObs);
|
|
expect(payload.trial.expressionHash).toMatch(/^[0-9a-f]{64}$/);
|
|
expect(payload.deflatedSharpe).toEqual(directStudy.deflatedSharpe);
|
|
|
|
// Bounded series preview: >100 observations truncated to latest 100 while study & ledger keep full sample
|
|
expect(payload.analysis.ledgerSeries.series).toBe('rank_ic');
|
|
expect(payload.analysis.ledgerSeries.totalCount).toBe(directStudy.trial.nObs);
|
|
expect(payload.analysis.ledgerSeries.totalCount).toBeGreaterThan(ANALYZE_SIGNAL_MAX_SERIES_POINTS);
|
|
expect(payload.analysis.ledgerSeries.truncated).toBe(true);
|
|
expect(payload.analysis.ledgerSeries.points).toHaveLength(ANALYZE_SIGNAL_MAX_SERIES_POINTS);
|
|
const lastPoint = payload.analysis.ledgerSeries.points[ANALYZE_SIGNAL_MAX_SERIES_POINTS - 1];
|
|
expect(lastPoint?.date).toBe(directStudy.trial.sampleEnd);
|
|
|
|
// Exactly one trial_ledger row written with injected principalId and full daily_series
|
|
expect(mcpLedger.rows).toHaveLength(1);
|
|
const stored = mcpLedger.rows[0]!;
|
|
expect(stored.stage).toBe('signal_ic');
|
|
expect(stored.principal_id).toBe(AGENT_PRINCIPAL);
|
|
expect(stored.campaign_id).toBe(CAMPAIGN_UUID);
|
|
expect(stored.hypothesis_id).toBe(HYPOTHESIS_UUID);
|
|
expect(stored.universe_market).toBe('CA_EQ');
|
|
expect(stored.horizon_bucket).toBe('swing_1_10d');
|
|
expect(stored.n_obs).toBe(directStudy.trial.nObs);
|
|
expect(stored.daily_series).toHaveLength(directStudy.trial.nObs);
|
|
});
|
|
|
|
test('identical requests and reordered/duplicate listingIds produce the same expressionHash; changing field, horizon, or ledgerSeries changes it', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const from = fixture.allDates[0]!;
|
|
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
|
|
|
async function runWithArgs(args: Record<string, unknown>) {
|
|
const store = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable });
|
|
const ledger = createFakeTrialLedger();
|
|
const res = await callAnalyzeSignal({
|
|
store: store.store,
|
|
ledger: ledger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args,
|
|
});
|
|
expect(res.isError).toBe(false);
|
|
const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload;
|
|
expect(payload.status).toBe('ok');
|
|
if (payload.status !== 'ok') {
|
|
throw new Error('Expected ok status');
|
|
}
|
|
return { payload, ledger };
|
|
}
|
|
|
|
const baseArgs = {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const run1 = await runWithArgs(baseArgs);
|
|
const run2 = await runWithArgs(baseArgs);
|
|
expect(run1.payload.trial.expressionHash).toBe(run2.payload.trial.expressionHash);
|
|
|
|
// Reordered and duplicated listingIds canonicalize to the exact same expressionHash
|
|
const reorderedIds = [...fixture.listingIds].reverse();
|
|
reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[3]!);
|
|
const runReordered = await runWithArgs({ ...baseArgs, listingIds: reorderedIds });
|
|
expect(runReordered.payload.trial.expressionHash).toBe(run1.payload.trial.expressionHash);
|
|
|
|
// Different signal.field -> different expressionHash
|
|
const runOtherField = await runWithArgs({
|
|
...baseArgs,
|
|
signal: { source: 'shorts', field: 'pct_float' },
|
|
});
|
|
expect(runOtherField.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash);
|
|
|
|
// Different horizonSessions -> different expressionHash (including position_10d_plus bucket for 11d)
|
|
const runOtherHorizon = await runWithArgs({
|
|
...baseArgs,
|
|
horizonSessions: 11,
|
|
horizonBucket: 'position_10d_plus',
|
|
});
|
|
expect(runOtherHorizon.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash);
|
|
expect(runOtherHorizon.ledger.rows[0]?.horizon_bucket).toBe('position_10d_plus');
|
|
|
|
// Equivalent date/timestamp/offset forms canonicalize to identical effective microsecond bounds & expressionHash
|
|
const midDate = fixture.allDates[120]!;
|
|
const runDateForm = await runWithArgs({
|
|
...baseArgs,
|
|
from,
|
|
to: midDate,
|
|
asOf: midDate,
|
|
});
|
|
const runIsoMicrosForm = await runWithArgs({
|
|
...baseArgs,
|
|
from: `${from}T00:00:00.000000Z`,
|
|
to: `${midDate}T23:59:59.999999Z`,
|
|
asOf: `${midDate}T23:59:59.999999Z`,
|
|
});
|
|
const runOffsetForm = await runWithArgs({
|
|
...baseArgs,
|
|
from: '2022-08-31T19:00:00.000000-05:00',
|
|
to: `${midDate}T18:59:59.999999-05:00`,
|
|
asOf: `${midDate}T18:59:59.999999-05:00`,
|
|
});
|
|
expect(runDateForm.payload.effectiveFrom).toBe(`${from}T00:00:00.000Z`);
|
|
expect(runDateForm.payload.effectiveTo).toBe(`${midDate}T23:59:59.999999Z`);
|
|
expect(runDateForm.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999999Z`);
|
|
expect(runIsoMicrosForm.payload.effectiveFrom).toBe(runDateForm.payload.effectiveFrom);
|
|
expect(runIsoMicrosForm.payload.effectiveTo).toBe(runDateForm.payload.effectiveTo);
|
|
expect(runIsoMicrosForm.payload.effectiveAsOf).toBe(runDateForm.payload.effectiveAsOf);
|
|
expect(runIsoMicrosForm.payload.trial.expressionHash).toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
expect(runOffsetForm.payload.trial.expressionHash).toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
|
|
// Distinct sub-millisecond effective bounds produce different expressionHash even with identical sampleStart/sampleEnd
|
|
const runAsOfZeroMicros = await runWithArgs({
|
|
...baseArgs,
|
|
from,
|
|
to: midDate,
|
|
asOf: `${midDate}T23:59:59.999000Z`,
|
|
});
|
|
expect(runAsOfZeroMicros.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999Z`);
|
|
expect(runAsOfZeroMicros.payload.trial.sampleStart).toBe(runDateForm.payload.trial.sampleStart);
|
|
expect(runAsOfZeroMicros.payload.trial.sampleEnd).toBe(runDateForm.payload.trial.sampleEnd);
|
|
expect(runAsOfZeroMicros.payload.trial.expressionHash).not.toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
|
|
const runToZeroMicros = await runWithArgs({
|
|
...baseArgs,
|
|
from,
|
|
to: `${midDate}T23:59:59.999000Z`,
|
|
asOf: midDate,
|
|
});
|
|
expect(runToZeroMicros.payload.effectiveTo).toBe(`${midDate}T23:59:59.999Z`);
|
|
expect(runToZeroMicros.payload.trial.expressionHash).not.toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
|
|
const runFromOneMicro = await runWithArgs({
|
|
...baseArgs,
|
|
from: `${from}T00:00:00.000001Z`,
|
|
to: midDate,
|
|
asOf: midDate,
|
|
});
|
|
expect(runFromOneMicro.payload.effectiveFrom).toBe(`${from}T00:00:00.000001Z`);
|
|
expect(runFromOneMicro.payload.trial.expressionHash).not.toBe(
|
|
runDateForm.payload.trial.expressionHash
|
|
);
|
|
|
|
// quantile_spread ledgerSeries works, truncates preview to 100 while preserving full count, and hashes distinctly
|
|
const runSpread = await runWithArgs({ ...baseArgs, ledgerSeries: 'quantile_spread' });
|
|
expect(runSpread.payload.analysis.ledgerSeries.series).toBe('quantile_spread');
|
|
expect(runSpread.payload.analysis.ledgerSeries.totalCount).toBe(runSpread.payload.trial.nObs);
|
|
expect(runSpread.payload.analysis.ledgerSeries.truncated).toBe(true);
|
|
expect(runSpread.payload.analysis.ledgerSeries.points).toHaveLength(
|
|
ANALYZE_SIGNAL_MAX_SERIES_POINTS
|
|
);
|
|
expect(runSpread.ledger.rows[0]?.daily_series).toHaveLength(runSpread.payload.trial.nObs);
|
|
expect(runSpread.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash);
|
|
});
|
|
|
|
test('clamps to/asOf strictly below midnight and intraday Vault cutoffs and blocks cutoff-day leakage from a leaky store', async () => {
|
|
const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false });
|
|
const poisonedFixture = buildCeoShortsFixture({ poisonPostCutoff: true });
|
|
const from = cleanFixture.allDates[0]!;
|
|
const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!;
|
|
const horizonSessions = 5;
|
|
|
|
// 1. Clamping test with to and asOf after Vault cutoff (midnight cutoff)
|
|
const clampLedger = createFakeTrialLedger();
|
|
const clampStore = createFakeStore({
|
|
bars: cleanFixture.bars,
|
|
shortsTable: cleanFixture.shortsTable,
|
|
});
|
|
const clampRes = await callAnalyzeSignal({
|
|
store: clampStore.store,
|
|
ledger: clampLedger.executor,
|
|
vaultCutoffTs: cleanFixture.vaultCutoffTs,
|
|
args: {
|
|
listingIds: cleanFixture.listingIds,
|
|
from,
|
|
to: postCutoffDate,
|
|
asOf: postCutoffDate,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
|
|
expect(clampRes.isError).toBe(false);
|
|
const clampPayload = JSON.parse(clampRes.text) as AnalyzeSignalResultPayload;
|
|
expect(clampPayload.status).toBe('ok');
|
|
expect(clampPayload.clampedTo).toBe(true);
|
|
expect(clampPayload.clampedAsOf).toBe(true);
|
|
expect(clampPayload.toMs).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
expect(clampPayload.asOfMs).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
|
|
// Store received fenced to and asOf strictly below vaultCutoffTs
|
|
expect(clampStore.barsCalls).toHaveLength(1);
|
|
expect(clampStore.barsCalls[0]?.scope).toBe('vault_fenced');
|
|
expect(Date.parse(clampStore.barsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
expect(Date.parse(clampStore.barsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
expect(clampStore.shortsCalls).toHaveLength(1);
|
|
expect(Date.parse(clampStore.shortsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
expect(Date.parse(clampStore.shortsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1);
|
|
if (clampPayload.status === 'ok') {
|
|
expect(clampPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true);
|
|
const endIdx = cleanFixture.allDates.indexOf(clampPayload.trial.sampleEnd);
|
|
const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!;
|
|
expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true);
|
|
}
|
|
|
|
// 2. Intraday Vault cutoff (12:00 UTC on vaultCutoffDate) with asOf beyond cutoff and leaky store
|
|
// injecting rows on vaultCutoffDate before cutoff, at exact cutoff timestamp, and after cutoff.
|
|
const intradayCutoffTs = makeUtcMs(cleanFixture.vaultCutoffDate, 12);
|
|
const cleanPreCutoffBars = cleanFixture.bars.filter(
|
|
b => new Date(b.ts).toISOString().slice(0, 10) < cleanFixture.vaultCutoffDate
|
|
);
|
|
const cleanPreCutoffShorts: Table = {
|
|
columns: cleanFixture.shortsTable.columns,
|
|
rows: cleanFixture.shortsTable.rows.filter(
|
|
r =>
|
|
(r.report_date as string) < cleanFixture.vaultCutoffDate &&
|
|
(r.known_at as number) < intradayCutoffTs
|
|
),
|
|
};
|
|
const cleanIntradayStore = createFakeStore({
|
|
bars: cleanPreCutoffBars,
|
|
shortsTable: cleanPreCutoffShorts,
|
|
leaky: false,
|
|
});
|
|
const leakyIntradayStore = createFakeStore({
|
|
bars: [
|
|
...poisonedFixture.bars,
|
|
// Cutoff-day bars BEFORE intradayCutoffTs (10:00 UTC) for every listing
|
|
...poisonedFixture.listingIds.map(listingId => ({
|
|
listingId,
|
|
ts: makeUtcMs(poisonedFixture.vaultCutoffDate, 10),
|
|
open: 888_888,
|
|
high: 888_888,
|
|
low: 888_888,
|
|
close: 888_888,
|
|
volume: 100,
|
|
vwap: 888_888,
|
|
knownAt: makeUtcMs(poisonedFixture.vaultCutoffDate, 10),
|
|
})),
|
|
// Bar at EXACT intradayCutoffTs (12:00 UTC)
|
|
{
|
|
listingId: poisonedFixture.listingIds[0]!,
|
|
ts: intradayCutoffTs,
|
|
open: 777_777,
|
|
high: 777_777,
|
|
low: 777_777,
|
|
close: 777_777,
|
|
volume: 100,
|
|
vwap: 777_777,
|
|
knownAt: intradayCutoffTs,
|
|
},
|
|
],
|
|
shortsTable: {
|
|
columns: poisonedFixture.shortsTable.columns,
|
|
rows: [
|
|
...poisonedFixture.shortsTable.rows,
|
|
// Shorts row on vaultCutoffDate with known_at before intradayCutoffTs
|
|
{
|
|
listing_id: poisonedFixture.listingIds[0]!,
|
|
report_date: poisonedFixture.vaultCutoffDate,
|
|
known_at: makeUtcMs(poisonedFixture.vaultCutoffDate, 9),
|
|
shares_short: 9_999_999,
|
|
net_change: 9_999_999,
|
|
pct_float: 0.99,
|
|
source: 'ceoShorts',
|
|
},
|
|
// Shorts row with report_date before cutoff but known_at at exact intradayCutoffTs
|
|
{
|
|
listing_id: poisonedFixture.listingIds[1]!,
|
|
report_date: cleanFixture.allDates[100]!,
|
|
known_at: intradayCutoffTs,
|
|
shares_short: 8_888_888,
|
|
net_change: 8_888_888,
|
|
pct_float: 0.88,
|
|
source: 'ceoShorts',
|
|
},
|
|
],
|
|
},
|
|
leaky: true,
|
|
});
|
|
|
|
const cleanIntradayLedger = createFakeTrialLedger();
|
|
const leakyIntradayLedger = createFakeTrialLedger();
|
|
const intradayArgs = {
|
|
listingIds: cleanFixture.listingIds,
|
|
from,
|
|
to: postCutoffDate,
|
|
asOf: postCutoffDate,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const cleanIntradayRes = await callAnalyzeSignal({
|
|
store: cleanIntradayStore.store,
|
|
ledger: cleanIntradayLedger.executor,
|
|
vaultCutoffTs: intradayCutoffTs,
|
|
args: intradayArgs,
|
|
});
|
|
const leakyIntradayRes = await callAnalyzeSignal({
|
|
store: leakyIntradayStore.store,
|
|
ledger: leakyIntradayLedger.executor,
|
|
vaultCutoffTs: intradayCutoffTs,
|
|
args: intradayArgs,
|
|
});
|
|
|
|
expect(cleanIntradayRes.isError).toBe(false);
|
|
expect(leakyIntradayRes.isError).toBe(false);
|
|
expect(leakyIntradayRes.text).toBe(cleanIntradayRes.text);
|
|
expect(leakyIntradayLedger.rows).toEqual(cleanIntradayLedger.rows);
|
|
|
|
const intradayPayload = JSON.parse(leakyIntradayRes.text) as AnalyzeSignalResultPayload;
|
|
expect(intradayPayload.status).toBe('ok');
|
|
expect(intradayPayload.clampedTo).toBe(true);
|
|
expect(intradayPayload.clampedAsOf).toBe(true);
|
|
expect(intradayPayload.toMs).toBe(intradayCutoffTs - 1);
|
|
expect(intradayPayload.asOfMs).toBe(intradayCutoffTs - 1);
|
|
if (intradayPayload.status === 'ok') {
|
|
expect(intradayPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true);
|
|
const endIdx = cleanFixture.allDates.indexOf(intradayPayload.trial.sampleEnd);
|
|
const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!;
|
|
expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true);
|
|
}
|
|
});
|
|
|
|
test('earlier explicit asOf excludes bars with ts > asOf or knownAt > asOf independently from a leaky store and matches clean replay', async () => {
|
|
const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false });
|
|
const from = cleanFixture.allDates[0]!;
|
|
const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!;
|
|
const horizonSessions = 5;
|
|
|
|
// Set asOf to noon UTC on session 100 while `to` extends past cutoff
|
|
const asOfSessionIdx = 100;
|
|
const asOfDate = cleanFixture.allDates[asOfSessionIdx]!;
|
|
const asOfIso = `${asOfDate}T12:00:00.000Z`;
|
|
const asOfMs = makeUtcMs(asOfDate, 12);
|
|
|
|
// Clean replay store filters strictly by ts <= asOfMs && knownAt <= asOfMs
|
|
const cleanStore = createFakeStore({
|
|
bars: cleanFixture.bars,
|
|
shortsTable: cleanFixture.shortsTable,
|
|
leaky: false,
|
|
});
|
|
|
|
// Leaky store injects two independent bar leaks + a delayed shorts row:
|
|
// (a) Closing bars on `asOfDate` stamped at 21:00 UTC (> noon asOf) with knownAt at 00:00 UTC (<= noon asOf) and poisoned close
|
|
// (b) Delayed bars on session 95 (ts <= noon asOf) with knownAt at 15:00 UTC on `asOfDate` (> noon asOf) and poisoned close
|
|
const delayedBarDate = cleanFixture.allDates[95]!;
|
|
const leakyBars: BarRecord[] = cleanFixture.bars.map(bar => {
|
|
if (bar.ts === makeUtcMs(asOfDate, 21)) {
|
|
return {
|
|
...bar,
|
|
open: 666_666,
|
|
high: 666_666,
|
|
low: 666_666,
|
|
close: 666_666,
|
|
vwap: 666_666,
|
|
knownAt: makeUtcMs(asOfDate, 0), // earlier than noon asOf, while ts (21:00 UTC) > noon asOf
|
|
};
|
|
}
|
|
return bar;
|
|
});
|
|
// Also inject a bar with ts <= asOfMs but knownAt > asOfMs for listing 0 on session 95 (replace clean bar? No, add extra listing or poisoned bar on a date not in clean? Better: inject on a date after clean or with a listing that has a delayed knownAt!)
|
|
// Specifically: take a clean bar on session 95 for listing 0 and verify a delayed-knownAt poison bar on session 100-1 (where ts <= asOfMs and knownAt > asOfMs) is dropped.
|
|
// Even stronger: add a synthetic bar on `delayedBarDate` at 10:00 UTC (ts <= asOfMs) with knownAt = 15:00 UTC on `asOfDate` (> asOfMs) and poisoned close 555_555.
|
|
// If knownAt filter regresses, buildForwardReturnPanel will throw duplicate_bar (conflicting close on delayedBarDate)!
|
|
leakyBars.push({
|
|
listingId: cleanFixture.listingIds[0]!,
|
|
ts: makeUtcMs(delayedBarDate, 10),
|
|
open: 555_555,
|
|
high: 555_555,
|
|
low: 555_555,
|
|
close: 555_555,
|
|
volume: 100,
|
|
vwap: 555_555,
|
|
knownAt: makeUtcMs(asOfDate, 15), // > noon asOf, while ts <= noon asOf
|
|
});
|
|
|
|
const leakyStore = createFakeStore({
|
|
bars: leakyBars,
|
|
shortsTable: {
|
|
columns: cleanFixture.shortsTable.columns,
|
|
rows: [
|
|
...cleanFixture.shortsTable.rows,
|
|
{
|
|
listing_id: cleanFixture.listingIds[1]!,
|
|
report_date: cleanFixture.allDates[50]!,
|
|
known_at: makeUtcMs(asOfDate, 15), // > noon asOf
|
|
shares_short: 7_777_777,
|
|
net_change: 7_777_777,
|
|
pct_float: 0.77,
|
|
source: 'ceoShorts',
|
|
},
|
|
],
|
|
},
|
|
leaky: true,
|
|
});
|
|
|
|
const cleanLedger = createFakeTrialLedger();
|
|
const leakyLedger = createFakeTrialLedger();
|
|
const args = {
|
|
listingIds: cleanFixture.listingIds,
|
|
from,
|
|
to: postCutoffDate,
|
|
asOf: asOfIso,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const cleanRes = await callAnalyzeSignal({
|
|
store: cleanStore.store,
|
|
ledger: cleanLedger.executor,
|
|
vaultCutoffTs: cleanFixture.vaultCutoffTs,
|
|
args,
|
|
});
|
|
const leakyRes = await callAnalyzeSignal({
|
|
store: leakyStore.store,
|
|
ledger: leakyLedger.executor,
|
|
vaultCutoffTs: cleanFixture.vaultCutoffTs,
|
|
args,
|
|
});
|
|
|
|
expect(cleanRes.isError).toBe(false);
|
|
expect(leakyRes.isError).toBe(false);
|
|
expect(leakyRes.text).toBe(cleanRes.text);
|
|
expect(leakyLedger.rows).toEqual(cleanLedger.rows);
|
|
|
|
const payload = JSON.parse(leakyRes.text) as AnalyzeSignalResultPayload;
|
|
expect(payload.status).toBe('ok');
|
|
expect(payload.clampedAsOf).toBe(false);
|
|
expect(payload.asOfMs).toBe(asOfMs);
|
|
if (payload.status === 'ok') {
|
|
const endIdx = cleanFixture.allDates.indexOf(payload.trial.sampleEnd);
|
|
const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!;
|
|
// Closing bar on asOfDate (21:00 UTC) was excluded by ts > asOfMs, so last forward endpoint must precede asOfDate
|
|
expect(lastForwardEndpoint < asOfDate).toBe(true);
|
|
}
|
|
});
|
|
|
|
test('request wholly inside Vault holdout returns fixed VaultHoldoutFenceError with zero store and ledger calls', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const fakeStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
});
|
|
const fakeLedger = createFakeTrialLedger();
|
|
|
|
const res = await callAnalyzeSignal({
|
|
store: fakeStore.store,
|
|
ledger: fakeLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
listingIds: fixture.listingIds,
|
|
from: fixture.vaultCutoffDate,
|
|
to: fixture.allDates[fixture.allDates.length - 1]!,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toBe(
|
|
'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.'
|
|
);
|
|
expect(fakeStore.barsCalls).toHaveLength(0);
|
|
expect(fakeStore.shortsCalls).toHaveLength(0);
|
|
expect(fakeStore.universeCalls).toHaveLength(0);
|
|
expect(fakeLedger.insertCalls).toBe(0);
|
|
expect(fakeLedger.rows).toHaveLength(0);
|
|
});
|
|
|
|
test('named universe resolves strictly before study start and respects earlier/intraday asOf', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const from = fixture.allDates[0]!; // 2022-09-01
|
|
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
|
|
|
const fakeStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
universeIds: [...fixture.listingIds].reverse(),
|
|
});
|
|
const fakeLedger = createFakeTrialLedger();
|
|
|
|
const res = await callAnalyzeSignal({
|
|
store: fakeStore.store,
|
|
ledger: fakeLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
universe: 'CA_EQ',
|
|
from,
|
|
to,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
|
|
expect(res.isError).toBe(false);
|
|
// Study starts 2022-09-01 -> universe must be resolved on 2022-08-31 (strictly before study start)
|
|
expect(fakeStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-31' }]);
|
|
// Sorted listingIds passed to bars and shortsAsOf
|
|
expect(fakeStore.barsCalls[0]?.listingIds).toEqual(fixture.listingIds);
|
|
expect(fakeStore.shortsCalls[0]?.listingIds).toEqual(fixture.listingIds);
|
|
|
|
// Earlier intraday asOf (2022-08-15T12:00:00Z) -> universe resolved on completed UTC date 2022-08-14
|
|
const earlyStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
universeIds: fixture.listingIds,
|
|
});
|
|
const earlyLedger = createFakeTrialLedger();
|
|
await callAnalyzeSignal({
|
|
store: earlyStore.store,
|
|
ledger: earlyLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: {
|
|
universe: 'CA_EQ',
|
|
from,
|
|
to,
|
|
asOf: '2022-08-15T12:00:00Z',
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(earlyStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-14' }]);
|
|
});
|
|
|
|
test('insufficient-data cases (empty universe, empty panel, undersized panel, zero-variance series) return reason with zero ledger writes', async () => {
|
|
const cutoffDate = '2025-03-31';
|
|
const cutoffTs = makeUtcMs(cutoffDate, 0);
|
|
|
|
// 1. Empty resolved universe -> zero bars/shorts calls, zero ledger rows
|
|
const emptyUniStore = createFakeStore({ universeIds: [] });
|
|
const emptyUniLedger = createFakeTrialLedger();
|
|
const emptyUniRes = await callAnalyzeSignal({
|
|
store: emptyUniStore.store,
|
|
ledger: emptyUniLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
universe: 'CA_EQ',
|
|
from: '2025-01-01',
|
|
to: '2025-03-20',
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(emptyUniRes.isError).toBe(false);
|
|
const emptyUniPayload = JSON.parse(emptyUniRes.text) as AnalyzeSignalResultPayload;
|
|
expect(emptyUniPayload.status).toBe('insufficient_data');
|
|
if (emptyUniPayload.status === 'insufficient_data') {
|
|
expect(emptyUniPayload.reason).toBe('too_few_observations');
|
|
}
|
|
expect(emptyUniStore.barsCalls).toHaveLength(0);
|
|
expect(emptyUniStore.shortsCalls).toHaveLength(0);
|
|
expect(emptyUniLedger.rows).toHaveLength(0);
|
|
|
|
// 2. Empty panel (bars exist but no shorts signals)
|
|
const dates = makeBusinessDates('2025-01-02', 6);
|
|
const barsForSixDays: BarRecord[] = [];
|
|
for (let d = 0; d < dates.length; d += 1) {
|
|
const ts = makeUtcMs(dates[d]!, 21);
|
|
for (let id = 1; id <= 6; id += 1) {
|
|
barsForSixDays.push({
|
|
listingId: id,
|
|
ts,
|
|
open: 100 + d,
|
|
high: 101 + d,
|
|
low: 99 + d,
|
|
close: 100 + d + id * 0.1,
|
|
volume: 1000,
|
|
vwap: 100 + d,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
const emptyPanelStore = createFakeStore({
|
|
bars: barsForSixDays,
|
|
shortsTable: { columns: SHORTS_COLUMNS, rows: [] },
|
|
});
|
|
const emptyPanelLedger = createFakeTrialLedger();
|
|
const emptyPanelRes = await callAnalyzeSignal({
|
|
store: emptyPanelStore.store,
|
|
ledger: emptyPanelLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
listingIds: [1, 2, 3, 4, 5, 6],
|
|
from: dates[0]!,
|
|
to: dates[dates.length - 1]!,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(emptyPanelRes.isError).toBe(false);
|
|
const emptyPanelPayload = JSON.parse(emptyPanelRes.text) as AnalyzeSignalResultPayload;
|
|
expect(emptyPanelPayload.status).toBe('insufficient_data');
|
|
if (emptyPanelPayload.status === 'insufficient_data') {
|
|
expect(emptyPanelPayload.reason).toBe('too_few_observations');
|
|
}
|
|
expect(emptyPanelLedger.rows).toHaveLength(0);
|
|
|
|
// 3. Undersized non-empty panel (only 1 date with forward return -> too_few_observations)
|
|
const twoDayBars = barsForSixDays.filter(b => b.ts <= makeUtcMs(dates[1]!, 21));
|
|
const singleSignalRows: TableRow[] = [1, 2, 3, 4, 5, 6].map(id => ({
|
|
listing_id: id,
|
|
report_date: dates[0]!,
|
|
known_at: makeUtcMs(dates[0]!, 10),
|
|
shares_short: 1000 * id,
|
|
net_change: 100 * id,
|
|
pct_float: 0.01 * id,
|
|
source: 'ceoShorts',
|
|
}));
|
|
const undersizedStore = createFakeStore({
|
|
bars: twoDayBars,
|
|
shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows },
|
|
});
|
|
const undersizedLedger = createFakeTrialLedger();
|
|
const undersizedRes = await callAnalyzeSignal({
|
|
store: undersizedStore.store,
|
|
ledger: undersizedLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
listingIds: [1, 2, 3, 4, 5, 6],
|
|
from: dates[0]!,
|
|
to: dates[1]!,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(undersizedRes.isError).toBe(false);
|
|
const undersizedPayload = JSON.parse(undersizedRes.text) as AnalyzeSignalResultPayload;
|
|
expect(undersizedPayload.status).toBe('insufficient_data');
|
|
if (undersizedPayload.status === 'insufficient_data') {
|
|
expect(undersizedPayload.reason).toBe('too_few_observations');
|
|
}
|
|
expect(undersizedLedger.rows).toHaveLength(0);
|
|
|
|
// 4. Zero-variance rank_ic series (identical strictly monotone rank ordering every day -> rank_ic = 1.0 on every date)
|
|
const monotoneBars: BarRecord[] = [];
|
|
for (let d = 0; d < dates.length; d += 1) {
|
|
const ts = makeUtcMs(dates[d]!, 21);
|
|
for (let id = 1; id <= 6; id += 1) {
|
|
const close = 100 * Math.pow(1 + 0.01 * id, d);
|
|
monotoneBars.push({
|
|
listingId: id,
|
|
ts,
|
|
open: close,
|
|
high: close,
|
|
low: close,
|
|
close,
|
|
volume: 1000,
|
|
vwap: close,
|
|
knownAt: ts,
|
|
});
|
|
}
|
|
}
|
|
const zeroVarStore = createFakeStore({
|
|
bars: monotoneBars,
|
|
shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows },
|
|
});
|
|
const zeroVarLedger = createFakeTrialLedger();
|
|
const zeroVarRes = await callAnalyzeSignal({
|
|
store: zeroVarStore.store,
|
|
ledger: zeroVarLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args: {
|
|
listingIds: [1, 2, 3, 4, 5, 6],
|
|
from: dates[0]!,
|
|
to: dates[dates.length - 1]!,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 1,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
});
|
|
expect(zeroVarRes.isError).toBe(false);
|
|
const zeroVarPayload = JSON.parse(zeroVarRes.text) as AnalyzeSignalResultPayload;
|
|
expect(zeroVarPayload.status).toBe('insufficient_data');
|
|
if (zeroVarPayload.status === 'insufficient_data') {
|
|
expect(zeroVarPayload.reason).toBe('zero_variance_series');
|
|
}
|
|
expect(zeroVarLedger.rows).toHaveLength(0);
|
|
});
|
|
|
|
test('strict schema rejects forbidden keys, unknown keys, bad selectors, invalid dates/UUIDs, INT32/limit/horizon violations with zero store or ledger calls', async () => {
|
|
const cutoffTs = makeUtcMs('2025-03-31', 0);
|
|
const validBase = {
|
|
listingIds: [101, 102],
|
|
from: '2025-01-02',
|
|
to: '2025-03-20',
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const invalidCases: readonly [string, Record<string, unknown>][] = [
|
|
['scope vault_evaluation_only', { ...validBase, scope: 'vault_evaluation_only' }],
|
|
['scope vault_fenced', { ...validBase, scope: 'vault_fenced' }],
|
|
['vault_evaluation_only flag', { ...validBase, vault_evaluation_only: true }],
|
|
['principalId override', { ...validBase, principalId: 'operator' }],
|
|
['vaultCutoffDate override', { ...validBase, vaultCutoffDate: '2026-01-01' }],
|
|
['unknown top-level key', { ...validBase, extraFlag: true }],
|
|
[
|
|
'unknown nested signal key',
|
|
{ ...validBase, signal: { source: 'shorts', field: 'net_change', extra: 1 } },
|
|
],
|
|
['both listingIds and universe', { ...validBase, universe: 'CA_EQ' }],
|
|
[
|
|
'neither listingIds nor universe',
|
|
{
|
|
from: validBase.from,
|
|
to: validBase.to,
|
|
signal: validBase.signal,
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
],
|
|
['unknown signal.source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }],
|
|
['unknown signal.field', { ...validBase, signal: { source: 'shorts', field: 'unknown_col' } }],
|
|
['invalid calendar date from', { ...validBase, from: '2025-02-30' }],
|
|
['invalid string date to', { ...validBase, to: 'not-a-date' }],
|
|
['naive timestamp without offset in asOf', { ...validBase, asOf: '2025-02-01T12:00:00' }],
|
|
['invalid campaignId UUID', { ...validBase, campaignId: 'not-a-uuid' }],
|
|
['invalid hypothesisId UUID', { ...validBase, hypothesisId: '12345' }],
|
|
['INT32 overflow listingId', { ...validBase, listingIds: [2_147_483_648] }],
|
|
['INT32 underflow listingId', { ...validBase, listingIds: [-2_147_483_649] }],
|
|
['non-integer listingId', { ...validBase, listingIds: [101.5] }],
|
|
['empty listingIds', { ...validBase, listingIds: [] }],
|
|
[
|
|
'more than 500 explicit listingIds',
|
|
{
|
|
...validBase,
|
|
listingIds: Array.from({ length: ANALYZE_SIGNAL_MAX_LISTING_IDS + 1 }, (_, i) => i + 1),
|
|
},
|
|
],
|
|
['horizonSessions 0', { ...validBase, horizonSessions: 0 }],
|
|
['horizonSessions negative', { ...validBase, horizonSessions: -3 }],
|
|
[
|
|
'horizonSessions above max',
|
|
{ ...validBase, horizonSessions: ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS + 1 },
|
|
],
|
|
['horizonSessions float', { ...validBase, horizonSessions: 2.5 }],
|
|
['negative maxSignalAgeSessions', { ...validBase, maxSignalAgeSessions: -1 }],
|
|
['mismatched horizonBucket intraday for 5d daily horizon', { ...validBase, horizonSessions: 5, horizonBucket: 'intraday' }],
|
|
[
|
|
'mismatched horizonBucket position_10d_plus for 5d daily horizon',
|
|
{ ...validBase, horizonSessions: 5, horizonBucket: 'position_10d_plus' },
|
|
],
|
|
[
|
|
'mismatched horizonBucket swing_1_10d for 11d daily horizon',
|
|
{ ...validBase, horizonSessions: 11, horizonBucket: 'swing_1_10d' },
|
|
],
|
|
[
|
|
'mismatched horizonBucket intraday for 15d daily horizon',
|
|
{ ...validBase, horizonSessions: 15, horizonBucket: 'intraday' },
|
|
],
|
|
[
|
|
'named universe CA_EQ with mismatched universeMarket FX',
|
|
{
|
|
from: validBase.from,
|
|
to: validBase.to,
|
|
signal: validBase.signal,
|
|
horizonSessions: 5,
|
|
universe: 'CA_EQ',
|
|
universeMarket: 'FX',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
],
|
|
[
|
|
'named universe CA_EQ with mismatched universeMarket US_EQ',
|
|
{
|
|
from: validBase.from,
|
|
to: validBase.to,
|
|
signal: validBase.signal,
|
|
horizonSessions: 5,
|
|
universe: 'CA_EQ',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
],
|
|
[
|
|
'named universe US_CA_EQ with mismatched universeMarket US_EQ',
|
|
{
|
|
from: validBase.from,
|
|
to: validBase.to,
|
|
signal: validBase.signal,
|
|
horizonSessions: 5,
|
|
universe: 'US_CA_EQ',
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
},
|
|
],
|
|
['shorts study with FX universeMarket and listingIds', { ...validBase, universeMarket: 'FX' }],
|
|
];
|
|
|
|
for (const [_label, args] of invalidCases) {
|
|
const fakeStore = createFakeStore();
|
|
const fakeLedger = createFakeTrialLedger();
|
|
const res = await callAnalyzeSignal({
|
|
store: fakeStore.store,
|
|
ledger: fakeLedger.executor,
|
|
vaultCutoffTs: cutoffTs,
|
|
args,
|
|
});
|
|
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toContain('Invalid arguments for tool "analyze_signal":');
|
|
expect(fakeStore.barsCalls).toHaveLength(0);
|
|
expect(fakeStore.shortsCalls).toHaveLength(0);
|
|
expect(fakeStore.universeCalls).toHaveLength(0);
|
|
expect(fakeLedger.insertCalls).toBe(0);
|
|
}
|
|
|
|
// Raw JSON own __proto__ key rejected with zero store or ledger calls
|
|
const protoStore = createFakeStore();
|
|
const protoLedger = createFakeTrialLedger();
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [
|
|
createAnalyzeSignalTool({
|
|
store: protoStore.store,
|
|
ledger: protoLedger.executor,
|
|
vaultContext: { vaultCutoffTs: cutoffTs },
|
|
principalId: AGENT_PRINCIPAL,
|
|
}),
|
|
],
|
|
});
|
|
const rawProto =
|
|
'{"jsonrpc":"2.0","id":"proto-1","method":"tools/call","params":{"name":"analyze_signal","arguments":{"listingIds":[101],"from":"2025-01-02","to":"2025-03-20","signal":{"source":"shorts","field":"net_change"},"horizonSessions":5,"universeMarket":"CA_EQ","horizonBucket":"swing_1_10d","__proto__":{"principalId":"operator"}}}}';
|
|
const protoResp = JSON.parse((await server.handleMessage(rawProto)) as string) as {
|
|
result: { isError?: boolean; content: { type: string; text: string }[] };
|
|
};
|
|
expect(protoResp.result.isError).toBe(true);
|
|
expect(protoStore.barsCalls).toHaveLength(0);
|
|
expect(protoLedger.insertCalls).toBe(0);
|
|
});
|
|
|
|
test('sanitizes store, panel, ledger insert, and DSR read failures without leaking SQL, paths, or connection URIs', async () => {
|
|
const fixture = buildCeoShortsFixture();
|
|
const from = fixture.allDates[0]!;
|
|
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
|
const validArgs = {
|
|
listingIds: fixture.listingIds,
|
|
from,
|
|
to,
|
|
signal: { source: 'shorts', field: 'net_change' },
|
|
horizonSessions: 5,
|
|
universeMarket: 'CA_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
};
|
|
|
|
const sensitiveDetail =
|
|
'SELECT * FROM trial_ledger WHERE secret=1 at /mnt/data/stockbot/curated/shorts/part.parquet via postgres://user:pass@host:5432/trading_bot';
|
|
|
|
function assertNoLeak(rawResponse: string): void {
|
|
expect(rawResponse).not.toContain('SELECT * FROM trial_ledger');
|
|
expect(rawResponse).not.toContain('/mnt/data/stockbot');
|
|
expect(rawResponse).not.toContain('part.parquet');
|
|
expect(rawResponse).not.toContain('postgres://user:pass@host');
|
|
}
|
|
|
|
// 1. Store domain & unexpected errors
|
|
const storeErrors: readonly [Error, string][] = [
|
|
[new VaultScopeNotAuthorizedError(sensitiveDetail), 'VaultScopeNotAuthorizedError'],
|
|
[new MarketDataStoreValidationError(sensitiveDetail, 'curatedRoot'), 'MarketDataStoreValidationError'],
|
|
[new MarketDataStoreNotImplementedError('shortsAsOf', sensitiveDetail), 'MarketDataStoreNotImplementedError'],
|
|
[new Error(sensitiveDetail), 'Error: Tool execution failed.'],
|
|
];
|
|
for (const [err, expectedSnippet] of storeErrors) {
|
|
const store = createFakeStore({ shortsError: err, bars: fixture.bars });
|
|
const ledger = createFakeTrialLedger();
|
|
const res = await callAnalyzeSignal({
|
|
store: store.store,
|
|
ledger: ledger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: validArgs,
|
|
});
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toContain(expectedSnippet);
|
|
assertNoLeak(res.rawResponse);
|
|
expect(ledger.rows).toHaveLength(0);
|
|
}
|
|
|
|
// 2. Malformed shorts table -> SignalPanelError mapped cleanly
|
|
const badTableStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: { columns: ['listing_id'], rows: [] },
|
|
});
|
|
const badTableLedger = createFakeTrialLedger();
|
|
const badTableRes = await callAnalyzeSignal({
|
|
store: badTableStore.store,
|
|
ledger: badTableLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: validArgs,
|
|
});
|
|
expect(badTableRes.isError).toBe(true);
|
|
expect(badTableRes.text).toContain('SignalPanelError:');
|
|
expect(badTableLedger.rows).toHaveLength(0);
|
|
|
|
// 3. Ledger INSERT failure -> isError: true, no leak, zero trial rows written
|
|
const insertFailStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
});
|
|
const insertFailLedger = createFakeTrialLedger({
|
|
insertError: new Error(sensitiveDetail),
|
|
});
|
|
const insertFailRes = await callAnalyzeSignal({
|
|
store: insertFailStore.store,
|
|
ledger: insertFailLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: validArgs,
|
|
});
|
|
expect(insertFailRes.isError).toBe(true);
|
|
expect(insertFailRes.text).toBe('Error: Tool execution failed.');
|
|
assertNoLeak(insertFailRes.rawResponse);
|
|
expect(insertFailLedger.insertCalls).toBe(1);
|
|
expect(insertFailLedger.rows).toHaveLength(0);
|
|
|
|
// 4. DSR read failure after INSERT -> isError: true, fixed SignalStudyError, no leak, exactly 1 insert (never retried)
|
|
const dsrFailStore = createFakeStore({
|
|
bars: fixture.bars,
|
|
shortsTable: fixture.shortsTable,
|
|
});
|
|
const dsrFailLedger = createFakeTrialLedger({
|
|
dsrReadError: new Error(sensitiveDetail),
|
|
});
|
|
const dsrFailRes = await callAnalyzeSignal({
|
|
store: dsrFailStore.store,
|
|
ledger: dsrFailLedger.executor,
|
|
vaultCutoffTs: fixture.vaultCutoffTs,
|
|
args: validArgs,
|
|
});
|
|
expect(dsrFailRes.isError).toBe(true);
|
|
expect(dsrFailRes.text).toBe(
|
|
'SignalStudyError: Trial was recorded, but cluster deflated Sharpe evaluation failed.'
|
|
);
|
|
assertNoLeak(dsrFailRes.rawResponse);
|
|
expect(dsrFailLedger.insertCalls).toBe(1);
|
|
expect(dsrFailLedger.rows).toHaveLength(1);
|
|
});
|
|
});
|