diff --git a/libs/research/README.md b/libs/research/README.md index e5fd65e5..96a62b74 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -271,6 +271,12 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **Atomic idempotency & autocommit requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass an autocommit, fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` or explicit `BEGIN` transaction unless the executor rolls back a `SAVEPOINT` before rethrowing errors) so concurrent callers observe the committed winner and `23505` retry lookups do not hit `25P02`. - **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`) for ASCII queries, and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`) for ASCII provider filters while retaining non-ASCII stored rows as candidates (and omitting SQL casing filters for non-ASCII selectors), then applying JavaScript `.toLowerCase()` matching after row validation so PostgreSQL libc/C collation casing (e.g., Greek final sigma or `BİST` / `K`) never drops `read_knowledge` matches. All eligible rows are returned ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing. +### Exchange Calendar Resolver + +- **`createPostgresListingCalendarPort({ executor, schema? })`** and **`createExchangeCalendarResolver({ listingCalendars, sessionDates, earlyCloses? })`** (exported from `@stock-bot/research/mcp` alongside `ListingCalendarPort`, `SessionDatesPort`, `EarlyCloseOverrides`, `PostgresListingCalendarError`, and `ExchangeCalendarResolverError`) implement `EventStudyExchangeCalendarResolver` for `createEventStudyTool` with zero `node:*` imports and zero runtime `pg` dependency. +- **Injected ports & fail-closed validation:** `createPostgresListingCalendarPort` issues one read-only parameterized `SELECT` joining `listing.mic` to `exchange.mic` (`WHERE l.listing_id = ANY($1::integer[])`), validating `executor.query` (`INVALID_EXECUTOR`), optional `schema` (`^[a-z_][a-z0-9_]*$`, `INVALID_SCHEMA`), and returned rows (`INVALID_ROW`). `SessionDatesPort.listSessionDates({ calendarCode, fromDate, toDate })` is called once per distinct calendar code in sorted order; the resolver fails closed with no partial result on missing, unrequested, or conflicting listing mappings or on malformed, duplicate, unsorted, or out-of-window session dates. Empty `listingIds` returns empty `{ calendars, listingCalendarId }` with zero port calls. +- **Supported DST range & default half-day close:** Session close timestamps convert Eastern Time (`America/New_York` / `America/Toronto`) to UTC epoch milliseconds across `1976-01-01` through `2030-12-31` inclusive (matching `tools/curate-etl/src/session_close.rs` across the `1976–1986`, `1987–2006`, and `2007–2030` DST eras) and throw `ExchangeCalendarResolverError('UNSUPPORTED_DATE')` outside that range. Optional `earlyCloses` (`{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, integer minutes in `1..=960`, e.g. `780` for `13:00 ET`) overrides the close on listed dates; when `earlyCloses` is omitted, every session closes at `16:00 ET` and exchange half-days are treated as full `16:00 ET` trading days. + ### Copilot Server - **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions. diff --git a/libs/research/src/mcp/adapters/exchange-calendars.ts b/libs/research/src/mcp/adapters/exchange-calendars.ts new file mode 100644 index 00000000..c9cf3872 --- /dev/null +++ b/libs/research/src/mcp/adapters/exchange-calendars.ts @@ -0,0 +1,741 @@ +/** + * Exchange-calendar resolver and read-only PostgreSQL listing-calendar adapter + * for the MCP copilot `event_study` tool (`EventStudyExchangeCalendarResolver`). + * + * Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare + * `process` access, and no runtime `pg` dependency. + * + * Eastern Time DST schedule (`1976-01-01..=2030-12-31`, matching + * `tools/curate-etl/src/session_close.rs` for `America/New_York` / + * `America/Toronto`): + * - `1976..=1986`: last Sunday of April -> last Sunday of October. + * - `1987..=2006`: first Sunday of April -> last Sunday of October. + * - `2007..=2030`: second Sunday of March -> first Sunday of November. + * + * Using the session-date convention (inclusive spring boundary, exclusive fall + * boundary), EDT is `UTC-4` and EST is `UTC-5`. + */ + +import type { + EventStudyExchangeCalendars, + ExchangeSessionClose, +} from '../../event-panel'; +import { + MS_PER_DAY, + isPlainRecord, + isValidInt32, + parseCalendarDayKey, +} from '../../panel-shared'; +import type { + EventStudyExchangeCalendarQuery, + EventStudyExchangeCalendarResolver, +} from '../tools/event-study'; + +const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; +const MS_PER_MINUTE = 60_000; +const EDT_UTC_OFFSET_MINUTES = 4 * 60; +const EST_UTC_OFFSET_MINUTES = 5 * 60; + +/** First Gregorian year supported by the Eastern Time DST schedule. */ +export const EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR = 1976; + +/** Last Gregorian year supported by the Eastern Time DST schedule. */ +export const EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR = 2030; + +/** Inclusive lower bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */ +export const EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE = '1976-01-01'; + +/** Inclusive upper bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */ +export const EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE = '2030-12-31'; + +/** Default Eastern Time close minute of day (`16:00 ET` = `960`). */ +export const EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET = 16 * 60; + +/** Minimum allowed Eastern Time early-close override minute of day (`00:01 ET`). */ +export const EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET = 1; + +/** Maximum allowed Eastern Time close minute of day (`16:00 ET`). */ +export const EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET = 16 * 60; + +/** Epoch day for `1976-01-01` (`Date.UTC(1976, 0, 1) / MS_PER_DAY`). */ +const MIN_SUPPORTED_DAY_KEY = 2_191; + +/** Epoch day for `2030-12-31` (`Date.UTC(2030, 11, 31) / MS_PER_DAY`). */ +const MAX_SUPPORTED_DAY_KEY = 22_279; + +const SUPPORTED_YEAR_COUNT = + EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR + 1; + +/** Error codes thrown by {@link PostgresListingCalendarError}. */ +export type PostgresListingCalendarErrorCode = + | 'INVALID_EXECUTOR' + | 'INVALID_SCHEMA' + | 'INVALID_ROW'; + +/** Typed validation error thrown by the PostgreSQL listing-calendar adapter. */ +export class PostgresListingCalendarError extends RangeError { + readonly code: PostgresListingCalendarErrorCode; + + constructor(code: PostgresListingCalendarErrorCode, message: string) { + super(message); + this.name = 'PostgresListingCalendarError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Error codes thrown by {@link ExchangeCalendarResolverError}. */ +export type ExchangeCalendarResolverErrorCode = + | 'INVALID_OPTION' + | 'INVALID_QUERY' + | 'UNSUPPORTED_DATE' + | 'INVALID_LISTING_CALENDAR_ROW' + | 'MISSING_LISTING_CALENDAR' + | 'UNEXPECTED_LISTING_CALENDAR' + | 'CONFLICTING_LISTING_CALENDAR' + | 'INVALID_SESSION_DATES'; + +/** Optional error constructor metadata for {@link ExchangeCalendarResolverError}. */ +export interface ExchangeCalendarResolverErrorOptions { + readonly cause?: unknown; +} + +/** Typed validation and fail-closed integrity error thrown by {@link createExchangeCalendarResolver}. */ +export class ExchangeCalendarResolverError extends RangeError { + readonly code: ExchangeCalendarResolverErrorCode; + override readonly cause?: unknown; + + constructor( + code: ExchangeCalendarResolverErrorCode, + message: string, + options?: ExchangeCalendarResolverErrorOptions + ) { + super(message, options?.cause !== undefined ? { cause: options.cause } : undefined); + this.name = 'ExchangeCalendarResolverError'; + this.code = code; + if (options?.cause !== undefined) { + this.cause = options.cause; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** + * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module + * has no runtime dependency on `pg` and is unit-testable with a fake executor. + */ +export interface ListingCalendarExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** Factory options for {@link createPostgresListingCalendarPort}. */ +export interface PostgresListingCalendarPortOptions { + readonly executor: ListingCalendarExecutor; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; +} + +/** One listing-to-exchange-calendar mapping row returned by {@link ListingCalendarPort}. */ +export interface ListingCalendarRow { + readonly listingId: number; + readonly calendarCode: string; +} + +/** Injected port resolving `listingId` -> `exchange.calendar_code`. */ +export interface ListingCalendarPort { + getListingCalendars( + listingIds: readonly number[] + ): Promise | readonly ListingCalendarRow[]; +} + +/** Query passed to {@link SessionDatesPort.listSessionDates}. */ +export interface SessionDatesQuery { + readonly calendarCode: string; + readonly fromDate: string; + readonly toDate: string; +} + +/** + * Injected port supplying strictly ascending, unique `YYYY-MM-DD` exchange session + * dates inside `[fromDate, toDate]` for one exchange calendar code. + */ +export interface SessionDatesPort { + listSessionDates(query: SessionDatesQuery): Promise | readonly string[]; +} + +/** + * Optional caller-supplied early-close overrides keyed by + * `{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, where + * `minuteOfDayEastern` is an integer in `(0, 960]` (e.g. `780` = `13:00 ET`). + */ +export type EarlyCloseOverrides = Readonly>>>; + +/** Factory options for {@link createExchangeCalendarResolver}. */ +export interface ExchangeCalendarResolverOptions { + readonly listingCalendars: ListingCalendarPort; + readonly sessionDates: SessionDatesPort; + readonly earlyCloses?: EarlyCloseOverrides; +} + +interface RawListingCalendarRow { + readonly listing_id: unknown; + readonly calendar_code: unknown; +} + +interface DstBoundsTable { + readonly startDay: Int32Array; + readonly endDay: Int32Array; +} + +let cachedDstBounds: DstBoundsTable | null = null; + +/** ISO-8601 weekday for an epoch day: `1 = Monday`, ..., `7 = Sunday`. */ +function isoWeekday(epochDay: number): number { + // 1970-01-01 (epochDay === 0) was Thursday (ISO 4). + return (((epochDay + 3) % 7) + 7) % 7 + 1; +} + +function ymdToEpochDay(year: number, month: number, day: number): number { + return Date.UTC(year, month - 1, day) / MS_PER_DAY; +} + +function nthSundayOfMonth(year: number, month: number, nth: number): number { + const first = ymdToEpochDay(year, month, 1); + const firstWd = isoWeekday(first); + const delta = (7 - firstWd) % 7; + return first + delta + (nth - 1) * 7; +} + +function lastSundayOfMonth(year: number, month: number): number { + const nextYear = month === 12 ? year + 1 : year; + const nextMonth = month === 12 ? 1 : month + 1; + const last = ymdToEpochDay(nextYear, nextMonth, 1) - 1; + const lastWd = isoWeekday(last); + return last - (lastWd % 7); +} + +function getDstBoundsTable(): DstBoundsTable { + if (cachedDstBounds !== null) { + return cachedDstBounds; + } + + const startDay = new Int32Array(SUPPORTED_YEAR_COUNT); + const endDay = new Int32Array(SUPPORTED_YEAR_COUNT); + + for ( + let year = EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR; + year <= EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR; + year += 1 + ) { + let dstStart: number; + let dstEnd: number; + if (year <= 1986) { + dstStart = lastSundayOfMonth(year, 4); + dstEnd = lastSundayOfMonth(year, 10); + } else if (year <= 2006) { + dstStart = nthSundayOfMonth(year, 4, 1); + dstEnd = lastSundayOfMonth(year, 10); + } else { + dstStart = nthSundayOfMonth(year, 3, 2); + dstEnd = nthSundayOfMonth(year, 11, 1); + } + const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR; + startDay[idx] = dstStart; + endDay[idx] = dstEnd; + } + + cachedDstBounds = { startDay, endDay }; + return cachedDstBounds; +} + +function assertSupportedDayKey(dayKey: number, dateStr: string, field: string): void { + if (dayKey < MIN_SUPPORTED_DAY_KEY || dayKey > MAX_SUPPORTED_DAY_KEY) { + throw new ExchangeCalendarResolverError( + 'UNSUPPORTED_DATE', + `Unsupported "${field}" date "${dateStr}": must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.` + ); + } +} + +function easternSessionCloseUtcMs(dayKey: number, closeMinuteEt: number): number { + const year = new Date(dayKey * MS_PER_DAY).getUTCFullYear(); + const table = getDstBoundsTable(); + const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR; + const isEdt = + dayKey >= (table.startDay[idx] as number) && dayKey < (table.endDay[idx] as number); + const utcOffsetMinutes = isEdt ? EDT_UTC_OFFSET_MINUTES : EST_UTC_OFFSET_MINUTES; + return dayKey * MS_PER_DAY + (closeMinuteEt + utcOffsetMinutes) * MS_PER_MINUTE; +} + +function defineDataProperty(target: Record, key: string, value: T): void { + Object.defineProperty(target, key, { + value, + enumerable: true, + writable: true, + configurable: true, + }); +} + +function buildListingCalendarSql(schemaPrefix: string): string { + const listingTable = `${schemaPrefix}listing`; + const exchangeTable = `${schemaPrefix}exchange`; + + return [ + 'SELECT', + ' l.listing_id AS listing_id,', + ' e.calendar_code AS calendar_code', + `FROM ${listingTable} l`, + `INNER JOIN ${exchangeTable} e ON e.mic = l.mic`, + 'WHERE l.listing_id = ANY($1::integer[])', + 'ORDER BY l.listing_id ASC', + ].join('\n'); +} + +function validatePostgresFactoryOptions(options: PostgresListingCalendarPortOptions): { + readonly executor: ListingCalendarExecutor; + readonly schemaPrefix: string; +} { + if (typeof options !== 'object' || options === null) { + throw new PostgresListingCalendarError( + 'INVALID_EXECUTOR', + 'Invalid options: expected an object with a ListingCalendarExecutor.' + ); + } + + const { executor, schema } = options; + if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { + throw new PostgresListingCalendarError( + 'INVALID_EXECUTOR', + 'Invalid executor: expected an object with a callable query(text, params?) method.' + ); + } + + if (schema === undefined) { + return { executor, schemaPrefix: '' }; + } + + if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) { + throw new PostgresListingCalendarError( + 'INVALID_SCHEMA', + 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' + ); + } + + return { executor, schemaPrefix: `"${schema}".` }; +} + +function mapRawListingCalendarRow(raw: unknown): ListingCalendarRow { + if (!isPlainRecord(raw)) { + throw new PostgresListingCalendarError( + 'INVALID_ROW', + 'Invalid security-master row: expected a non-null plain object.' + ); + } + + const row = raw as unknown as RawListingCalendarRow; + if (!isValidInt32(row.listing_id)) { + throw new PostgresListingCalendarError( + 'INVALID_ROW', + 'Invalid security-master row: "listing_id" must be a safe 32-bit integer.' + ); + } + + if (typeof row.calendar_code !== 'string' || row.calendar_code.trim().length === 0) { + throw new PostgresListingCalendarError( + 'INVALID_ROW', + 'Invalid security-master row: "calendar_code" must be a non-empty string.' + ); + } + + return { + listingId: row.listing_id, + calendarCode: row.calendar_code.trim(), + }; +} + +/** + * Creates a read-only PostgreSQL {@link ListingCalendarPort} backed by the M1 + * security master (`listing` joined to `exchange` on `mic`), binding listing IDs + * as a single `$1::integer[]` parameter. + */ +export function createPostgresListingCalendarPort( + options: PostgresListingCalendarPortOptions +): ListingCalendarPort { + const { executor, schemaPrefix } = validatePostgresFactoryOptions(options); + const sql = buildListingCalendarSql(schemaPrefix); + + return { + async getListingCalendars( + listingIds: readonly number[] + ): Promise { + if (!Array.isArray(listingIds)) { + throw new PostgresListingCalendarError( + 'INVALID_ROW', + 'Invalid listingIds: expected an array of 32-bit integers.' + ); + } + + const boundIds: number[] = []; + for (let i = 0; i < listingIds.length; i += 1) { + const id = listingIds[i]; + if (!isValidInt32(id)) { + throw new PostgresListingCalendarError( + 'INVALID_ROW', + `Invalid listingIds[${i}]: expected a safe 32-bit integer.` + ); + } + boundIds.push(id); + } + + if (boundIds.length === 0) { + return []; + } + + const result = await executor.query(sql, [boundIds]); + if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { + throw new PostgresListingCalendarError( + 'INVALID_ROW', + 'Invalid executor response: expected an object with a rows array.' + ); + } + + const mapped: ListingCalendarRow[] = []; + for (let i = 0; i < result.rows.length; i += 1) { + mapped.push(mapRawListingCalendarRow(result.rows[i])); + } + return mapped; + }, + }; +} + +function parseResolverDayKey( + value: unknown, + field: string, + code: 'INVALID_OPTION' | 'INVALID_QUERY' | 'INVALID_SESSION_DATES' +): number { + return parseCalendarDayKey(value, field, (message, cause) => + new ExchangeCalendarResolverError( + code, + message, + cause !== undefined ? { cause } : undefined + ) + ); +} + +function parseEarlyCloses( + raw: unknown +): Map> { + const result = new Map>(); + if (raw === undefined) { + return result; + } + if (!isPlainRecord(raw)) { + throw new ExchangeCalendarResolverError( + 'INVALID_OPTION', + 'Invalid "earlyCloses": expected a plain object mapping calendarCode to { [YYYY-MM-DD]: minuteOfDay }.' + ); + } + + const calendarEntries = Object.entries(raw); + for (let i = 0; i < calendarEntries.length; i += 1) { + const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown]; + if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) { + throw new ExchangeCalendarResolverError( + 'INVALID_OPTION', + `Invalid "earlyCloses" calendar code "${calendarCode}": expected a non-blank trimmed string.` + ); + } + if (!isPlainRecord(rawDates)) { + throw new ExchangeCalendarResolverError( + 'INVALID_OPTION', + `Invalid "earlyCloses.${calendarCode}": expected a plain object mapping YYYY-MM-DD dates to Eastern close minutes.` + ); + } + + const dateOverrides = new Map(); + const dateEntries = Object.entries(rawDates); + for (let j = 0; j < dateEntries.length; j += 1) { + const [dateStr, minute] = dateEntries[j] as [string, unknown]; + const field = `earlyCloses.${calendarCode}["${dateStr}"]`; + const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_OPTION'); + assertSupportedDayKey(dayKey, dateStr, field); + + if ( + typeof minute !== 'number' || + !Number.isSafeInteger(minute) || + minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET || + minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET + ) { + throw new ExchangeCalendarResolverError( + 'INVALID_OPTION', + `Invalid "${field}": expected an integer Eastern minute in (${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET - 1}, ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}], got ${String(minute)}.` + ); + } + + dateOverrides.set(dateStr, minute); + } + result.set(calendarCode, dateOverrides); + } + + return result; +} + +function validateResolverOptions(options: ExchangeCalendarResolverOptions): { + readonly listingCalendars: ListingCalendarPort; + readonly sessionDates: SessionDatesPort; + readonly earlyCloseMap: Map>; +} { + if (!isPlainRecord(options)) { + throw new ExchangeCalendarResolverError( + 'INVALID_OPTION', + 'Invalid options: expected an object with listingCalendars and sessionDates ports.' + ); + } + + const { listingCalendars, sessionDates, earlyCloses } = options; + if ( + typeof listingCalendars !== 'object' || + listingCalendars === null || + typeof listingCalendars.getListingCalendars !== 'function' + ) { + throw new ExchangeCalendarResolverError( + 'INVALID_OPTION', + 'Invalid "listingCalendars": expected an object with a callable getListingCalendars(listingIds) method.' + ); + } + + if ( + typeof sessionDates !== 'object' || + sessionDates === null || + typeof sessionDates.listSessionDates !== 'function' + ) { + throw new ExchangeCalendarResolverError( + 'INVALID_OPTION', + 'Invalid "sessionDates": expected an object with a callable listSessionDates({ calendarCode, fromDate, toDate }) method.' + ); + } + + const earlyCloseMap = parseEarlyCloses(earlyCloses); + return { listingCalendars, sessionDates, earlyCloseMap }; +} + +function compareAscii(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * Creates an {@link EventStudyExchangeCalendarResolver} over injected + * {@link ListingCalendarPort} and {@link SessionDatesPort} implementations, + * converting each validated exchange session date into its UTC epoch-ms close + * timestamp (`16:00 ET` by default, or caller-supplied `earlyCloses` override). + */ +export function createExchangeCalendarResolver( + options: ExchangeCalendarResolverOptions +): EventStudyExchangeCalendarResolver { + const { listingCalendars, sessionDates, earlyCloseMap } = validateResolverOptions(options); + + return async function resolveExchangeCalendars( + query: EventStudyExchangeCalendarQuery + ): Promise { + if (!isPlainRecord(query)) { + throw new ExchangeCalendarResolverError( + 'INVALID_QUERY', + 'Invalid query: expected a plain object with listingIds, fromDate, and toDate.' + ); + } + + if (!Array.isArray(query.listingIds)) { + throw new ExchangeCalendarResolverError( + 'INVALID_QUERY', + 'Invalid "listingIds": expected an array of 32-bit integer listing IDs.' + ); + } + + if (query.listingIds.length === 0) { + return { + calendars: {}, + listingCalendarId: {}, + }; + } + + const fromDayKey = parseResolverDayKey(query.fromDate, 'fromDate', 'INVALID_QUERY'); + const toDayKey = parseResolverDayKey(query.toDate, 'toDate', 'INVALID_QUERY'); + if (fromDayKey > toDayKey) { + throw new ExchangeCalendarResolverError( + 'INVALID_QUERY', + `Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".` + ); + } + assertSupportedDayKey(fromDayKey, query.fromDate, 'fromDate'); + assertSupportedDayKey(toDayKey, query.toDate, 'toDate'); + + const requestedSet = new Set(); + for (let i = 0; i < query.listingIds.length; i += 1) { + const id: unknown = query.listingIds[i]; + if (!isValidInt32(id)) { + throw new ExchangeCalendarResolverError( + 'INVALID_QUERY', + `Invalid "listingIds[${i}]": expected a safe 32-bit integer.` + ); + } + requestedSet.add(id); + } + + const sortedListingIds = Array.from(requestedSet).sort((a, b) => a - b); + const rawMappings = await listingCalendars.getListingCalendars(sortedListingIds); + if (!Array.isArray(rawMappings)) { + throw new ExchangeCalendarResolverError( + 'INVALID_LISTING_CALENDAR_ROW', + 'Invalid listingCalendars response: expected an array of { listingId, calendarCode } rows.' + ); + } + + const listingToCalendar = new Map(); + for (let i = 0; i < rawMappings.length; i += 1) { + const row: unknown = rawMappings[i]; + if (!isPlainRecord(row)) { + throw new ExchangeCalendarResolverError( + 'INVALID_LISTING_CALENDAR_ROW', + `Invalid listingCalendars[${i}]: expected a plain object.` + ); + } + + const listingId = row.listingId; + const calendarCode = row.calendarCode; + if (!isValidInt32(listingId)) { + throw new ExchangeCalendarResolverError( + 'INVALID_LISTING_CALENDAR_ROW', + `Invalid listingCalendars[${i}].listingId: expected a safe 32-bit integer.` + ); + } + if ( + typeof calendarCode !== 'string' || + calendarCode.trim().length === 0 || + calendarCode !== calendarCode.trim() + ) { + throw new ExchangeCalendarResolverError( + 'INVALID_LISTING_CALENDAR_ROW', + `Invalid listingCalendars[${i}].calendarCode: expected a non-blank trimmed string.` + ); + } + + if (!requestedSet.has(listingId)) { + throw new ExchangeCalendarResolverError( + 'UNEXPECTED_LISTING_CALENDAR', + `Listing calendar port returned unrequested listingId ${listingId}.` + ); + } + + const existing = listingToCalendar.get(listingId); + if (existing !== undefined && existing !== calendarCode) { + throw new ExchangeCalendarResolverError( + 'CONFLICTING_LISTING_CALENDAR', + `Conflicting calendar codes for listingId ${listingId}: "${existing}" vs "${calendarCode}".` + ); + } + listingToCalendar.set(listingId, calendarCode); + } + + const missingIds: number[] = []; + for (let i = 0; i < sortedListingIds.length; i += 1) { + const id = sortedListingIds[i] as number; + if (!listingToCalendar.has(id)) { + missingIds.push(id); + } + } + if (missingIds.length > 0) { + throw new ExchangeCalendarResolverError( + 'MISSING_LISTING_CALENDAR', + `Missing exchange calendar mapping for listingId(s): ${missingIds.join(', ')}.` + ); + } + + const distinctCalendars = Array.from(new Set(listingToCalendar.values())).sort(compareAscii); + const sessionsByCalendar = new Map(); + + for (let c = 0; c < distinctCalendars.length; c += 1) { + const calendarCode = distinctCalendars[c] as string; + const rawDates = await sessionDates.listSessionDates({ + calendarCode, + fromDate: query.fromDate, + toDate: query.toDate, + }); + + if (!Array.isArray(rawDates)) { + throw new ExchangeCalendarResolverError( + 'INVALID_SESSION_DATES', + `Invalid session dates for "${calendarCode}": expected an array of YYYY-MM-DD strings.` + ); + } + + const overrides = earlyCloseMap.get(calendarCode); + const sessions: ExchangeSessionClose[] = []; + let prevDayKey = Number.NEGATIVE_INFINITY; + + for (let i = 0; i < rawDates.length; i += 1) { + const dateStr: unknown = rawDates[i]; + const field = `sessionDates["${calendarCode}"][${i}]`; + const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_SESSION_DATES'); + const validDate = dateStr as string; + assertSupportedDayKey(dayKey, validDate, field); + + if (dayKey < fromDayKey || dayKey > toDayKey) { + throw new ExchangeCalendarResolverError( + 'INVALID_SESSION_DATES', + `Session date "${validDate}" for "${calendarCode}" is outside requested window [${query.fromDate}, ${query.toDate}].` + ); + } + if (dayKey === prevDayKey) { + throw new ExchangeCalendarResolverError( + 'INVALID_SESSION_DATES', + `Duplicate session date "${validDate}" for "${calendarCode}".` + ); + } + if (dayKey < prevDayKey) { + throw new ExchangeCalendarResolverError( + 'INVALID_SESSION_DATES', + `Session dates for "${calendarCode}" must be strictly ascending (saw "${validDate}" out of order).` + ); + } + + prevDayKey = dayKey; + const closeMinuteEt = + overrides?.get(validDate) ?? EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET; + sessions.push({ + date: validDate, + closeTs: easternSessionCloseUtcMs(dayKey, closeMinuteEt), + }); + } + + sessionsByCalendar.set(calendarCode, sessions); + } + + const calendars: Record = {}; + for (let c = 0; c < distinctCalendars.length; c += 1) { + const calendarCode = distinctCalendars[c] as string; + defineDataProperty( + calendars, + calendarCode, + sessionsByCalendar.get(calendarCode) as readonly ExchangeSessionClose[] + ); + } + + const listingCalendarId: Record = {}; + for (let i = 0; i < sortedListingIds.length; i += 1) { + const id = sortedListingIds[i] as number; + defineDataProperty( + listingCalendarId as unknown as Record, + String(id), + listingToCalendar.get(id) as string + ); + } + + return { + calendars, + listingCalendarId, + }; + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index a6aab4ad..af5eb583 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,6 +1,7 @@ export * from './adapters/postgres-findings'; export * from './adapters/postgres-symbol-search'; export * from './adapters/postgres-trial-ref'; +export * from './adapters/exchange-calendars'; export * from './copilot-server'; export * from './protocol'; export * from './server'; diff --git a/libs/research/test/mcp-exchange-calendars.test.ts b/libs/research/test/mcp-exchange-calendars.test.ts new file mode 100644 index 00000000..6526da0d --- /dev/null +++ b/libs/research/test/mcp-exchange-calendars.test.ts @@ -0,0 +1,693 @@ +import { describe, expect, test } from 'bun:test'; +import { type EventObservation, buildEventStudyInput } from '../src/event-panel'; +import type { BarRecord } from '../src/market-data-store'; +import { + EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET, + EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE, + EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE, + ExchangeCalendarResolverError, + type ListingCalendarExecutor, + type ListingCalendarPort, + type ListingCalendarRow, + PostgresListingCalendarError, + type SessionDatesPort, + type SessionDatesQuery, + createExchangeCalendarResolver, + createPostgresListingCalendarPort, +} from '../src/mcp/index'; + +function utcMs( + year: number, + month: number, + day: number, + hour = 0, + minute = 0, + second = 0 +): number { + return Date.UTC(year, month - 1, day, hour, minute, second, 0); +} + +function makeBar(listingId: number, dateStr: string, close: number, closeHourUtc = 21): BarRecord { + const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number]; + const ts = utcMs(y, m, d, closeHourUtc, 0, 0); + return { + listingId, + ts, + open: close, + high: close, + low: close, + close, + volume: 100_000, + knownAt: ts, + }; +} + +describe('createExchangeCalendarResolver — Eastern DST schedule & date bounds', () => { + test('computes exact UTC ms for EDT (2024-07-01 -> 20:00Z) and EST (2024-12-02 -> 21:00Z)', async () => { + const resolver = createExchangeCalendarResolver({ + listingCalendars: { + getListingCalendars: () => [{ listingId: 1, calendarCode: 'XNYS' }], + }, + sessionDates: { + listSessionDates: () => ['2024-07-01', '2024-12-02'], + }, + }); + + const result = await resolver({ + listingIds: [1], + fromDate: '2024-07-01', + toDate: '2024-12-02', + }); + + expect(result.calendars).toEqual({ + XNYS: [ + { date: '2024-07-01', closeTs: utcMs(2024, 7, 1, 20, 0, 0) }, + { date: '2024-12-02', closeTs: utcMs(2024, 12, 2, 21, 0, 0) }, + ], + }); + expect(result.listingCalendarId).toEqual({ 1: 'XNYS' }); + }); + + test('matches session_close.rs DST transition vectors across all three eras (1976, 1987, 2007)', async () => { + const vectors: readonly { + readonly date: string; + readonly expectedUtcHour: number; + }[] = [ + // Era 1 (1976..=1986): last Sunday of April -> last Sunday of October + { date: '1976-04-24', expectedUtcHour: 21 }, // Sat before spring-forward (EST) + { date: '1976-04-25', expectedUtcHour: 20 }, // Last Sun of April (EDT) + { date: '1976-10-30', expectedUtcHour: 20 }, // Sat before fall-back (EDT) + { date: '1976-10-31', expectedUtcHour: 21 }, // Last Sun of October (EST) + // Era 2 (1987..=2006): first Sunday of April -> last Sunday of October + { date: '1987-04-04', expectedUtcHour: 21 }, // Sat before spring-forward (EST) + { date: '1987-04-05', expectedUtcHour: 20 }, // First Sun of April (EDT) + { date: '1987-10-24', expectedUtcHour: 20 }, // Sat before fall-back (EDT) + { date: '1987-10-25', expectedUtcHour: 21 }, // Last Sun of October (EST) + // Era 3 (2007..=2030): second Sunday of March -> first Sunday of November + { date: '2007-03-10', expectedUtcHour: 21 }, // Sat before spring-forward (EST) + { date: '2007-03-11', expectedUtcHour: 20 }, // Second Sun of March (EDT) + { date: '2007-11-03', expectedUtcHour: 20 }, // Sat before fall-back (EDT) + { date: '2007-11-04', expectedUtcHour: 21 }, // First Sun of November (EST) + ]; + + const resolver = createExchangeCalendarResolver({ + listingCalendars: { + getListingCalendars: () => [{ listingId: 10, calendarCode: 'XNYS' }], + }, + sessionDates: { + listSessionDates: () => vectors.map((v) => v.date), + }, + }); + + const result = await resolver({ + listingIds: [10], + fromDate: '1976-04-24', + toDate: '2007-11-04', + }); + + const sessions = (result.calendars as Record) + .XNYS; + expect(sessions).toHaveLength(vectors.length); + + for (let i = 0; i < vectors.length; i += 1) { + const vec = vectors[i] as { date: string; expectedUtcHour: number }; + const [y, m, d] = vec.date.split('-').map(Number) as [number, number, number]; + expect(sessions?.[i]).toEqual({ + date: vec.date, + closeTs: utcMs(y, m, d, vec.expectedUtcHour, 0, 0), + }); + } + }); + + test('supports inclusive endpoints 1976-01-01 and 2030-12-31 and fails closed outside range', async () => { + let listingCalls = 0; + let sessionCalls = 0; + const resolver = createExchangeCalendarResolver({ + listingCalendars: { + getListingCalendars: () => { + listingCalls += 1; + return [{ listingId: 1, calendarCode: 'XNYS' }]; + }, + }, + sessionDates: { + listSessionDates: () => { + sessionCalls += 1; + return [EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE, EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE]; + }, + }, + }); + + const ok = await resolver({ + listingIds: [1], + fromDate: '1976-01-01', + toDate: '2030-12-31', + }); + expect(ok.calendars).toEqual({ + XNYS: [ + { date: '1976-01-01', closeTs: utcMs(1976, 1, 1, 21, 0, 0) }, + { date: '2030-12-31', closeTs: utcMs(2030, 12, 31, 21, 0, 0) }, + ], + }); + expect(listingCalls).toBe(1); + expect(sessionCalls).toBe(1); + + await expect( + resolver({ listingIds: [1], fromDate: '1975-12-31', toDate: '1976-01-02' }) + ).rejects.toThrow(ExchangeCalendarResolverError); + try { + await resolver({ listingIds: [1], fromDate: '1975-12-31', toDate: '1976-01-02' }); + } catch (err) { + expect(err).toBeInstanceOf(ExchangeCalendarResolverError); + expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE'); + } + + try { + await resolver({ listingIds: [1], fromDate: '2030-12-30', toDate: '2031-01-01' }); + expect.unreachable('expected UNSUPPORTED_DATE for 2031-01-01'); + } catch (err) { + expect(err).toBeInstanceOf(ExchangeCalendarResolverError); + expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE'); + } + + // Out-of-range query bounds fail before calling either port. + expect(listingCalls).toBe(1); + expect(sessionCalls).toBe(1); + }); +}); + +describe('createPostgresListingCalendarPort', () => { + test('issues one parameterized SELECT joining listing.mic to exchange.mic with no ID literals or writes', async () => { + const calls: Array<{ text: string; params: readonly unknown[] | undefined }> = []; + const executor: ListingCalendarExecutor = { + async query>(text: string, params?: readonly unknown[]) { + calls.push({ text, params }); + const rows = [ + { listing_id: 101, calendar_code: 'XNYS' }, + { listing_id: 202, calendar_code: 'XTSE' }, + ]; + return { rows: rows as unknown as readonly Row[] }; + }, + }; + + const port = createPostgresListingCalendarPort({ executor }); + const rows = await port.getListingCalendars([101, 202]); + + expect(rows).toEqual([ + { listingId: 101, calendarCode: 'XNYS' }, + { listingId: 202, calendarCode: 'XTSE' }, + ]); + expect(calls).toHaveLength(1); + + const call = calls[0] as { text: string; params: readonly unknown[] | undefined }; + expect(call.text).toContain('SELECT'); + expect(call.text).toContain('FROM listing l'); + expect(call.text).toContain('INNER JOIN exchange e ON e.mic = l.mic'); + expect(call.text).toContain('WHERE l.listing_id = ANY($1::integer[])'); + expect(call.text).not.toContain('101'); + expect(call.text).not.toContain('202'); + expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); + expect(call.params).toEqual([[101, 202]]); + }); + + test('supports optional validated schema qualification and short-circuits empty listingIds', async () => { + const calls: Array<{ text: string; params: readonly unknown[] | undefined }> = []; + const executor: ListingCalendarExecutor = { + async query>(text: string, params?: readonly unknown[]) { + calls.push({ text, params }); + return { rows: [{ listing_id: 7, calendar_code: 'XNYS' }] as unknown as readonly Row[] }; + }, + }; + + const port = createPostgresListingCalendarPort({ executor, schema: 'sec_master_v1' }); + expect(await port.getListingCalendars([])).toEqual([]); + expect(calls).toHaveLength(0); + + const rows = await port.getListingCalendars([7]); + expect(rows).toEqual([{ listingId: 7, calendarCode: 'XNYS' }]); + expect(calls).toHaveLength(1); + expect(calls[0]?.text).toContain('FROM "sec_master_v1".listing l'); + expect(calls[0]?.text).toContain('INNER JOIN "sec_master_v1".exchange e ON e.mic = l.mic'); + }); + + test('throws typed INVALID_EXECUTOR, INVALID_SCHEMA, and INVALID_ROW errors', async () => { + const badExecutors: unknown[] = [null, undefined, {}, { executor: null }, { executor: {} }]; + for (const bad of badExecutors) { + let caught: unknown; + try { + createPostgresListingCalendarPort(bad as never); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresListingCalendarError); + expect((caught as PostgresListingCalendarError).code).toBe('INVALID_EXECUTOR'); + } + + const okExecutor: ListingCalendarExecutor = { + async query() { + return { rows: [] }; + }, + }; + for (const badSchema of ['', 'Public', '1bad', 'bad-schema', 'a; DROP TABLE listing;']) { + let caught: unknown; + try { + createPostgresListingCalendarPort({ executor: okExecutor, schema: badSchema }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresListingCalendarError); + expect((caught as PostgresListingCalendarError).code).toBe('INVALID_SCHEMA'); + } + + const badResponses: unknown[] = [ + null, + { rows: 'not-an-array' }, + { rows: [null] }, + { rows: [{ listing_id: '101', calendar_code: 'XNYS' }] }, + { rows: [{ listing_id: 2_147_483_648, calendar_code: 'XNYS' }] }, + { rows: [{ listing_id: 101, calendar_code: '' }] }, + { rows: [{ listing_id: 101, calendar_code: ' ' }] }, + { rows: [{ listing_id: 101, calendar_code: null }] }, + ]; + for (const badResp of badResponses) { + const port = createPostgresListingCalendarPort({ + executor: { + async query() { + return badResp as never; + }, + }, + }); + let caught: unknown; + try { + await port.getListingCalendars([101]); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresListingCalendarError); + expect((caught as PostgresListingCalendarError).code).toBe('INVALID_ROW'); + } + }); +}); + +describe('createExchangeCalendarResolver — multi-calendar, earlyCloses, and buildEventStudyInput integration', () => { + test('calls listSessionDates once per distinct calendar, anchors early-close vs 16:00 ET in buildEventStudyInput, and respects Vault cutoff', async () => { + const xnysDates = ['2024-11-27', '2024-11-29', '2024-12-02', '2024-12-03']; + const xtseDates = ['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02', '2024-12-03']; + + const makePorts = () => { + const sessionCalls: SessionDatesQuery[] = []; + const listingPort: ListingCalendarPort = { + async getListingCalendars() { + return [ + { listingId: 101, calendarCode: 'XNYS' }, + { listingId: 102, calendarCode: 'XNYS' }, + { listingId: 201, calendarCode: 'XTSE' }, + ]; + }, + }; + const sessionPort: SessionDatesPort = { + async listSessionDates(q) { + sessionCalls.push(q); + return q.calendarCode === 'XNYS' ? xnysDates : xtseDates; + }, + }; + return { listingPort, sessionPort, sessionCalls }; + }; + + const bars: BarRecord[] = [ + // Listing 101 (XNYS) — closed on US Thanksgiving 2024-11-28 + makeBar(101, '2024-11-27', 100), + makeBar(101, '2024-11-29', 110), + makeBar(101, '2024-12-02', 121), + makeBar(101, '2024-12-03', 121), + makeBar(101, '2024-12-04', 999), // post-Vault bar (must be excluded) + // Listing 102 (XNYS) + makeBar(102, '2024-11-27', 50), + makeBar(102, '2024-11-29', 55), + makeBar(102, '2024-12-02', 60.5), + makeBar(102, '2024-12-03', 60.5), + // Listing 201 (XTSE) — open on 2024-11-28 + makeBar(201, '2024-11-27', 200), + makeBar(201, '2024-11-28', 210), + makeBar(201, '2024-11-29', 220.5), + makeBar(201, '2024-12-02', 242.55), + makeBar(201, '2024-12-03', 242.55), + ]; + + // Event at 19:00:00Z on 2024-11-29 (14:00 EST): + // - After XNYS 13:00 EST early close (18:00Z), so with override it anchors to 2024-12-02. + // - Before XTSE 16:00 EST close (21:00Z), so it stays on 2024-11-29. + const eventTs = utcMs(2024, 11, 29, 19, 0, 0); + const events: EventObservation[] = [ + { listingId: 101, knownAt: eventTs, kind: 'filing', subtype: '8-K' }, + { listingId: 201, knownAt: eventTs, kind: 'filing', subtype: '8-K' }, + ]; + + // 1) Baseline: no earlyCloses (all sessions close at 16:00 ET = 21:00Z in EST) + const baselinePorts = makePorts(); + const baselineResolver = createExchangeCalendarResolver({ + listingCalendars: baselinePorts.listingPort, + sessionDates: baselinePorts.sessionPort, + }); + const baselineCal = await baselineResolver({ + listingIds: [101, 102, 201], + fromDate: '2024-11-27', + toDate: '2024-12-03', + }); + + expect(baselinePorts.sessionCalls).toEqual([ + { calendarCode: 'XNYS', fromDate: '2024-11-27', toDate: '2024-12-03' }, + { calendarCode: 'XTSE', fromDate: '2024-11-27', toDate: '2024-12-03' }, + ]); + expect(baselineCal.listingCalendarId).toEqual({ + 101: 'XNYS', + 102: 'XNYS', + 201: 'XTSE', + }); + + const baselinePanel = buildEventStudyInput({ + bars, + events, + vaultCutoffDate: '2024-12-04', + benchmark: 'equal_weight', + exchangeCalendars: baselineCal, + }); + + expect(baselinePanel.diagnostics.vaultExcludedDates).toBe(1); + expect(baselinePanel.input.sessionDates).toEqual([ + '2024-11-27', + '2024-11-28', + '2024-11-29', + '2024-12-02', + '2024-12-03', + ]); + // Under 16:00 ET baseline, both listings anchor to 2024-11-29 (index 2). + expect(baselinePanel.input.events).toEqual([ + { entityId: 101, dayIndex: 2 }, + { entityId: 201, dayIndex: 2 }, + ]); + + // Consecutive-session returns: listing 101 has no 2024-11-28 session on XNYS, + // so 2024-11-27 -> 2024-11-29 is consecutive on XNYS (+10%), and 2024-11-28 is NaN. + const returns101 = baselinePanel.input.entityReturns.get(101) as Float64Array; + expect(Number.isNaN(returns101[0] as number)).toBe(true); + expect(Number.isNaN(returns101[1] as number)).toBe(true); + expect(returns101[2]).toBeCloseTo(0.1, 12); + expect(returns101[3]).toBeCloseTo(0.1, 12); + expect(returns101[4]).toBeCloseTo(0.0, 12); + + // 2) With XNYS-only early close override (780 = 13:00 ET -> 18:00Z on 2024-11-29) + const overridePorts = makePorts(); + const overrideConfig = { XNYS: { '2024-11-29': 780 } }; + const overrideResolver = createExchangeCalendarResolver({ + listingCalendars: overridePorts.listingPort, + sessionDates: overridePorts.sessionPort, + earlyCloses: overrideConfig, + }); + // Mutating caller's override object after construction must not affect resolver. + overrideConfig.XNYS['2024-11-29'] = EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET; + + const overrideCal = await overrideResolver({ + listingIds: [101, 102, 201], + fromDate: '2024-11-27', + toDate: '2024-12-03', + }); + + const xnysSessions = ( + overrideCal.calendars as Record + ).XNYS; + const xtseSessions = ( + overrideCal.calendars as Record + ).XTSE; + + expect(xnysSessions?.find((s) => s.date === '2024-11-29')?.closeTs).toBe( + utcMs(2024, 11, 29, 18, 0, 0) + ); + expect(xnysSessions?.find((s) => s.date === '2024-12-02')?.closeTs).toBe( + utcMs(2024, 12, 2, 21, 0, 0) + ); + expect(xtseSessions?.find((s) => s.date === '2024-11-29')?.closeTs).toBe( + utcMs(2024, 11, 29, 21, 0, 0) + ); + + const overridePanel = buildEventStudyInput({ + bars, + events, + vaultCutoffDate: '2024-12-04', + benchmark: 'equal_weight', + exchangeCalendars: overrideCal, + }); + + // Listing 201 (XTSE) stays on 2024-11-29 (index 2); listing 101 (XNYS) shifts to 2024-12-02 (index 3). + expect(overridePanel.input.events).toEqual([ + { entityId: 201, dayIndex: 2 }, + { entityId: 101, dayIndex: 3 }, + ]); + }); + + test('is deterministic under permuted listingIds and reversed listing rows without mutating caller inputs', async () => { + const xnysDates = ['2024-11-29', '2024-12-02']; + const xtseDates = ['2024-11-29', '2024-12-02']; + + const runWithOrder = async ( + listingIds: number[], + rows: readonly ListingCalendarRow[], + asyncSessionPort: boolean + ) => { + const snapshot = [...listingIds]; + const resolver = createExchangeCalendarResolver({ + listingCalendars: { + getListingCalendars: () => rows, + }, + sessionDates: { + listSessionDates: (q) => { + const dates = q.calendarCode === 'XNYS' ? xnysDates : xtseDates; + return asyncSessionPort ? Promise.resolve(dates) : dates; + }, + }, + earlyCloses: { XNYS: { '2024-11-29': 780 } }, + }); + + const resolved = await resolver({ + listingIds, + fromDate: '2024-11-29', + toDate: '2024-12-02', + }); + expect(listingIds).toEqual(snapshot); + return resolved; + }; + + const forward = await runWithOrder( + [101, 102, 201], + [ + { listingId: 101, calendarCode: 'XNYS' }, + { listingId: 102, calendarCode: 'XNYS' }, + { listingId: 201, calendarCode: 'XTSE' }, + ], + false + ); + + // Permuted listingIds (including duplicate) + reversed listing rows (including identical duplicate) + const permuted = await runWithOrder( + [201, 102, 101, 102], + [ + { listingId: 201, calendarCode: 'XTSE' }, + { listingId: 102, calendarCode: 'XNYS' }, + { listingId: 102, calendarCode: 'XNYS' }, + { listingId: 101, calendarCode: 'XNYS' }, + ], + true + ); + + expect(permuted).toEqual(forward); + expect(Object.keys(permuted.calendars)).toEqual(Object.keys(forward.calendars)); + expect(Object.keys(permuted.listingCalendarId)).toEqual( + Object.keys(forward.listingCalendarId) + ); + }); +}); + +describe('createExchangeCalendarResolver — fail-closed validation & edge cases', () => { + test('empty listingIds returns empty records with zero port calls', async () => { + let listingCalls = 0; + let sessionCalls = 0; + const resolver = createExchangeCalendarResolver({ + listingCalendars: { + getListingCalendars: () => { + listingCalls += 1; + return []; + }, + }, + sessionDates: { + listSessionDates: () => { + sessionCalls += 1; + return []; + }, + }, + }); + + const result = await resolver({ + listingIds: [], + fromDate: '2024-01-01', + toDate: '2024-12-31', + }); + + expect(result).toEqual({ calendars: {}, listingCalendarId: {} }); + expect(listingCalls).toBe(0); + expect(sessionCalls).toBe(0); + }); + + test('fails closed with zero sessionDates calls on missing, unrequested, or conflicting listing rows', async () => { + const cases: readonly { + readonly name: string; + readonly rows: readonly ListingCalendarRow[]; + readonly expectedCode: string; + }[] = [ + { + name: 'missing requested listing', + rows: [{ listingId: 101, calendarCode: 'XNYS' }], + expectedCode: 'MISSING_LISTING_CALENDAR', + }, + { + name: 'unrequested listing returned', + rows: [ + { listingId: 101, calendarCode: 'XNYS' }, + { listingId: 102, calendarCode: 'XNYS' }, + { listingId: 999, calendarCode: 'XTSE' }, + ], + expectedCode: 'UNEXPECTED_LISTING_CALENDAR', + }, + { + name: 'conflicting duplicate listing rows', + rows: [ + { listingId: 101, calendarCode: 'XNYS' }, + { listingId: 101, calendarCode: 'XTSE' }, + { listingId: 102, calendarCode: 'XNYS' }, + ], + expectedCode: 'CONFLICTING_LISTING_CALENDAR', + }, + ]; + + for (const tc of cases) { + let sessionCalls = 0; + const resolver = createExchangeCalendarResolver({ + listingCalendars: { getListingCalendars: () => tc.rows }, + sessionDates: { + listSessionDates: () => { + sessionCalls += 1; + return ['2024-12-02']; + }, + }, + }); + + let caught: unknown; + try { + await resolver({ + listingIds: [101, 102], + fromDate: '2024-12-02', + toDate: '2024-12-02', + }); + } catch (err) { + caught = err; + } + expect(caught, tc.name).toBeInstanceOf(ExchangeCalendarResolverError); + expect((caught as ExchangeCalendarResolverError).code, tc.name).toBe(tc.expectedCode); + expect(sessionCalls, tc.name).toBe(0); + } + }); + + test('fails closed with no partial result on unsorted, duplicate, malformed, or out-of-range session dates', async () => { + const badSessionLists: readonly { readonly name: string; readonly dates: unknown }[] = [ + { name: 'non-array response', dates: '2024-12-02' }, + { name: 'unsorted dates', dates: ['2024-12-03', '2024-12-02'] }, + { name: 'duplicate dates', dates: ['2024-12-02', '2024-12-02'] }, + { name: 'malformed date string', dates: ['2024-02-30'] }, + { name: 'non-string date', dates: [20241202] }, + { name: 'date before fromDate', dates: ['2024-12-01', '2024-12-02'] }, + { name: 'date after toDate', dates: ['2024-12-02', '2024-12-04'] }, + ]; + + for (const tc of badSessionLists) { + const resolver = createExchangeCalendarResolver({ + listingCalendars: { + getListingCalendars: () => [ + { listingId: 101, calendarCode: 'XNYS' }, + { listingId: 201, calendarCode: 'XTSE' }, + ], + }, + sessionDates: { + listSessionDates: (q) => + q.calendarCode === 'XNYS' ? ['2024-12-02', '2024-12-03'] : (tc.dates as never), + }, + }); + + let caught: unknown; + try { + await resolver({ + listingIds: [101, 201], + fromDate: '2024-12-02', + toDate: '2024-12-03', + }); + } catch (err) { + caught = err; + } + expect(caught, tc.name).toBeInstanceOf(ExchangeCalendarResolverError); + expect((caught as ExchangeCalendarResolverError).code, tc.name).toBe('INVALID_SESSION_DATES'); + } + }); + + test('rejects invalid earlyCloses minutes, dates, and shapes at construction with zero port calls', () => { + let listingCalls = 0; + let sessionCalls = 0; + const listingCalendars: ListingCalendarPort = { + getListingCalendars: () => { + listingCalls += 1; + return []; + }, + }; + const sessionDates: SessionDatesPort = { + listSessionDates: () => { + sessionCalls += 1; + return []; + }, + }; + + const invalidCases: readonly { readonly earlyCloses: unknown; readonly expectedCode: string }[] = + [ + { earlyCloses: null, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: [], expectedCode: 'INVALID_OPTION' }, + { earlyCloses: 'XNYS', expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { '': { '2024-11-29': 780 } }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { ' XNYS ': { '2024-11-29': 780 } }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: null }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: [] }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: { '2024-02-30': 780 } }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: { 'not-a-date': 780 } }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: { '1975-12-31': 780 } }, expectedCode: 'UNSUPPORTED_DATE' }, + { earlyCloses: { XNYS: { '2031-01-01': 780 } }, expectedCode: 'UNSUPPORTED_DATE' }, + { earlyCloses: { XNYS: { '2024-11-29': 0 } }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: { '2024-11-29': -1 } }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: { '2024-11-29': 961 } }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: { '2024-11-29': 780.5 } }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: { '2024-11-29': Number.NaN } }, expectedCode: 'INVALID_OPTION' }, + { earlyCloses: { XNYS: { '2024-11-29': '780' } }, expectedCode: 'INVALID_OPTION' }, + ]; + + for (const tc of invalidCases) { + let caught: unknown; + try { + createExchangeCalendarResolver({ + listingCalendars, + sessionDates, + earlyCloses: tc.earlyCloses as never, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(ExchangeCalendarResolverError); + expect((caught as ExchangeCalendarResolverError).code).toBe(tc.expectedCode); + } + + expect(listingCalls).toBe(0); + expect(sessionCalls).toBe(0); + }); +});