/** * Bar-derived {@link SessionDatesPort} adapter for the MCP copilot `event_study` * exchange-calendar resolver (`createExchangeCalendarResolver`). * * Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare * `process` access, no `pg` dependency, and no DuckDB driver import. * * Daily bar timestamp convention: * - In `libs/research/src/market-data-store-duckdb.ts`, `planBars1dQuery` * projects `epoch_ms(b.ts) AS ts` and `mapBarRows` validates it as an integer * UTC epoch millisecond value on `BarRecord.ts`. * - In `tools/curate-etl/src/curate_bars.rs`, curated daily bars are stamped at * `16:00:00 America/New_York` (`16:00 ET`), which converts to `20:00:00Z` * (EDT) or `21:00:00Z` (EST) on the same UTC calendar date. * - Therefore, `Math.floor(bar.ts / MS_PER_DAY)` yields the session's integer * UTC day key (`formatDayKeyUtc`). Close timestamps and optional early-close * overrides remain owned by `createExchangeCalendarResolver`. * * Vault fence behavior: * - Queries `store.bars` with `timeframe: '1d'` and `adjustment: 'raw'`, * omitting `scope` and `asOf` so the injected store applies its default * `'vault_fenced'` scope. Never passes `'vault_evaluation_only'`. * - Errors thrown by the store (including `VaultHoldoutFenceError`) propagate * unchanged. */ import type { MarketDataStore } from '../../market-data-store'; import { MS_PER_DAY, formatDayKeyUtc, isPlainRecord, isValidEpochMs, isValidInt32, parseCalendarDayKey, } from '../../panel-shared'; import type { SessionDatesPort, SessionDatesQuery } from './exchange-calendars'; /** Error codes thrown by {@link BarSessionDatesError}. */ export type BarSessionDatesErrorCode = | 'invalid_options' | 'unknown_calendar' | 'invalid_query' | 'invalid_bar'; /** Optional error constructor metadata for {@link BarSessionDatesError}. */ export interface BarSessionDatesErrorOptions { readonly cause?: unknown; } /** Typed fail-closed error thrown by {@link createBarSessionDatesPort}. */ export class BarSessionDatesError extends RangeError { readonly code: BarSessionDatesErrorCode; override readonly cause?: unknown; constructor( code: BarSessionDatesErrorCode, message: string, options?: BarSessionDatesErrorOptions ) { super(message, options?.cause !== undefined ? { cause: options.cause } : undefined); this.name = 'BarSessionDatesError'; this.code = code; if (options?.cause !== undefined) { this.cause = options.cause; } Object.setPrototypeOf(this, new.target.prototype); } } /** Factory options for {@link createBarSessionDatesPort}. */ export interface BarSessionDatesPortOptions { readonly store: Pick; /** * Caller-configured reference listing IDs per `exchange.calendar_code` * (e.g. `XNYS`, `XTSE`). The union of their daily bars defines the exchange's * session dates. */ readonly referenceListingIds: Readonly>; } interface CalendarReferenceConfig { readonly listingIds: readonly number[]; readonly listingIdSet: ReadonlySet; } function isPlainObjectRecord(value: unknown): value is Record { if (typeof value !== 'object' || value === null) { return false; } const proto: unknown = Object.getPrototypeOf(value); return proto === Object.prototype || proto === null; } function parseQueryDayKey(value: unknown, field: string): number { return parseCalendarDayKey(value, field, (message, cause) => new BarSessionDatesError( 'invalid_query', message, cause !== undefined ? { cause } : undefined ) ); } function validateOptions(options: BarSessionDatesPortOptions): { readonly store: Pick; readonly calendars: ReadonlyMap; } { if (!isPlainRecord(options)) { throw new BarSessionDatesError( 'invalid_options', 'Invalid options: expected an object with store and referenceListingIds.' ); } const { store, referenceListingIds } = options; if (typeof store !== 'object' || store === null || typeof store.bars !== 'function') { throw new BarSessionDatesError( 'invalid_options', 'Invalid "store": expected an object with a callable bars(query) method.' ); } if (!isPlainObjectRecord(referenceListingIds)) { throw new BarSessionDatesError( 'invalid_options', 'Invalid "referenceListingIds": expected a plain object mapping calendar codes to positive INT32 listing ID arrays.' ); } const calendars = new Map(); const entries = Object.entries(referenceListingIds); for (let i = 0; i < entries.length; i += 1) { const [calendarCode, rawIds] = entries[i] as [string, unknown]; if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) { throw new BarSessionDatesError( 'invalid_options', `Invalid "referenceListingIds" calendar code "${calendarCode}": expected a non-empty trimmed string.` ); } if (!Array.isArray(rawIds) || rawIds.length === 0) { throw new BarSessionDatesError( 'invalid_options', `Invalid "referenceListingIds.${calendarCode}": expected a non-empty array of positive 32-bit integer listing IDs.` ); } const copiedIds: number[] = []; const idSet = new Set(); for (let j = 0; j < rawIds.length; j += 1) { const id: unknown = rawIds[j]; if (!isValidInt32(id) || id <= 0) { throw new BarSessionDatesError( 'invalid_options', `Invalid "referenceListingIds.${calendarCode}[${j}]": expected a positive 32-bit integer, got ${String(id)}.` ); } if (idSet.has(id)) { throw new BarSessionDatesError( 'invalid_options', `Duplicate listing ID ${id} in "referenceListingIds.${calendarCode}".` ); } idSet.add(id); copiedIds.push(id); } calendars.set(calendarCode, { listingIds: copiedIds, listingIdSet: idSet, }); } return { store, calendars }; } /** * Creates a {@link SessionDatesPort} backed by Vault-fenced daily bars * (`timeframe: '1d'`, `adjustment: 'raw'`) for caller-configured reference * listings per `exchange.calendar_code`. */ export function createBarSessionDatesPort( options: BarSessionDatesPortOptions ): SessionDatesPort { const { store, calendars } = validateOptions(options); return { async listSessionDates(query: SessionDatesQuery): Promise { if (!isPlainRecord(query)) { throw new BarSessionDatesError( 'invalid_query', 'Invalid query: expected an object with calendarCode, fromDate, and toDate.' ); } if (typeof query.calendarCode !== 'string') { throw new BarSessionDatesError( 'invalid_query', 'Invalid "calendarCode": expected a string.' ); } const config = calendars.get(query.calendarCode); if (config === undefined) { throw new BarSessionDatesError( 'unknown_calendar', `No reference listings configured for calendarCode "${query.calendarCode}".` ); } const fromDayKey = parseQueryDayKey(query.fromDate, 'fromDate'); const toDayKey = parseQueryDayKey(query.toDate, 'toDate'); if (fromDayKey > toDayKey) { throw new BarSessionDatesError( 'invalid_query', `Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".` ); } const dayKeys = new Set(); const stream = store.bars({ listingIds: config.listingIds.slice(), timeframe: '1d', from: query.fromDate, to: query.toDate, adjustment: 'raw', }); for await (const batch of stream) { if (!isPlainRecord(batch) || !Array.isArray(batch.rows)) { throw new BarSessionDatesError( 'invalid_bar', 'Invalid bar batch: expected an object with a rows array.' ); } const rows = batch.rows; for (let i = 0; i < rows.length; i += 1) { const bar: unknown = rows[i]; if (!isPlainRecord(bar)) { throw new BarSessionDatesError( 'invalid_bar', `Invalid bar row at index ${i}: expected a plain object.` ); } if (!isValidEpochMs(bar.ts)) { throw new BarSessionDatesError( 'invalid_bar', `Invalid bar timestamp at index ${i}: expected a finite integer epoch ms, got ${String(bar.ts)}.` ); } if (!isValidInt32(bar.listingId) || !config.listingIdSet.has(bar.listingId)) { throw new BarSessionDatesError( 'invalid_bar', `Unexpected bar listingId ${String(bar.listingId)} for calendarCode "${query.calendarCode}".` ); } const dayKey = Math.floor(bar.ts / MS_PER_DAY); if (dayKey >= fromDayKey && dayKey <= toDayKey) { dayKeys.add(dayKey); } } } if (dayKeys.size === 0) { return []; } const sortedDayKeys = Array.from(dayKeys).sort((a, b) => a - b); return sortedDayKeys.map(formatDayKeyUtc); }, }; }