import { describe, expect, test } from 'bun:test'; import { type BarBatch, type BarRecord, type MarketDataStore, MarketDataStoreValidationError, type Table, type TableRow, } from '../src/market-data-store'; import { type BarsQuery, MarketDataStoreNotImplementedError, type ShortsAsOfQuery, type UniverseQuery, } from '../src/market-data-store-duckdb'; import { type AnalyzeSignalResultPayload, createAnalyzeSignalTool, createMcpServer, } from '../src/mcp/index'; import { SignalPanelError, buildForwardReturnPanel, shortsTableToSignalRows, } from '../src/signal-panel'; import { TrialLedgerError, type TrialLedgerExecutor } from '../src/trial-ledger'; // QA fixture: seeded synthetic short-interest panel (SEED below), 12 listings, // 140 pre-cutoff + 10 post-cutoff business sessions from 2022-09-01, shorts // every 10 sessions published T+4 at 22:00 UTC, gross close-to-close returns, // raw adjustment, no fills or fees. const SEED = 4_242_026; const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; const POISON = 'POISON' as unknown as number; const SHORTS_COLUMNS = [ 'listing_id', 'report_date', 'known_at', 'shares_short', 'net_change', 'pct_float', 'source', ] as const; 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, minute = 0): number { return Date.parse(`${date}T00:00:00.000Z`) + hour * 3_600_000 + minute * 60_000; } interface Fixture { readonly listingIds: number[]; readonly allDates: string[]; readonly cutoffDate: string; readonly cutoffTs: number; readonly bars: BarRecord[]; readonly shorts: Table; } function buildFixture(): Fixture { const rand = createSeededRng(SEED); const listingCount = 12; const pre = 140; const allDates = makeBusinessDates('2022-09-01', pre + 10); const cutoffDate = allDates[pre]!; const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i); const bars: BarRecord[] = []; const shortsRows: TableRow[] = []; const active = new Float64Array(listingCount); const pending = new Map(); const prices = Array.from({ length: listingCount }, (_, l) => 20 + l); for (let t = 0; t < allDates.length; t += 1) { const date = allDates[t]!; const released = pending.get(t - 1); if (released !== undefined) { for (let l = 0; l < listingCount; l += 1) { active[l] = released[l]! / 20_000; } } if (t % 10 === 0 && t + 4 < allDates.length) { const knownAt = utcMs(allDates[t + 4]!, 22); const values: number[] = []; for (let l = 0; l < listingCount; l += 1) { const netChange = Math.round((rand() * 2 - 1) * 20_000); values.push(netChange); shortsRows.push({ listing_id: listingIds[l]!, report_date: date, known_at: knownAt, shares_short: 100_000 + Math.round(rand() * 10_000), net_change: netChange, pct_float: Number((0.02 + rand() * 0.08).toFixed(4)), source: 'ceoShorts', }); } pending.set(t + 4, values); } for (let l = 0; l < listingCount; l += 1) { prices[l] = Math.max(0.5, prices[l]! * (1 - 0.004 * active[l]! + (rand() * 2 - 1) * 0.008)); const close = Number(prices[l]!.toFixed(6)); const ts = utcMs(date, 21); bars.push({ listingId: listingIds[l]!, ts, open: close, high: close, low: close, close, volume: 10_000, knownAt: ts, }); } } return { listingIds, allDates, cutoffDate, cutoffTs: utcMs(cutoffDate, 0), bars, shorts: { columns: SHORTS_COLUMNS, rows: shortsRows }, }; } function parseBound(raw: string, endOfDay: boolean): number { if (raw.length === 10) { return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); } return Date.parse(raw); } interface FakeStore { readonly store: MarketDataStore; readonly barsCalls: BarsQuery[]; readonly shortsCalls: ShortsAsOfQuery[]; readonly universeCalls: UniverseQuery[]; } /** * Correctly filtering store; `extraBars` / `extraShorts` are appended * unconditionally to simulate an adapter that leaks rows past its filters. */ function createStore( fixture: Fixture, options?: { extraBars?: readonly BarRecord[]; extraShorts?: readonly TableRow[]; universe?: (q: UniverseQuery) => number[]; barsThrow?: unknown; shortsThrow?: unknown; } ): FakeStore { const barsCalls: BarsQuery[] = []; const shortsCalls: ShortsAsOfQuery[] = []; const universeCalls: UniverseQuery[] = []; const store: MarketDataStore = { bars(q: BarsQuery): AsyncIterable { barsCalls.push(q); const ids = new Set(q.listingIds); const fromMs = parseBound(q.from, false); const toMs = parseBound(q.to, true); const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); const rows = fixture.bars.filter( b => ids.has(b.listingId) && b.ts >= fromMs && b.ts <= toMs && b.ts <= asOfMs && b.knownAt <= asOfMs ); const thrown = options?.barsThrow; return { async *[Symbol.asyncIterator]() { if (thrown !== undefined) { throw thrown; } yield { rows: [...rows, ...(options?.extraBars ?? [])] }; }, }; }, async shortsAsOf(q: ShortsAsOfQuery): Promise { shortsCalls.push(q); if (options?.shortsThrow !== undefined) { throw options.shortsThrow; } const ids = new Set(q.listingIds); const fromDate = q.from.slice(0, 10); const toDate = q.to.slice(0, 10); const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); const rows = fixture.shorts.rows.filter( r => ids.has(r.listing_id as number) && (r.report_date as string) >= fromDate && (r.report_date as string) <= toDate && (r.known_at as number) <= asOfMs ); return { columns: fixture.shorts.columns, rows: [...rows, ...(options?.extraShorts ?? [])] }; }, async universe(q: UniverseQuery): Promise { universeCalls.push(q); return options?.universe?.(q) ?? []; }, 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 { store, barsCalls, shortsCalls, universeCalls }; } 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(options?: { insertThrow?: unknown }): { executor: TrialLedgerExecutor; rows: LedgerRow[]; } { const rows: LedgerRow[] = []; const executor: TrialLedgerExecutor = { async query>(text: string, params?: readonly unknown[]) { const sql = text.trimStart(); if (sql.startsWith('INSERT INTO trial_ledger')) { if (options?.insertThrow !== undefined) { throw options.insertThrow; } const p = params ?? []; const id = rows.length + 1; const row: LedgerRow = { trial_id: String(id), created_at: new Date(Date.UTC(2024, 0, 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 (sql.startsWith('SELECT')) { if (text.includes('WHERE trial_id = $1::bigint')) { const m = rows.filter(r => r.trial_id === String(params?.[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 === params?.[0] && r.horizon_bucket === params?.[1] ); return { rows: m as unknown as Row[], rowCount: m.length }; } } return { rows: [], rowCount: 0 }; }, }; return { executor, rows }; } async function call(params: { store: MarketDataStore; ledger: TrialLedgerExecutor; cutoffTs: number; args: Record; principalId?: string; }): Promise<{ raw: string; isError: boolean; text: string }> { const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [ createAnalyzeSignalTool({ store: params.store, ledger: params.ledger, vaultContext: { vaultCutoffTs: params.cutoffTs }, principalId: params.principalId ?? AGENT_PRINCIPAL, }), ], }); const raw = (await server.handleMessage( JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'analyze_signal', arguments: params.args }, }) )) as string; const parsed = JSON.parse(raw) as { result: { isError?: boolean; content: { text: string }[] }; }; return { raw, isError: parsed.result.isError === true, text: parsed.result.content[0]?.text ?? '', }; } function baseArgs(fixture: Fixture): Record { return { listingIds: fixture.listingIds, from: fixture.allDates[0]!, to: fixture.allDates[fixture.allDates.length - 1]!, signal: { source: 'shorts', field: 'net_change' }, horizonSessions: 5, universeMarket: 'CA_EQ', horizonBucket: 'swing_1_10d', }; } function poisonBar(listingId: number, ts: number, knownAt: number): BarRecord { return { listingId, ts, open: POISON, high: POISON, low: POISON, close: POISON, volume: 1, knownAt, }; } function poisonShort(listingId: number, reportDate: string, knownAt: number): TableRow { return { listing_id: listingId, report_date: reportDate, known_at: knownAt, shares_short: POISON, net_change: POISON, pct_float: POISON, source: 'poison', }; } describe('analyze_signal QA: sentinel rows that would fail panel validation if forwarded', () => { test('positive control: a poison bar or poison shorts row inside the window reaches the panel and maps to a fixed SignalPanelError', async () => { const fixture = buildFixture(); const inWindowTs = utcMs(fixture.allDates[50]!, 21); expect(() => shortsTableToSignalRows( { columns: SHORTS_COLUMNS, rows: [poisonShort(fixture.listingIds[0]!, '2022-10-03', 1)] }, 'net_change' ) ).toThrow(SignalPanelError); const leakedBar = await call({ store: createStore(fixture, { extraBars: [poisonBar(fixture.listingIds[0]!, inWindowTs + 60_000, inWindowTs + 60_000)], }).store, ledger: createLedger().executor, cutoffTs: fixture.cutoffTs, args: baseArgs(fixture), }); expect(leakedBar.isError).toBe(true); expect(leakedBar.text).toBe('SignalPanelError: Market bar data failed panel validation.'); expect(leakedBar.raw).not.toContain('POISON'); const ledger = createLedger(); const leakedShort = await call({ store: createStore(fixture, { extraShorts: [poisonShort(fixture.listingIds[0]!, fixture.allDates[50]!, inWindowTs)], }).store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, args: baseArgs(fixture), }); expect(leakedShort.isError).toBe(true); expect(leakedShort.text).toBe('SignalPanelError: Signal table data failed panel validation.'); expect(leakedShort.raw).not.toContain('POISON'); expect(ledger.rows).toHaveLength(0); }); test('midnight Vault clamp: sentinels at/after the cutoff, before from, or for foreign listings never reach the panel; result equals clean replay', async () => { const fixture = buildFixture(); const lid = fixture.listingIds[3]!; const extraBars = [ poisonBar(lid, fixture.cutoffTs, fixture.cutoffTs - 1), // exact cutoff ts, backdated knownAt poisonBar(lid, utcMs(fixture.allDates[100]!, 21), fixture.cutoffTs), // knownAt at cutoff poisonBar(99_999, utcMs(fixture.allDates[100]!, 15), utcMs(fixture.allDates[100]!, 15)), poisonBar(lid, utcMs('2022-08-15', 21), utcMs('2022-08-15', 21)), // before from ]; const extraShorts = [ poisonShort(lid, fixture.cutoffDate, fixture.cutoffTs - 1), // cutoff-day report, backdated poisonShort(lid, fixture.allDates[100]!, fixture.cutoffTs), // known exactly at cutoff poisonShort(99_999, fixture.allDates[100]!, utcMs(fixture.allDates[105]!, 22)), poisonShort(lid, '2022-08-15', utcMs('2022-08-19', 22)), // report before from ]; const cleanLedger = createLedger(); const clean = await call({ store: createStore(fixture).store, ledger: cleanLedger.executor, cutoffTs: fixture.cutoffTs, args: baseArgs(fixture), }); const poisonedLedger = createLedger(); const poisoned = await call({ store: createStore(fixture, { extraBars, extraShorts }).store, ledger: poisonedLedger.executor, cutoffTs: fixture.cutoffTs, args: baseArgs(fixture), }); expect(clean.isError).toBe(false); expect(poisoned.isError).toBe(false); const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; expect(payload.status).toBe('ok'); expect(payload.clampedTo).toBe(true); // Omitted asOf defaults to the already-clamped `to`, so only `to` reports a clamp. expect(payload.clampedAsOf).toBe(false); expect(payload.asOfMs).toBe(fixture.cutoffTs - 1); if (payload.status === 'ok') { expect(payload.trial.sampleEnd < fixture.cutoffDate).toBe(true); } expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); expect(poisonedLedger.rows).toEqual(cleanLedger.rows); }); test('intraday Vault cutoff: cutoff-date bars before the cutoff instant and cutoff-date shorts are excluded; result equals clean replay', async () => { const fixture = buildFixture(); const cutoffTs = utcMs(fixture.cutoffDate, 15); const lid = fixture.listingIds[5]!; const earlyCutoffDay = utcMs(fixture.cutoffDate, 14); const extraBars = [ poisonBar(lid, earlyCutoffDay, earlyCutoffDay), // before cutoff instant, same UTC date poisonBar(lid, cutoffTs, earlyCutoffDay), // exactly at cutoff ]; const extraShorts = [ poisonShort(lid, fixture.cutoffDate, utcMs(fixture.cutoffDate, 10)), // known before cutoff instant ]; const cleanLedger = createLedger(); const clean = await call({ store: createStore(fixture).store, ledger: cleanLedger.executor, cutoffTs, args: { ...baseArgs(fixture), asOf: fixture.allDates[fixture.allDates.length - 1]! }, }); const poisonedLedger = createLedger(); const poisoned = await call({ store: createStore(fixture, { extraBars, extraShorts }).store, ledger: poisonedLedger.executor, cutoffTs, args: { ...baseArgs(fixture), asOf: fixture.allDates[fixture.allDates.length - 1]! }, }); expect(poisoned.isError).toBe(false); const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; expect(payload.clampedTo).toBe(true); expect(payload.clampedAsOf).toBe(true); expect(payload.effectiveTo).toBe(`${fixture.cutoffDate}T14:59:59.999999Z`); expect(payload.status).toBe('ok'); expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); expect(poisonedLedger.rows).toEqual(cleanLedger.rows); }); test('earlier explicit asOf: shorts known after asOf and bars stamped or known after asOf are excluded; result equals clean replay', async () => { const fixture = buildFixture(); const asOfDate = fixture.allDates[120]!; const asOf = `${asOfDate}T18:00:00.000Z`; const asOfMs = Date.parse(asOf); const lid = fixture.listingIds[7]!; const extraBars = [ poisonBar(lid, utcMs(asOfDate, 21), utcMs(asOfDate, 0)), // close after asOf, backdated knownAt poisonBar(lid, utcMs(fixture.allDates[119]!, 22), asOfMs + 1), // known 1ms after asOf ]; const extraShorts = [poisonShort(lid, fixture.allDates[100]!, asOfMs + 1)]; const args = { ...baseArgs(fixture), asOf }; const cleanLedger = createLedger(); const clean = await call({ store: createStore(fixture).store, ledger: cleanLedger.executor, cutoffTs: fixture.cutoffTs, args, }); const poisonedLedger = createLedger(); const poisoned = await call({ store: createStore(fixture, { extraBars, extraShorts }).store, ledger: poisonedLedger.executor, cutoffTs: fixture.cutoffTs, args, }); expect(poisoned.isError).toBe(false); const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; expect(payload.status).toBe('ok'); expect(payload.clampedAsOf).toBe(false); expect(payload.effectiveAsOf).toBe(asOf); if (payload.status === 'ok') { expect(payload.trial.sampleEnd < asOfDate).toBe(true); } expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); expect(poisonedLedger.rows).toEqual(cleanLedger.rows); }); }); describe('analyze_signal QA: store arguments, universe and ledger behaviour', () => { test('bars and shorts receive identical fenced bounds, 1d timeframe, vault_fenced scope and requested adjustment', async () => { const fixture = buildFixture(); const fake = createStore(fixture); await call({ store: fake.store, ledger: createLedger().executor, cutoffTs: fixture.cutoffTs, args: { ...baseArgs(fixture), adjustment: 'split' }, }); expect(fake.barsCalls).toHaveLength(1); expect(fake.shortsCalls).toHaveLength(1); const bars = fake.barsCalls[0]!; const shorts = fake.shortsCalls[0]!; expect(bars.timeframe).toBe('1d'); expect(bars.scope).toBe('vault_fenced'); expect(bars.adjustment).toBe('split'); expect(bars.from).toBe(shorts.from); expect(bars.to).toBe(shorts.to); expect(bars.asOf).toBe(shorts.asOf); expect(bars.listingIds).toEqual(shorts.listingIds); const lastAllowed = new Date(fixture.cutoffTs - 1).toISOString().replace('Z', '999Z'); expect(bars.to).toBe(lastAllowed); expect(bars.asOf).toBe(lastAllowed); const defaulted = createStore(fixture); await call({ store: defaulted.store, ledger: createLedger().executor, cutoffTs: fixture.cutoffTs, args: baseArgs(fixture), }); expect(defaulted.barsCalls[0]?.adjustment).toBe('raw'); }); test('named universe: one snapshot lookup before from; resolved IDs are sorted and deduplicated before the store query', async () => { const fixture = buildFixture(); const shuffled = [...fixture.listingIds].reverse(); const fake = createStore(fixture, { universe: () => [...shuffled, fixture.listingIds[0]!, fixture.listingIds[1]!], }); const ledger = createLedger(); const args = { ...baseArgs(fixture), universe: 'CA_EQ' } as Record; delete args.listingIds; const res = await call({ store: fake.store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, args }); expect(res.isError).toBe(false); expect(fake.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-31' }]); expect(fake.barsCalls[0]?.listingIds).toEqual(fixture.listingIds); expect(fake.shortsCalls[0]?.listingIds).toEqual(fixture.listingIds); const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; expect(payload.listingCount).toBe(fixture.listingIds.length); }); test('named-universe expression hash differs from the same IDs selected explicitly', async () => { const fixture = buildFixture(); const explicitLedger = createLedger(); await call({ store: createStore(fixture).store, ledger: explicitLedger.executor, cutoffTs: fixture.cutoffTs, args: baseArgs(fixture), }); const universeLedger = createLedger(); const args = { ...baseArgs(fixture), universe: 'CA_EQ' } as Record; delete args.listingIds; await call({ store: createStore(fixture, { universe: () => fixture.listingIds }).store, ledger: universeLedger.executor, cutoffTs: fixture.cutoffTs, args, }); expect(explicitLedger.rows).toHaveLength(1); expect(universeLedger.rows).toHaveLength(1); expect(universeLedger.rows[0]!.expression_hash).not.toBe(explicitLedger.rows[0]!.expression_hash); expect(universeLedger.rows[0]!.daily_series).toEqual(explicitLedger.rows[0]!.daily_series); }); test('maxSignalAgeSessions is applied to the panel and changes the expression hash', async () => { const fixture = buildFixture(); const run = async (extra: Record) => { const ledger = createLedger(); const res = await call({ store: createStore(fixture).store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, args: { ...baseArgs(fixture), ...extra }, }); return { payload: JSON.parse(res.text) as AnalyzeSignalResultPayload, ledger }; }; const unbounded = await run({}); const capped = await run({ maxSignalAgeSessions: 3 }); expect(unbounded.payload.panelDiagnostics.droppedStaleSignal).toBe(0); expect(capped.payload.panelDiagnostics.droppedStaleSignal).toBeGreaterThan(0); expect(capped.payload.status).toBe('ok'); expect(capped.ledger.rows[0]!.expression_hash).not.toBe(unbounded.ledger.rows[0]!.expression_hash); }); test('replaying the same request on one ledger appends a second row with the same hash and grows the DSR cluster', async () => { const fixture = buildFixture(); const ledger = createLedger(); const first = await call({ store: createStore(fixture).store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, args: baseArgs(fixture), }); const second = await call({ store: createStore(fixture).store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, args: baseArgs(fixture), }); const p1 = JSON.parse(first.text) as AnalyzeSignalResultPayload; const p2 = JSON.parse(second.text) as AnalyzeSignalResultPayload; if (p1.status !== 'ok' || p2.status !== 'ok') { throw new Error('expected ok'); } expect(ledger.rows).toHaveLength(2); expect(p2.trial.expressionHash).toBe(p1.trial.expressionHash); expect(p2.trial.trialId).not.toBe(p1.trial.trialId); expect(p1.deflatedSharpe.clusterSize).toBe(1); expect(p2.deflatedSharpe.clusterSize).toBe(2); }); test('operator principal is accepted and recorded; caller cannot change it', async () => { const fixture = buildFixture(); const ledger = createLedger(); const res = await call({ store: createStore(fixture).store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, principalId: 'operator', args: baseArgs(fixture), }); expect(res.isError).toBe(false); expect(ledger.rows.map(r => r.principal_id)).toEqual(['operator']); }); test('unsupported universe refs accept equity market labels but reject FX before any store call', async () => { const fixture = buildFixture(); const args = { ...baseArgs(fixture), universe: 'TSX_COMPOSITE' } as Record; delete args.listingIds; const okStore = createStore(fixture, { universe: () => fixture.listingIds }); const ok = await call({ store: okStore.store, ledger: createLedger().executor, cutoffTs: fixture.cutoffTs, args }); expect(ok.isError).toBe(false); expect(okStore.universeCalls[0]?.ref).toBe('TSX_COMPOSITE'); const fxStore = createStore(fixture); const fxLedger = createLedger(); const fx = await call({ store: fxStore.store, ledger: fxLedger.executor, cutoffTs: fixture.cutoffTs, args: { ...args, universeMarket: 'FX' }, }); expect(JSON.parse(fx.raw).error ?? JSON.parse(fx.raw).result?.isError).toBeTruthy(); expect(fxStore.universeCalls).toHaveLength(0); expect(fxStore.barsCalls).toHaveLength(0); expect(fxLedger.rows).toHaveLength(0); }); }); describe('analyze_signal QA: factory validation and error sanitisation', () => { test('factory rejects invalid principal, ledger, store and cutoff without touching the store', () => { const fixture = buildFixture(); const fake = createStore(fixture); const ledger = createLedger().executor; const vaultContext = { vaultCutoffTs: fixture.cutoffTs }; expect(() => createAnalyzeSignalTool({ store: fake.store, ledger, vaultContext, principalId: 'agent:not-a-uuid' }) ).toThrow(TrialLedgerError); expect(() => createAnalyzeSignalTool({ store: fake.store, ledger: {} as TrialLedgerExecutor, vaultContext, principalId: AGENT_PRINCIPAL, }) ).toThrow(); expect(() => createAnalyzeSignalTool({ store: { bars: fake.store.bars } as unknown as MarketDataStore, ledger, vaultContext, principalId: AGENT_PRINCIPAL, }) ).toThrow(MarketDataStoreValidationError); for (const bad of [Number.NaN, 1.5, Number.POSITIVE_INFINITY, undefined]) { expect(() => createAnalyzeSignalTool({ store: fake.store, ledger, vaultContext: { vaultCutoffTs: bad as number }, principalId: AGENT_PRINCIPAL, }) ).toThrow(MarketDataStoreValidationError); } expect(fake.barsCalls).toHaveLength(0); expect(fake.universeCalls).toHaveLength(0); }); test('unknown errors, non-Error throws and unsafe validation fields return fixed generic text with no secrets', async () => { const fixture = buildFixture(); const secret = 'SELECT * FROM bars_1d WHERE x; /srv/data/parquet/bars.parquet postgres://user:pass@host:5432/db'; const cases: readonly [string, Parameters[1], { insertThrow?: unknown } | undefined, string][] = [ ['plain Error from bars stream', { barsThrow: new Error(secret) }, undefined, 'Error: Tool execution failed.'], ['string thrown from shortsAsOf', { shortsThrow: secret }, undefined, 'Error: Tool execution failed.'], [ 'validation error with unsafe field name', { shortsThrow: new MarketDataStoreValidationError(secret, secret) }, undefined, 'MarketDataStoreValidationError: Query parameters failed store validation.', ], [ 'not-implemented error for unknown method', { barsThrow: new MarketDataStoreNotImplementedError(secret as never) }, undefined, 'MarketDataStoreNotImplementedError: Requested store operation is not supported.', ], ['plain Error from ledger insert', undefined, { insertThrow: new Error(secret) }, 'Error: Tool execution failed.'], [ 'unmapped TrialLedgerError code', undefined, { insertThrow: new TrialLedgerError('INVALID_ROW', secret) }, 'TrialLedgerError: Trial ledger operation failed.', ], ]; for (const [label, storeOpts, ledgerOpts, expected] of cases) { const ledger = createLedger(ledgerOpts); const res = await call({ store: createStore(fixture, storeOpts).store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, args: baseArgs(fixture), }); expect(res.isError, label).toBe(true); expect(res.text, label).toBe(expected); for (const fragment of ['SELECT', 'bars_1d', '/srv/data', 'postgres://', 'user:pass', 'stack']) { expect(res.raw.includes(fragment), `${label}: ${fragment}`).toBe(false); } expect(ledger.rows, label).toHaveLength(0); } }); test('a poison bar forwarded to the panel builder directly throws, proving the sentinel is meaningful', () => { const fixture = buildFixture(); const ts = utcMs(fixture.allDates[10]!, 21); expect(() => buildForwardReturnPanel({ bars: [...fixture.bars.filter(b => b.ts < fixture.cutoffTs), poisonBar(fixture.listingIds[0]!, ts + 1, ts + 1)], signals: [], horizonSessions: 5, vaultCutoffDate: fixture.cutoffDate, }) ).toThrow(SignalPanelError); }); });