diff --git a/libs/research/README.md b/libs/research/README.md index a6b9bb6e..83bd4394 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -276,6 +276,7 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`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. +- **Bar-derived `SessionDatesPort` (`createBarSessionDatesPort({ store, referenceListingIds })`):** Exported from `@stock-bot/research/mcp` alongside `BarSessionDatesPortOptions` and `BarSessionDatesError`. Keys in `referenceListingIds` are exact `exchange.calendar_code` strings (e.g. `XNYS`, `XTSE`) mapped to non-empty, duplicate-free arrays of positive INT32 reference listing IDs whose daily bars define that exchange's session dates; the caller owns reference-listing coverage so gaps do not omit real sessions. Each `listSessionDates` call queries `store.bars({ listingIds, timeframe: '1d', from, to, adjustment: 'raw' })` once with `scope` and `asOf` omitted so the store's default `'vault_fenced'` scope applies (`'vault_evaluation_only'` is never passed), propagates store errors (including `VaultHoldoutFenceError`) unchanged, derives UTC session dates from `BarRecord.ts` (`Math.floor(ts / MS_PER_DAY)`), and fails closed on unknown calendars, malformed queries, or invalid bars. ### Copilot Server diff --git a/libs/research/src/mcp/adapters/bar-session-dates.ts b/libs/research/src/mcp/adapters/bar-session-dates.ts new file mode 100644 index 00000000..d87b1219 --- /dev/null +++ b/libs/research/src/mcp/adapters/bar-session-dates.ts @@ -0,0 +1,278 @@ +/** + * 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); + }, + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 76d441d4..9fe68dd1 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -13,3 +13,4 @@ export * from './tools/query-data'; export * from './tools/read-knowledge'; export * from './tools/search-symbols'; export * from './adapters/postgres-copilot'; +export * from './adapters/bar-session-dates'; diff --git a/libs/research/test/mcp-bar-session-dates-qa.test.ts b/libs/research/test/mcp-bar-session-dates-qa.test.ts new file mode 100644 index 00000000..1685e47f --- /dev/null +++ b/libs/research/test/mcp-bar-session-dates-qa.test.ts @@ -0,0 +1,249 @@ +import { describe, expect, test } from 'bun:test'; +import { VaultHoldoutFenceError } from '../src/market-data-store'; +import { + type DuckDbExecutor, + type DuckDbParam, + createDuckDbMarketDataStore, +} from '../src/market-data-store-duckdb'; +import { + type ListingCalendarPort, + createBarSessionDatesPort, + createExchangeCalendarResolver, +} from '@stock-bot/research/mcp'; + +/** + * QA: the bar-derived SessionDatesPort composed with the real DuckDB store + * planner (`planBars1dQuery` + `mapBarRows`) over a recording fake executor that + * emulates the raw 1d SQL predicate (`listing_id IN (...) AND ts >= ? AND ts <= ? + * AND known_at <= ?` ordered by `listing_id, ts`) on a pinned in-memory dataset. + */ + +const CURATED_ROOT = '/mnt/data/stockbot/curated'; +const CUTOFF_MS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); // 2026-05-28T00:00:00.000Z +const MAX_ALLOWED_ISO_MICROS = '2026-05-27T23:59:59.999999Z'; + +interface FixtureBar { + readonly listingId: number; + readonly ts: number; + readonly knownAt: number; +} + +function utcMs(dateStr: string, hour: number, minute = 0): number { + const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number]; + return Date.UTC(y, m - 1, d, hour, minute, 0, 0); +} + +/** 16:00 ET daily stamp (curate_bars.rs convention): 20:00Z in EDT. Known shortly after close. */ +function edtBar(listingId: number, date: string, knownAt?: number): FixtureBar { + const ts = utcMs(date, 20); + return { listingId, ts, knownAt: knownAt ?? ts + 60_000 }; +} + +/** Parses `YYYY-MM-DDTHH:MM:SS(.ffffff)?Z` to fractional epoch ms (µs precision kept). */ +function isoToMs(iso: string): number { + const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/.exec(iso); + if (m === null) { + throw new Error(`Unexpected ISO bound: ${iso}`); + } + const frac = Number(`0.${(m[7] ?? '0').padEnd(6, '0').slice(0, 6)}`); + return ( + Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])) + + frac * 1000 + ); +} + +function createFixtureExecutor(dataset: readonly FixtureBar[]): { + readonly executor: DuckDbExecutor; + readonly queries: Array<{ sql: string; params: readonly DuckDbParam[] }>; +} { + const queries: Array<{ sql: string; params: readonly DuckDbParam[] }> = []; + const executor: DuckDbExecutor = { + async run(): Promise {}, + async query(sql: string, params: readonly DuckDbParam[]) { + queries.push({ sql, params: [...params] }); + const listingIds = new Set(params.slice(0, -3) as number[]); + const [fromIso, toIso, asOfIso] = params.slice(-3) as [string, string, string]; + const fromMs = isoToMs(fromIso); + const toMs = isoToMs(toIso); + const asOfMs = isoToMs(asOfIso); + return dataset + .filter( + (b) => + listingIds.has(b.listingId) && b.ts >= fromMs && b.ts <= toMs && b.knownAt <= asOfMs + ) + .sort((a, b) => a.listingId - b.listingId || a.ts - b.ts) + .map((b) => ({ + listing_id: b.listingId, + ts: b.ts, + open: 10, + high: 11, + low: 9, + close: 10.5, + volume: 1000, + vwap: null, + known_at: b.knownAt, + })); + }, + }; + return { executor, queries }; +} + +const DATASET: readonly FixtureBar[] = [ + // XNYS reference listings 11 and 12 (overlapping + one-sided dates). + edtBar(11, '2026-05-21'), + edtBar(12, '2026-05-22'), + edtBar(11, '2026-05-26'), + edtBar(12, '2026-05-26'), + edtBar(12, '2026-05-27'), + // Held-out Vault sessions at and after the cutoff date. + edtBar(11, '2026-05-28'), + edtBar(12, '2026-05-29'), + edtBar(11, '2026-06-01'), + // XTSE reference listing 21. + edtBar(21, '2026-05-25'), // Victoria Day: XTSE closed in reality, but present here to prove per-calendar isolation. + edtBar(21, '2026-05-26'), + // Pre-cutoff session whose bar only became known after the cutoff: must stay hidden. + edtBar(21, '2026-05-27', CUTOFF_MS + 3_600_000), + edtBar(21, '2026-05-28'), +]; + +function makeStore(barBatchSize?: number) { + const fake = createFixtureExecutor(DATASET); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + env: {}, + ...(barBatchSize !== undefined ? { barBatchSize } : {}), + }); + return { store, queries: fake.queries }; +} + +describe('bar-session-dates QA — DuckDB store planner at the Vault cutoff', () => { + test('window straddling the cutoff returns only pre-cutoff sessions with a raw bars_1d plan clamped to cutoff - 1µs', async () => { + const { store, queries } = makeStore(); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [12, 11], XTSE: [21] }, + }); + + const dates = await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2026-05-22', + toDate: '2026-06-02', + }); + + expect(dates).toEqual(['2026-05-22', '2026-05-26', '2026-05-27']); + expect(queries).toHaveLength(1); + const q = queries[0]!; + expect(q.sql).toContain(`read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet'`); + expect(q.sql).not.toContain('adj_factors'); + expect(q.params).toEqual([ + 12, + 11, + '2026-05-22T00:00:00.000Z', + MAX_ALLOWED_ISO_MICROS, + MAX_ALLOWED_ISO_MICROS, + ]); + }); + + test('pre-cutoff bar first known after the cutoff is excluded via the default known_at fence', async () => { + const { store } = makeStore(); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [11, 12], XTSE: [21] }, + }); + + expect( + await port.listSessionDates({ + calendarCode: 'XTSE', + fromDate: '2026-05-25', + toDate: '2026-05-31', + }) + ).toEqual(['2026-05-25', '2026-05-26']); + }); + + test('fromDate on or after the cutoff date rejects with VaultHoldoutFenceError before any executor query', async () => { + const { store, queries } = makeStore(); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [11, 12] }, + }); + + for (const fromDate of ['2026-05-28', '2026-06-01']) { + let caught: unknown; + try { + await port.listSessionDates({ calendarCode: 'XNYS', fromDate, toDate: '2026-06-02' }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(VaultHoldoutFenceError); + } + expect(queries).toHaveLength(0); + }); + + test('last pre-cutoff day as a single-day window is included, and output is identical across barBatchSize settings', async () => { + const results: string[][] = []; + for (const batchSize of [undefined, 1, 2]) { + const { store } = makeStore(batchSize); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [11, 12] }, + }); + results.push([ + ...(await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2026-05-21', + toDate: '2026-05-27', + })), + ]); + expect( + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2026-05-27', + toDate: '2026-05-27', + }) + ).toEqual(['2026-05-27']); + } + const expected = ['2026-05-21', '2026-05-22', '2026-05-26', '2026-05-27']; + expect(results).toEqual([expected, expected, expected]); + }); + + test('resolver composed over the DuckDB-backed port yields no post-cutoff session closes', async () => { + const { store, queries } = makeStore(); + const sessionDates = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [11, 12], XTSE: [21] }, + }); + const listingCalendars: ListingCalendarPort = { + getListingCalendars(listingIds) { + return listingIds.map((listingId) => ({ + listingId, + calendarCode: listingId === 901 ? 'XNYS' : 'XTSE', + })); + }, + }; + const resolve = createExchangeCalendarResolver({ listingCalendars, sessionDates }); + + const resolved = await resolve({ + listingIds: [901, 902], + fromDate: '2026-05-26', + toDate: '2026-06-02', + }); + + expect(resolved.listingCalendarId).toEqual({ 901: 'XNYS', 902: 'XTSE' }); + expect(resolved.calendars).toEqual({ + XNYS: [ + { date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) }, + { date: '2026-05-27', closeTs: utcMs('2026-05-27', 20) }, + ], + XTSE: [{ date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) }], + }); + for (const closes of Object.values(resolved.calendars)) { + for (const c of closes) { + expect(c.closeTs).toBeLessThan(CUTOFF_MS); + } + } + expect(queries).toHaveLength(2); + }); +}); diff --git a/libs/research/test/mcp-bar-session-dates.test.ts b/libs/research/test/mcp-bar-session-dates.test.ts new file mode 100644 index 00000000..f5a1ebca --- /dev/null +++ b/libs/research/test/mcp-bar-session-dates.test.ts @@ -0,0 +1,527 @@ +import { describe, expect, test } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type MarketDataStore, + VaultHoldoutFenceError, +} from '../src/market-data-store'; +import { + BarSessionDatesError, + type BarSessionDatesPortOptions, + type ListingCalendarPort, + type PostgresResearchCopilotServerOptions, + type SessionDatesPort, + createBarSessionDatesPort, + createExchangeCalendarResolver, +} from '@stock-bot/research/mcp'; + +type BarsQueryArg = Parameters[0]; + +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, 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: 100, + high: 101, + low: 99, + close: 100.5, + volume: 100_000, + knownAt: ts, + }; +} + +function makeRecordingStore( + handler: (q: BarsQueryArg) => AsyncIterable +): { + readonly store: Pick; + readonly calls: BarsQueryArg[]; +} { + const calls: BarsQueryArg[] = []; + const store: Pick = { + bars(q: BarsQueryArg): AsyncIterable { + calls.push(q); + return handler(q); + }, + }; + return { store, calls }; +} + +async function* yieldBatches(batches: readonly BarBatch[]): AsyncGenerator { + for (const batch of batches) { + yield batch; + } +} + +describe('createBarSessionDatesPort — exports, types, and query contract', () => { + test('returned port is assignable to SessionDatesPort and PostgresResearchCopilotServerOptions["sessionDates"] without casts', async () => { + const { store } = makeRecordingStore(() => yieldBatches([])); + const options: BarSessionDatesPortOptions = { + store, + referenceListingIds: { + XNYS: [101], + }, + }; + + const port = createBarSessionDatesPort(options); + const asSessionDatesPort: SessionDatesPort = port; + const asCopilotSessionDates: PostgresResearchCopilotServerOptions['sessionDates'] = port; + + expect(asSessionDatesPort).toBe(port); + expect(asCopilotSessionDates).toBe(port); + expect( + await asCopilotSessionDates.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }) + ).toEqual([]); + }); + + test('calls store.bars once per query with exact Vault-default keys and configured ID order', async () => { + const { store, calls } = makeRecordingStore(() => + yieldBatches([{ rows: [makeBar(202, '2024-11-26', 21)] }]) + ); + + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [202, 101], + XTSE: [303], + }, + }); + + const dates = await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }); + + expect(dates).toEqual(['2024-11-26']); + expect(calls).toHaveLength(1); + + const req = calls[0] as BarsQueryArg; + expect(req.listingIds).toEqual([202, 101]); + expect(req.timeframe).toBe('1d'); + expect(req.adjustment).toBe('raw'); + expect(req.from).toBe('2024-11-25'); + expect(req.to).toBe('2024-11-29'); + expect(Object.keys(req).sort()).toEqual(['adjustment', 'from', 'listingIds', 'timeframe', 'to']); + expect('scope' in req).toBe(false); + expect('asOf' in req).toBe(false); + }); +}); + +describe('createBarSessionDatesPort — union, bounds, determinism, and empty streams', () => { + test('returns strictly ascending de-duplicated union across multiple out-of-order batches inside [fromDate, toDate]', async () => { + const batches: readonly BarBatch[] = [ + { + rows: [ + // Valid bars outside the requested window must be excluded. + makeBar(101, '2024-11-22', 21), + makeBar(102, '2024-12-02', 21), + // Out-of-order bars inside window, including upper inclusive bound. + makeBar(102, '2024-11-29', 21), + makeBar(101, '2024-11-27', 21), + ], + }, + { + rows: [ + // Overlapping date (2024-11-27), single-listing date (2024-11-26), lower inclusive bound (2024-11-25). + makeBar(102, '2024-11-27', 21), + makeBar(101, '2024-11-25', 21), + makeBar(102, '2024-11-26', 21), + ], + }, + ]; + + const { store, calls } = makeRecordingStore(() => yieldBatches(batches)); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [101, 102], + }, + }); + + const first = await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }); + const second = await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }); + + const expected = ['2024-11-25', '2024-11-26', '2024-11-27', '2024-11-29']; + expect(first).toEqual(expected); + expect(second).toEqual(expected); + expect(calls).toHaveLength(2); + }); + + test('supports single-day inclusive window and returns [] for empty streams or empty batches', async () => { + const { store: singleDayStore } = makeRecordingStore(() => + yieldBatches([ + { + rows: [ + makeBar(101, '2024-07-01', 20), + makeBar(101, '2024-07-02', 20), + makeBar(101, '2024-07-03', 20), + ], + }, + ]) + ); + + const singleDayPort = createBarSessionDatesPort({ + store: singleDayStore, + referenceListingIds: { XNYS: [101] }, + }); + + expect( + await singleDayPort.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-07-02', + toDate: '2024-07-02', + }) + ).toEqual(['2024-07-02']); + + const { store: emptyBatchStore } = makeRecordingStore(() => + yieldBatches([{ rows: [] }, { rows: [] }]) + ); + const emptyPort = createBarSessionDatesPort({ + store: emptyBatchStore, + referenceListingIds: { XNYS: [101] }, + }); + + expect( + await emptyPort.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-07-02', + toDate: '2024-07-02', + }) + ).toEqual([]); + }); +}); + +describe('createBarSessionDatesPort — fail-closed query, store error, and bar validation', () => { + test('throws unknown_calendar and invalid_query with zero store calls', async () => { + const { store, calls } = makeRecordingStore(() => yieldBatches([])); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [101], + }, + }); + + const expectError = async ( + query: unknown, + expectedCode: BarSessionDatesError['code'] + ): Promise => { + let caught: unknown; + try { + await port.listSessionDates(query as never); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(BarSessionDatesError); + expect((caught as BarSessionDatesError).code).toBe(expectedCode); + }; + + await expectError( + { calendarCode: 'XTSE', fromDate: '2024-11-25', toDate: '2024-11-29' }, + 'unknown_calendar' + ); + await expectError( + { calendarCode: '', fromDate: '2024-11-25', toDate: '2024-11-29' }, + 'unknown_calendar' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024/11/25', toDate: '2024-11-29' }, + 'invalid_query' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024-11-25T00:00:00Z', toDate: '2024-11-29' }, + 'invalid_query' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024-02-30', toDate: '2024-03-01' }, + 'invalid_query' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024-11-25', toDate: '2023-02-29' }, + 'invalid_query' + ); + await expectError( + { calendarCode: 'XNYS', fromDate: '2024-11-29', toDate: '2024-11-25' }, + 'invalid_query' + ); + await expectError(null, 'invalid_query'); + + expect(calls).toHaveLength(0); + }); + + test('propagates VaultHoldoutFenceError from the async iterator unchanged with no partial result', async () => { + const vaultError = new VaultHoldoutFenceError( + '2025-01-02', + utcMs(2025, 1, 2, 0, 0, 0), + utcMs(2025, 1, 1, 0, 0, 0) + ); + + const { store } = makeRecordingStore(() => + (async function* (): AsyncGenerator { + yield { rows: [makeBar(101, '2024-12-31', 21)] }; + throw vaultError; + })() + ); + + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { XNYS: [101] }, + }); + + let caught: unknown; + try { + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-12-30', + toDate: '2025-01-02', + }); + } catch (err) { + caught = err; + } + + expect(caught).toBe(vaultError); + }); + + test('throws invalid_bar for NaN, Infinity, fractional ts, or unconfigured listingId', async () => { + const badBars: readonly BarRecord[] = [ + { ...makeBar(101, '2024-11-25', 21), ts: Number.NaN }, + { ...makeBar(101, '2024-11-25', 21), ts: Number.POSITIVE_INFINITY }, + { ...makeBar(101, '2024-11-25', 21), ts: Number.NEGATIVE_INFINITY }, + { ...makeBar(101, '2024-11-25', 21), ts: utcMs(2024, 11, 25, 21, 0, 0) + 0.5 }, + // Listing ID configured only on XTSE, not XNYS. + makeBar(202, '2024-11-25', 21), + // Listing ID not configured on any calendar, even when outside the date window. + makeBar(999, '2024-01-02', 21), + ]; + + for (const badBar of badBars) { + const { store } = makeRecordingStore(() => yieldBatches([{ rows: [badBar] }])); + const port = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [101], + XTSE: [202], + }, + }); + + let caught: unknown; + try { + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-29', + }); + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(BarSessionDatesError); + expect((caught as BarSessionDatesError).code).toBe('invalid_bar'); + } + }); +}); + +describe('createBarSessionDatesPort — options validation and defensive copy', () => { + test('rejects malformed options, empty keys, non-positive/non-INT32 IDs, and duplicates with invalid_options', () => { + const { store } = makeRecordingStore(() => yieldBatches([])); + + const invalidInputs: readonly unknown[] = [ + null, + undefined, + {}, + { store: null, referenceListingIds: { XNYS: [1] } }, + { store: {}, referenceListingIds: { XNYS: [1] } }, + { store: { bars: 'nope' }, referenceListingIds: { XNYS: [1] } }, + { store, referenceListingIds: null }, + { store, referenceListingIds: [] }, + { store, referenceListingIds: { '': [1] } }, + { store, referenceListingIds: { ' ': [1] } }, + { store, referenceListingIds: { ' XNYS': [1] } }, + { store, referenceListingIds: { XNYS: null } }, + { store, referenceListingIds: { XNYS: [] } }, + { store, referenceListingIds: { XNYS: [0] } }, + { store, referenceListingIds: { XNYS: [-5] } }, + { store, referenceListingIds: { XNYS: [1.5] } }, + { store, referenceListingIds: { XNYS: [2_147_483_648] } }, + { store, referenceListingIds: { XNYS: [Number.NaN] } }, + { store, referenceListingIds: { XNYS: [101, 202, 101] } }, + ]; + + for (const input of invalidInputs) { + let caught: unknown; + try { + createBarSessionDatesPort(input as never); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(BarSessionDatesError); + expect((caught as BarSessionDatesError).code).toBe('invalid_options'); + } + }); + + test('defensively copies caller config and isolates per-call listingIds arrays', async () => { + const xnysIds = [101, 102]; + const referenceListingIds: Record = { + XNYS: xnysIds, + }; + + const observedIds: number[][] = []; + const store: Pick = { + bars(q: BarsQueryArg): AsyncIterable { + observedIds.push([...q.listingIds]); + // Mutate caller-passed query array to confirm port passes a fresh copy each time. + q.listingIds.push(999); + return yieldBatches([{ rows: [makeBar(101, '2024-11-25', 21)] }]); + }, + }; + + const port = createBarSessionDatesPort({ store, referenceListingIds }); + + // Mutate caller config after construction. + xnysIds.push(303); + xnysIds[0] = 404; + referenceListingIds.XNYS = [505]; + referenceListingIds.XTSE = [606]; + + expect( + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-25', + }) + ).toEqual(['2024-11-25']); + expect( + await port.listSessionDates({ + calendarCode: 'XNYS', + fromDate: '2024-11-25', + toDate: '2024-11-25', + }) + ).toEqual(['2024-11-25']); + + expect(observedIds).toEqual([ + [101, 102], + [101, 102], + ]); + + let caught: unknown; + try { + await port.listSessionDates({ + calendarCode: 'XTSE', + fromDate: '2024-11-25', + toDate: '2024-11-25', + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(BarSessionDatesError); + expect((caught as BarSessionDatesError).code).toBe('unknown_calendar'); + }); +}); + +describe('createBarSessionDatesPort — composition with createExchangeCalendarResolver', () => { + test('resolves XNYS and XTSE session closes including summer EDT, Thanksgiving divergence, and early-close override', async () => { + const xnysBars: readonly BarRecord[] = [ + // Summer EDT session (16:00 ET = 20:00Z) + makeBar(1001, '2024-07-02', 20), + // Winter EST sessions (US closed 2024-11-28 Thanksgiving; open 2024-11-29) + makeBar(1001, '2024-11-27', 21), + makeBar(1002, '2024-11-29', 21), + ]; + + const xtseBars: readonly BarRecord[] = [ + // Summer EDT session (16:00 ET = 20:00Z) + makeBar(2001, '2024-07-02', 20), + // Winter EST sessions (TSX open on US Thanksgiving 2024-11-28 and regular close on 2024-11-29) + makeBar(2001, '2024-11-27', 21), + makeBar(2001, '2024-11-28', 21), + makeBar(2002, '2024-11-29', 21), + ]; + + const { store, calls } = makeRecordingStore((q) => { + const requested = new Set(q.listingIds); + const rows = [...xnysBars, ...xtseBars].filter((bar) => requested.has(bar.listingId)); + return yieldBatches([{ rows }]); + }); + + const sessionDates = createBarSessionDatesPort({ + store, + referenceListingIds: { + XNYS: [1001, 1002], + XTSE: [2001, 2002], + }, + }); + + const listingCalendars: ListingCalendarPort = { + getListingCalendars(listingIds) { + return listingIds.map((listingId) => ({ + listingId, + calendarCode: listingId === 501 ? 'XNYS' : 'XTSE', + })); + }, + }; + + const resolveExchangeCalendars = createExchangeCalendarResolver({ + listingCalendars, + sessionDates, + earlyCloses: { + XNYS: { + '2024-11-29': 13 * 60, // 13:00 ET -> 18:00Z (EST) + }, + }, + }); + + const resolved = await resolveExchangeCalendars({ + listingIds: [501, 602], + fromDate: '2024-07-02', + toDate: '2024-11-29', + }); + + expect(resolved.listingCalendarId).toEqual({ + 501: 'XNYS', + 602: 'XTSE', + }); + + expect(resolved.calendars).toEqual({ + XNYS: [ + { date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) }, + { date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) }, + { date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 18, 0, 0) }, + ], + XTSE: [ + { date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) }, + { date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) }, + { date: '2024-11-28', closeTs: utcMs(2024, 11, 28, 21, 0, 0) }, + { date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 21, 0, 0) }, + ], + }); + + // One store.bars call per distinct calendar code (XNYS, XTSE). + expect(calls).toHaveLength(2); + expect(calls[0]?.listingIds).toEqual([1001, 1002]); + expect(calls[1]?.listingIds).toEqual([2001, 2002]); + }); +});