From b56329de2a2254a544b166f0cd2fe36810b80bd1 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 08:49:30 -0500 Subject: [PATCH 1/5] =?UTF-8?q?T-158:=20M2.1k=20=E2=80=94=20PostgreSQL=20s?= =?UTF-8?q?ecurity-master=20adapter=20for=20the=20MCP=20copilot=20`search?= =?UTF-8?q?=5Fsymbols`=20tool:=20`SymbolSearchPort`=20over=20an=20injected?= =?UTF-8?q?=20executor=20in=20`libs/research/src/mcp/adapters/postgres-sym?= =?UTF-8?q?bol-search.ts`=20(as-of-cutoff=20ticker=20resolution,=20paramet?= =?UTF-8?q?erized=20SQL,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 8 + .../mcp/adapters/postgres-symbol-search.ts | 355 ++++++++++++++ libs/research/src/mcp/index.ts | 1 + .../test/mcp-postgres-symbol-search.test.ts | 413 ++++++++++++++++ .../mcp-symbol-search-adapter.test.ts | 447 ++++++++++++++++++ 5 files changed, 1224 insertions(+) create mode 100644 libs/research/src/mcp/adapters/postgres-symbol-search.ts create mode 100644 libs/research/test/mcp-postgres-symbol-search.test.ts create mode 100644 test/postgres/mcp-symbol-search-adapter.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index 93e29a1d..cf49f406 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -256,6 +256,14 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **Review status & Vault safety:** Server-controlled metadata (`id`, UTC ISO `createdAt`, and initial `status: 'pending_review'`) cannot be supplied by callers; director approval occurs out-of-band. Every unique `trialRef` is verified via the injected read-only `trialLookup.hasResearchVisibleTrial(ref)` before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only in `title` and `summary` and keep Vault holdout observations out of filing text. - **Idempotency & receipts:** `FindingWritePort` exposes only `appendFinding(record, idempotencyKey?)` with atomic `created` / `replayed` / `conflict` semantics comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs`. Retries with the same key and normalized payload return the original `{ id, createdAt, created: false }` without appending; key reuse with a different payload returns a fixed `isError: true` conflict error with zero writes; unkeyed calls are independent. Filed records extend `FindingRecord` and can be read back by receipt ID via `read_knowledge`. +### PostgreSQL Symbol Search Adapter + +- **`createPostgresSymbolSearchPort({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `SymbolSearchExecutor` and `PostgresSymbolSearchError`) implements `SymbolSearchPort` over the M1 PostgreSQL security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`) in one read-only parameterized `SELECT` with zero runtime `pg` dependency. +- **Inputs & schema:** Validates that `executor` exposes a callable `query(text, params?)` method (`INVALID_EXECUTOR`), validates optional `schema` against `^[a-z_][a-z0-9_]*$` before quoting table identifiers (`INVALID_SCHEMA`; defaults to the executor's `search_path`), validates `q.vaultCutoffTs` (epoch milliseconds) and converts it to a UTC calendar date (`YYYY-MM-DD`), escapes `%`, `_`, and `\` before building the `ILIKE` pattern, and rejects malformed/non-integer IDs or invalid/impossible `YYYY-MM-DD` dates returned by the executor (`INVALID_ROW`). +- **As-of ticker resolution & root suppression:** Excludes listings with `listed_from > cutoff` (retaining `listed_from IS NULL`). Defines `root_is_future` per listing when `listing_symbol_history` has at least one row with `upper(ticker) = upper(listing.ticker_root)` and none with `valid_from <= cutoff`. Resolves one ticker per listing (breaking same-`valid_from` ties by `ticker ASC`) in strict order: (1) latest history row valid at cutoff (`valid_from <= cutoff AND (valid_to IS NULL OR valid_to >= cutoff)`), (2) `listing.ticker_root` when `NOT root_is_future`, (3) latest history row with `valid_from <= cutoff` even if its `valid_to < cutoff`, (4) otherwise excludes the listing so future tickers never leak via fallback or name/ISIN lookup. +- **`delistedAt` derivation:** Projects `delistedAt` as `listing.listed_to` (`YYYY-MM-DD`) when `delist_reason IS NOT NULL AND delist_reason <> 'active'`, else `null`. When `q.includeDelisted === false`, rows with non-null `delistedAt <= cutoff` are filtered out while future delistings (`delistedAt > cutoff`) remain eligible as of the cutoff. +- **Port matching vs. MCP ranking:** The adapter matches on resolved as-of ticker (`ILIKE`), `listing.ticker_root` (`ILIKE`, gated by `NOT root_is_future`), `instrument.canonical_name` (`ILIKE`), or case-insensitive exact `instrument.primary_isin`, ignores `q.limit`, and returns all candidates ordered by `listing_id ASC`. When composed with `createSearchSymbolsTool`, the MCP tool applies Vault clamping/masking, ranks by exact ticker > ticker prefix > company name substring (tie-breaking by `listingId ASC`), and truncates to `limit` — so callers needing ticker-substring, root-only, or exact-ISIN lookups should call the port directly, while MCP tool callers should query by ticker or company name. + ### 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/postgres-symbol-search.ts b/libs/research/src/mcp/adapters/postgres-symbol-search.ts new file mode 100644 index 00000000..c2e7b9ae --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-symbol-search.ts @@ -0,0 +1,355 @@ +/** + * Read-only PostgreSQL security-master adapter implementing {@link SymbolSearchPort} + * for the MCP copilot `search_symbols` tool. + * + * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is + * injected via {@link SymbolSearchExecutor}. + */ + +import type { SymbolSearchPort, SymbolSearchQuery, SymbolSearchRow } from '../tools/search-symbols'; +import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input'; + +const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; +const CALENDAR_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/; +const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +/** Error codes thrown by {@link PostgresSymbolSearchError}. */ +export type PostgresSymbolSearchErrorCode = + | 'INVALID_EXECUTOR' + | 'INVALID_SCHEMA' + | 'INVALID_ROW'; + +/** Typed validation error thrown by the PostgreSQL symbol-search adapter. */ +export class PostgresSymbolSearchError extends RangeError { + readonly code: PostgresSymbolSearchErrorCode; + + constructor(code: PostgresSymbolSearchErrorCode, message: string) { + super(message); + this.name = 'PostgresSymbolSearchError'; + this.code = code; + 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 SymbolSearchExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** Factory options for {@link createPostgresSymbolSearchPort}. */ +export interface PostgresSymbolSearchPortOptions { + readonly executor: SymbolSearchExecutor; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; +} + +interface RawSymbolSearchRow { + readonly listing_id: unknown; + readonly instrument_id: unknown; + readonly ticker: unknown; + readonly class_suffix: unknown; + readonly name: unknown; + readonly mic: unknown; + readonly currency: unknown; + readonly isin: unknown; + readonly first_bar_date: unknown; + readonly last_bar_date: unknown; + readonly delisted_at: unknown; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function daysInUtcMonth(year: number, monthIndex: number): number { + if (monthIndex === 1 && isLeapYear(year)) { + return 29; + } + return DAYS_IN_MONTH[monthIndex] ?? 0; +} + +function isValidCalendarDate(value: unknown): value is string { + if (typeof value !== 'string') { + return false; + } + const match = CALENDAR_DATE_RE.exec(value); + if (match === null) { + return false; + } + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + if (month < 1 || month > 12) { + return false; + } + return day >= 1 && day <= daysInUtcMonth(year, month - 1); +} + +function escapeLikePattern(value: string): string { + return value.replace(/[\\%_]/g, '\\$&'); +} + +function quoteTable(schemaPrefix: string, table: string): string { + return `${schemaPrefix}${table}`; +} + +function buildSearchSymbolsSql(schemaPrefix: string): string { + const listingTable = quoteTable(schemaPrefix, 'listing'); + const instrumentTable = quoteTable(schemaPrefix, 'instrument'); + const exchangeTable = quoteTable(schemaPrefix, 'exchange'); + const historyTable = quoteTable(schemaPrefix, 'listing_symbol_history'); + + return [ + 'SELECT', + ' l.listing_id AS listing_id,', + ' l.instrument_id AS instrument_id,', + ' resolved.ticker AS ticker,', + " NULLIF(l.class_suffix, '') AS class_suffix,", + ' i.canonical_name AS name,', + ' l.mic AS mic,', + ' btrim(l.currency) AS currency,', + " NULLIF(btrim(i.primary_isin), '') AS isin,", + " to_char(l.listed_from, 'YYYY-MM-DD') AS first_bar_date,", + " to_char(l.listed_to, 'YYYY-MM-DD') AS last_bar_date,", + " to_char(delisted.delisted_at, 'YYYY-MM-DD') AS delisted_at", + `FROM ${listingTable} l`, + `INNER JOIN ${instrumentTable} i ON i.instrument_id = l.instrument_id`, + `INNER JOIN ${exchangeTable} e ON e.mic = l.mic`, + 'CROSS JOIN LATERAL (', + ' SELECT (', + ' EXISTS (', + ' SELECT 1', + ` FROM ${historyTable} h_any`, + ' WHERE h_any.listing_id = l.listing_id', + ' AND upper(h_any.ticker) = upper(l.ticker_root)', + ' )', + ' AND NOT EXISTS (', + ' SELECT 1', + ` FROM ${historyTable} h_past`, + ' WHERE h_past.listing_id = l.listing_id', + ' AND upper(h_past.ticker) = upper(l.ticker_root)', + ' AND h_past.valid_from <= $1::date', + ' )', + ' ) AS is_future', + ') root_state', + 'LEFT JOIN LATERAL (', + ' SELECT h.ticker', + ` FROM ${historyTable} h`, + ' WHERE h.listing_id = l.listing_id', + ' AND h.valid_from <= $1::date', + ' AND (h.valid_to IS NULL OR h.valid_to >= $1::date)', + ' ORDER BY h.valid_from DESC, h.ticker ASC', + ' LIMIT 1', + ') hist_active ON TRUE', + 'LEFT JOIN LATERAL (', + ' SELECT h.ticker', + ` FROM ${historyTable} h`, + ' WHERE h.listing_id = l.listing_id', + ' AND h.valid_from <= $1::date', + ' ORDER BY h.valid_from DESC, h.ticker ASC', + ' LIMIT 1', + ') hist_prior ON TRUE', + 'CROSS JOIN LATERAL (', + ' SELECT CASE', + ' WHEN hist_active.ticker IS NOT NULL THEN hist_active.ticker', + ' WHEN NOT root_state.is_future THEN l.ticker_root', + ' ELSE hist_prior.ticker', + ' END AS ticker', + ') resolved', + 'CROSS JOIN LATERAL (', + ' SELECT CASE', + " WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to", + ' ELSE NULL', + ' END AS delisted_at', + ') delisted', + 'WHERE (l.listed_from IS NULL OR l.listed_from <= $1::date)', + ' AND resolved.ticker IS NOT NULL', + " AND resolved.ticker <> ''", + ' AND ($4::text IS NULL OR btrim(e.country_iso) = $4::text)', + ' AND ($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)', + ' AND (', + " resolved.ticker ILIKE $2::text ESCAPE '\\'", + " OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')", + " OR i.canonical_name ILIKE $2::text ESCAPE '\\'", + ' OR (i.primary_isin IS NOT NULL AND upper(btrim(i.primary_isin)) = upper($3::text))', + ' )', + 'ORDER BY l.listing_id ASC', + ].join('\n'); +} + +function parseSafeInt(value: unknown, field: string): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value)) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + `Invalid security-master row: "${field}" must be a safe integer.` + ); + } + return value; +} + +function parseNonEmptyString(value: unknown, field: string): string { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + `Invalid security-master row: "${field}" must be a non-empty string.` + ); + } + return value; +} + +function parseNullableClassSuffix(value: unknown): string | null { + if (value === null) { + return null; + } + if (typeof value !== 'string') { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + 'Invalid security-master row: "class_suffix" must be a string or null.' + ); + } + return value === '' ? null : value; +} + +function parseNullableIsin(value: unknown): string | null { + if (value === null) { + return null; + } + if (typeof value !== 'string') { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + 'Invalid security-master row: "isin" must be a string or null.' + ); + } + const trimmed = value.trim(); + return trimmed === '' ? null : trimmed; +} + +function parseNullableDate(value: unknown, field: string): string | null { + if (value === null) { + return null; + } + if (!isValidCalendarDate(value)) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + `Invalid security-master row: "${field}" must be a valid YYYY-MM-DD calendar date or null.` + ); + } + return value; +} + +function mapRawRow(raw: unknown): SymbolSearchRow { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + 'Invalid security-master row: expected a non-null object.' + ); + } + + const row = raw as RawSymbolSearchRow; + const listingId = parseSafeInt(row.listing_id, 'listing_id'); + const instrumentId = parseSafeInt(row.instrument_id, 'instrument_id'); + const ticker = parseNonEmptyString(row.ticker, 'ticker'); + const classSuffix = parseNullableClassSuffix(row.class_suffix); + const name = parseNonEmptyString(row.name, 'name'); + const mic = parseNonEmptyString(row.mic, 'mic'); + const currency = parseNonEmptyString(row.currency, 'currency').trim(); + const isin = parseNullableIsin(row.isin); + const firstBarDate = parseNullableDate(row.first_bar_date, 'first_bar_date'); + const lastBarDate = parseNullableDate(row.last_bar_date, 'last_bar_date'); + const delistedAt = parseNullableDate(row.delisted_at, 'delisted_at'); + + return { + listingId, + instrumentId, + ticker, + classSuffix, + name, + mic, + currency, + isin, + firstBarDate, + lastBarDate, + delistedAt, + }; +} + +function validateFactoryOptions(options: PostgresSymbolSearchPortOptions): { + readonly executor: SymbolSearchExecutor; + readonly schemaPrefix: string; +} { + if (typeof options !== 'object' || options === null) { + throw new PostgresSymbolSearchError( + 'INVALID_EXECUTOR', + 'Invalid options: expected an object with a SymbolSearchExecutor.' + ); + } + + const { executor, schema } = options; + if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { + throw new PostgresSymbolSearchError( + '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 PostgresSymbolSearchError( + 'INVALID_SCHEMA', + 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' + ); + } + + return { executor, schemaPrefix: `"${schema}".` }; +} + +/** + * Creates a read-only PostgreSQL {@link SymbolSearchPort} backed by the M1 + * security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`). + */ +export function createPostgresSymbolSearchPort( + options: PostgresSymbolSearchPortOptions +): SymbolSearchPort { + const { executor, schemaPrefix } = validateFactoryOptions(options); + const sql = buildSearchSymbolsSql(schemaPrefix); + + return { + async searchSymbols(q: SymbolSearchQuery): Promise { + const cutoffTs = validateVaultCutoffTs(q.vaultCutoffTs); + const cutoffDate = utcDateOf(cutoffTs); + const ilikePattern = `%${escapeLikePattern(q.query)}%`; + const country = q.country ?? null; + const includeDelisted = q.includeDelisted; + + const result = await executor.query(sql, [ + cutoffDate, + ilikePattern, + q.query, + country, + includeDelisted, + ]); + + if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + 'Invalid executor response: expected an object with a rows array.' + ); + } + + const mapped: SymbolSearchRow[] = []; + for (let i = 0; i < result.rows.length; i += 1) { + mapped.push(mapRawRow(result.rows[i])); + } + return mapped; + }, + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 3ab56692..f8f50f75 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,3 +1,4 @@ +export * from './adapters/postgres-symbol-search'; export * from './copilot-server'; export * from './protocol'; export * from './server'; diff --git a/libs/research/test/mcp-postgres-symbol-search.test.ts b/libs/research/test/mcp-postgres-symbol-search.test.ts new file mode 100644 index 00000000..ea9a3edd --- /dev/null +++ b/libs/research/test/mcp-postgres-symbol-search.test.ts @@ -0,0 +1,413 @@ +import { describe, expect, test } from 'bun:test'; +import { MarketDataStoreValidationError } from '../src/market-data-store'; +import { + PostgresSymbolSearchError, + type SymbolSearchExecutor, + type SymbolSearchQuery, + createPostgresSymbolSearchPort, +} from '../src/mcp/index'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function createFakeExecutor(rows: readonly Record[] = []): { + readonly calls: RecordedCall[]; + readonly executor: SymbolSearchExecutor; +} { + const calls: RecordedCall[] = []; + const executor: SymbolSearchExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return { rows: rows as readonly Row[] }; + }, + }; + return { calls, executor }; +} + +function makeRawRow(overrides: Record = {}): Record { + return { + listing_id: 101, + instrument_id: 1001, + ticker: 'ACME', + class_suffix: '', + name: 'Acme Corporation', + mic: 'XNAS', + currency: 'USD', + isin: 'US0000001015', + first_bar_date: '2018-01-02', + last_bar_date: '2024-06-28', + delisted_at: null, + ...overrides, + }; +} + +const BASE_QUERY: SymbolSearchQuery = { + query: 'ACME', + limit: 20, + includeDelisted: true, + vaultCutoffTs: Date.UTC(2024, 5, 30, 0, 0, 0, 0), // 2024-06-30T00:00:00.000Z +}; + +describe('createPostgresSymbolSearchPort (fake executor)', () => { + test('issues a single parameterized SELECT and never interpolates injection-shaped queries', async () => { + const injection = "'; DROP TABLE listing; --"; + const fake = createFakeExecutor([makeRawRow()]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols({ + ...BASE_QUERY, + query: injection, + }); + + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text.trimStart().startsWith('SELECT')).toBe(true); + expect(call.text).not.toContain(';'); + expect(call.text).not.toContain(injection); + expect(call.text).not.toContain('DROP TABLE'); + expect(call.params).toEqual([ + '2024-06-30', + `%${injection}%`, + injection, + null, + true, + ]); + }); + + test('escapes %, _, and backslash literals in the ILIKE pattern while preserving raw query for ISIN', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols({ + ...BASE_QUERY, + query: 'A%B_C\\D', + }); + + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text).toContain("ESCAPE '\\'"); + expect(call.params).toEqual([ + '2024-06-30', + '%A\\%B\\_C\\\\D%', + 'A%B_C\\D', + null, + true, + ]); + }); + + test('converts vaultCutoffTs epoch-ms to UTC calendar date across midnight boundaries', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols({ + ...BASE_QUERY, + vaultCutoffTs: Date.UTC(2024, 5, 30, 23, 59, 59, 999), + }); + await port.searchSymbols({ + ...BASE_QUERY, + vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0), + }); + + expect(fake.calls).toHaveLength(2); + expect(fake.calls[0]!.params?.[0]).toBe('2024-06-30'); + expect(fake.calls[1]!.params?.[0]).toBe('2024-07-01'); + }); + + test('binds optional country filter and both includeDelisted flags', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols({ + ...BASE_QUERY, + country: 'CA', + includeDelisted: false, + }); + await port.searchSymbols({ + ...BASE_QUERY, + country: 'US', + includeDelisted: true, + }); + + expect(fake.calls).toHaveLength(2); + expect(fake.calls[0]!.params?.[3]).toBe('CA'); + expect(fake.calls[0]!.params?.[4]).toBe(false); + expect(fake.calls[1]!.params?.[3]).toBe('US'); + expect(fake.calls[1]!.params?.[4]).toBe(true); + }); + + test('ignores q.limit in SQL and returns all candidates without truncation', async () => { + const rows = [ + makeRawRow({ listing_id: 1, instrument_id: 10, ticker: 'AA' }), + makeRawRow({ listing_id: 2, instrument_id: 20, ticker: 'AAB' }), + makeRawRow({ listing_id: 3, instrument_id: 30, ticker: 'AAC' }), + ]; + const fake = createFakeExecutor(rows); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + const r1 = await port.searchSymbols({ ...BASE_QUERY, limit: 1 }); + const r2 = await port.searchSymbols({ ...BASE_QUERY, limit: 100 }); + + expect(r1).toHaveLength(3); + expect(r2).toHaveLength(3); + expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text); + expect(fake.calls[0]!.params).toEqual(fake.calls[1]!.params); + // Outer query has ORDER BY listing_id ASC with no outer LIMIT clause + expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY l.listing_id ASC')).toBe(true); + }); + + test('gates ticker_root fallback and matching on cutoff-aware history suppression and derives delisted_at', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols(BASE_QUERY); + + const sql = fake.calls[0]!.text; + // Root-suppression subquery checks upper(ticker) = upper(ticker_root) and cutoff $1::date + expect(sql).toContain('upper(h_any.ticker) = upper(l.ticker_root)'); + expect(sql).toContain('upper(h_past.ticker) = upper(l.ticker_root)'); + expect(sql).toContain('h_past.valid_from <= $1::date'); + // Both fallback resolution and root ILIKE predicate are gated by NOT root_state.is_future + expect(sql).toContain('WHEN NOT root_state.is_future THEN l.ticker_root'); + expect(sql).toContain("OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')"); + // delisted_at derivation and $5 filter + expect(sql).toContain("WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to"); + expect(sql).toContain('($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)'); + }); + + test('quotes optional validated schema on all security-master tables and omits prefix when unset', async () => { + const fakeDefault = createFakeExecutor([]); + const defaultPort = createPostgresSymbolSearchPort({ executor: fakeDefault.executor }); + await defaultPort.searchSymbols(BASE_QUERY); + expect(fakeDefault.calls[0]!.text).toContain('FROM listing l'); + expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN instrument i'); + expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN exchange e'); + expect(fakeDefault.calls[0]!.text).toContain('FROM listing_symbol_history'); + + const fakeScoped = createFakeExecutor([]); + const scopedPort = createPostgresSymbolSearchPort({ + executor: fakeScoped.executor, + schema: 'custom_master_1', + }); + await scopedPort.searchSymbols(BASE_QUERY); + expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing l'); + expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".instrument i'); + expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".exchange e'); + expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing_symbol_history'); + }); + + test('maps raw rows into SymbolSearchRow with classSuffix, ISIN trimming, nullable dates, and delistedAt', async () => { + const fake = createFakeExecutor([ + makeRawRow({ + listing_id: 101, + instrument_id: 501, + ticker: 'ACME', + class_suffix: '', + name: 'Acme Corp', + mic: 'XNAS', + currency: 'USD ', + isin: ' US0000001015 ', + first_bar_date: '2020-02-29', + last_bar_date: '2024-06-28', + delisted_at: null, + }), + makeRawRow({ + listing_id: 102, + instrument_id: 502, + ticker: 'BRK', + class_suffix: 'B', + name: 'Berkshire Example', + mic: 'XNYS', + currency: 'USD', + isin: ' ', + first_bar_date: null, + last_bar_date: '2023-12-15', + delisted_at: '2023-12-15', + }), + makeRawRow({ + listing_id: 103, + instrument_id: 503, + ticker: 'NULLY', + class_suffix: null, + name: 'Nullable Fields Co', + mic: 'XTSE', + currency: 'CAD', + isin: null, + first_bar_date: null, + last_bar_date: null, + delisted_at: null, + }), + ]); + + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + const rows = await port.searchSymbols(BASE_QUERY); + + expect(rows).toEqual([ + { + listingId: 101, + instrumentId: 501, + ticker: 'ACME', + classSuffix: null, + name: 'Acme Corp', + mic: 'XNAS', + currency: 'USD', + isin: 'US0000001015', + firstBarDate: '2020-02-29', + lastBarDate: '2024-06-28', + delistedAt: null, + }, + { + listingId: 102, + instrumentId: 502, + ticker: 'BRK', + classSuffix: 'B', + name: 'Berkshire Example', + mic: 'XNYS', + currency: 'USD', + isin: null, + firstBarDate: null, + lastBarDate: '2023-12-15', + delistedAt: '2023-12-15', + }, + { + listingId: 103, + instrumentId: 503, + ticker: 'NULLY', + classSuffix: null, + name: 'Nullable Fields Co', + mic: 'XTSE', + currency: 'CAD', + isin: null, + firstBarDate: null, + lastBarDate: null, + delistedAt: null, + }, + ]); + }); + + test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => { + const invalidOptions: unknown[] = [ + null, + undefined, + {}, + { executor: null }, + { executor: {} }, + { executor: { query: 'not-a-fn' } }, + ]; + + for (const opts of invalidOptions) { + let caught: unknown; + try { + createPostgresSymbolSearchPort(opts as Parameters[0]); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresSymbolSearchError); + expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_EXECUTOR'); + } + }); + + test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { + const fake = createFakeExecutor([]); + const badSchemas: unknown[] = [ + '', + 'Public', + '1schema', + 'bad-name', + 'bad.name', + 'public"; DROP TABLE listing; --', + 'space name', + 123, + null, + ]; + + for (const schema of badSchemas) { + let caught: unknown; + try { + createPostgresSymbolSearchPort({ + executor: fake.executor, + schema: schema as string, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresSymbolSearchError); + expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_SCHEMA'); + } + + expect(fake.calls).toHaveLength(0); + }); + + test('rejects invalid vaultCutoffTs before executing any query', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await expect( + port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Number.NaN }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + expect(fake.calls).toHaveLength(0); + }); + + test('rejects malformed rows (fractional/unsafe IDs, malformed/impossible dates, invalid types) with INVALID_ROW', async () => { + const badRows: readonly Record[] = [ + makeRawRow({ listing_id: 1.5 }), + makeRawRow({ listing_id: Number.MAX_SAFE_INTEGER + 1 }), + makeRawRow({ listing_id: '101' }), + makeRawRow({ listing_id: Number.NaN }), + makeRawRow({ instrument_id: 2.25 }), + makeRawRow({ instrument_id: Number.POSITIVE_INFINITY }), + makeRawRow({ ticker: '' }), + makeRawRow({ ticker: null }), + makeRawRow({ name: '' }), + makeRawRow({ mic: null }), + makeRawRow({ currency: '' }), + makeRawRow({ class_suffix: 42 }), + makeRawRow({ isin: 12345 }), + makeRawRow({ first_bar_date: '2024-6-1' }), + makeRawRow({ first_bar_date: '2023-02-29' }), + makeRawRow({ last_bar_date: '2024-02-30' }), + makeRawRow({ last_bar_date: '2024-13-01' }), + makeRawRow({ delisted_at: '2024-06-30T00:00:00Z' }), + makeRawRow({ delisted_at: new Date('2024-06-30T00:00:00Z') }), + ]; + + for (const badRow of badRows) { + const fake = createFakeExecutor([badRow]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + let caught: unknown; + try { + await port.searchSymbols(BASE_QUERY); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresSymbolSearchError); + expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW'); + } + + // Non-object row / invalid result shape + const nullRowExecutor: SymbolSearchExecutor = { + async query>() { + return { rows: [null as unknown as Row] }; + }, + }; + const portNullRow = createPostgresSymbolSearchPort({ executor: nullRowExecutor }); + await expect(portNullRow.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf( + PostgresSymbolSearchError + ); + + const badResultExecutor: SymbolSearchExecutor = { + async query() { + return { rows: 'not-an-array' as unknown as readonly never[] }; + }, + }; + const portBadResult = createPostgresSymbolSearchPort({ executor: badResultExecutor }); + await expect(portBadResult.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf( + PostgresSymbolSearchError + ); + }); +}); diff --git a/test/postgres/mcp-symbol-search-adapter.test.ts b/test/postgres/mcp-symbol-search-adapter.test.ts new file mode 100644 index 00000000..a66a0b8c --- /dev/null +++ b/test/postgres/mcp-symbol-search-adapter.test.ts @@ -0,0 +1,447 @@ +import { randomUUID } from 'node:crypto'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + type SearchSymbolsResultPayload, + type SymbolSearchExecutor, + createMcpServer, + createPostgresSymbolSearchPort, + createSearchSymbolsTool, +} from '../../libs/research/src/mcp/index'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('mcp-symbol-search-adapter-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; + +const VAULT_CUTOFF_DATE = '2024-06-30'; +const VAULT_CUTOFF_TS = Date.UTC(2024, 5, 30, 0, 0, 0, 0); + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +function assertSafetyDatabaseUrl(connectionString: string | undefined): string { + if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + return connectionString; +} + +function createPgExecutor(pool: Pool): SymbolSearchExecutor { + return { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + return pool.query( + text, + params === undefined ? undefined : [...params] + ) as unknown as Promise<{ readonly rows: readonly Row[] }>; + }, + }; +} + +async function createIsolatedFixture() { + const safeUrl = assertSafetyDatabaseUrl(url); + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: safeUrl }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: safeUrl, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'master' }); + await seedFixture(pool); + + return { admin, pool, schema }; +} + +async function seedFixture(pool: Pool): Promise { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + + await client.query(` + INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) + VALUES + ('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered') + ON CONFLICT (mic) DO NOTHING + `); + + await client.query(` + INSERT INTO instrument (instrument_id, primary_isin, canonical_name, security_type, issuer_country) + OVERRIDING SYSTEM VALUE + VALUES + (101, 'US1010000001', 'Renamed Holdings Inc', 'common', 'US'), + (102, 'US1020000002', 'Gap Rename Corp', 'common', 'US'), + (103, 'US1030000003', 'Stealth Future Ventures', 'common', 'US'), + (104, 'CA1040000004', 'No History Metals', 'common', 'CA'), + (105, 'US1050000005', 'Overlap Equity Inc', 'common', 'US'), + (106, 'US1060000006', 'Post Cutoff IPO Inc', 'common', 'US'), + (107, 'CA1070000007', 'Unknown Start Corp', 'common', 'CA'), + (108, 'US1080000008', 'Delist Boundary Co', 'common', 'US'), + (109, 'US1090000009', 'Delist Boundary Active', 'common', 'US'), + (110, 'US1100000010', 'Delist Boundary Unspecified', 'common', 'US'), + (111, 'US1110000011', 'Delist Boundary Future', 'common', 'US'), + (112, 'US1120000012', '100% Pure_Wild\\Co', 'common', 'US'), + (113, 'US1130000013', 'Second Oldco Group', 'common', 'US'), + (114, 'CA1140000014', 'Alpha Oldco Canada', 'common', 'CA') + `); + + await client.query(` + INSERT INTO listing ( + listing_id, instrument_id, mic, ticker_root, class_suffix, currency, + listed_from, listed_to, delist_reason + ) + OVERRIDING SYSTEM VALUE + VALUES + (101, 101, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active'), + (102, 102, 'XNYS', 'GAPNEW', '', 'USD', '2019-01-01', '2024-12-31', 'active'), + (103, 103, 'XNAS', 'FUTROOT', '', 'USD', '2020-01-01', NULL, NULL), + (104, 104, 'XTSE', 'NOHIST', 'A', 'CAD', '2021-03-15', '2024-06-28', 'active'), + (105, 105, 'XNYS', 'OVLP', '', 'USD', '2018-01-01', '2024-06-28', 'active'), + (106, 106, 'XNAS', 'IPO25', '', 'USD', '2024-07-01', NULL, 'active'), + (107, 107, 'XTSE', 'NULLSTART', '', 'CAD', NULL, NULL, NULL), + (108, 108, 'XNAS', 'DLST1', '', 'USD', '2015-01-01', '2024-06-30', 'merger_cash'), + (109, 109, 'XNAS', 'DLST2', '', 'USD', '2015-01-01', '2024-06-28', 'active'), + (110, 110, 'XNAS', 'DLST3', '', 'USD', '2015-01-01', '2024-06-28', NULL), + (111, 111, 'XNAS', 'DLST4', '', 'USD', '2015-01-01', '2024-09-15', 'bankruptcy_cancelled'), + (112, 112, 'XNYS', 'WILD', '', 'USD', '2020-01-01', '2024-06-28', 'active'), + (113, 113, 'XNAS', 'OLDCO2', '', 'USD', '2020-01-01', '2024-06-28', 'active'), + (114, 114, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active') + `); + + await client.query(` + INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source) + VALUES + (101, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'), + (101, 'NEWCO', '2024-07-01', NULL, 'eod'), + (102, 'GAPOLD', '2019-01-01', '2024-05-31', 'eod'), + (102, 'GAPNEW', '2024-07-01', NULL, 'eod'), + (103, 'FUTROOT', '2024-07-15', NULL, 'eod'), + (105, 'OVLP1', '2018-01-01', NULL, 'eod'), + (105, 'OVLPZ', '2023-01-01', NULL, 'eod'), + (105, 'OVLPA', '2023-01-01', NULL, 'eod') + `); + + await client.query('COMMIT'); + } catch (err) { + await client.query('ROLLBACK'); + throw err; + } finally { + client.release(); + } +} + +describe('PostgreSQL symbol search safety guard', () => { + test('rejects unsafe database targets before connecting', () => { + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') + ).toThrow('Dedicated stock_bot_safety database required'); + expect( + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') + ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); + }); +}); + +describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { + test('enforces as-of-cutoff ticker resolution, root suppression, and listed_from bounds', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); + + // (a)/(g) Post-cutoff rename: OLDCO is valid on 2024-06-30; NEWCO starts 2024-07-01 and is invisible even as ticker_root + const oldcoRows = await port.searchSymbols({ + query: 'OLDCO', + limit: 1, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(oldcoRows.map(r => r.listingId)).toEqual([101, 113, 114]); + expect(oldcoRows[0]).toEqual({ + listingId: 101, + instrumentId: 101, + ticker: 'OLDCO', + classSuffix: null, + name: 'Renamed Holdings Inc', + mic: 'XNAS', + currency: 'USD', + isin: 'US1010000001', + firstBarDate: '2018-01-02', + lastBarDate: '2024-12-31', + delistedAt: null, + }); + + const newcoRows = await port.searchSymbols({ + query: 'NEWCO', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(newcoRows).toEqual([]); + + // Expired-but-known fallback (step 3c): GAPNEW is future-only root, falls back to GAPOLD + const gapOldRows = await port.searchSymbols({ + query: 'GAPOLD', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(gapOldRows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 102, ticker: 'GAPOLD' }, + ]); + const gapNewRows = await port.searchSymbols({ + query: 'GAPNEW', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(gapNewRows).toEqual([]); + + // (h) Future-only root with no prior history: excluded by root, name, and ISIN searches + expect( + await port.searchSymbols({ + query: 'FUTROOT', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toEqual([]); + expect( + await port.searchSymbols({ + query: 'Stealth Future', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toEqual([]); + expect( + await port.searchSymbols({ + query: 'US1030000003', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toEqual([]); + + // (i) No history rows at all: falls back to ticker_root + const noHistRows = await port.searchSymbols({ + query: 'NOHIST', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(noHistRows).toEqual([ + { + listingId: 104, + instrumentId: 104, + ticker: 'NOHIST', + classSuffix: 'A', + name: 'No History Metals', + mic: 'XTSE', + currency: 'CAD', + isin: 'CA1040000004', + firstBarDate: '2021-03-15', + lastBarDate: '2024-06-28', + delistedAt: null, + }, + ]); + + // Overlapping valid history: latest valid_from wins, tie-breaking by ticker ASC (OVLPA < OVLPZ) + const overlapRows = await port.searchSymbols({ + query: 'Overlap Equity', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(overlapRows).toHaveLength(1); + expect(overlapRows[0]!.listingId).toBe(105); + expect(overlapRows[0]!.ticker).toBe('OVLPA'); + + // (b) listed_from > cutoff excluded + expect( + await port.searchSymbols({ + query: 'IPO25', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toEqual([]); + + // (c) listed_from IS NULL included + const nullStartRows = await port.searchSymbols({ + query: 'NULLSTART', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(nullStartRows).toHaveLength(1); + expect(nullStartRows[0]!.listingId).toBe(107); + expect(nullStartRows[0]!.firstBarDate).toBeNull(); + expect(nullStartRows[0]!.lastBarDate).toBeNull(); + expect(nullStartRows[0]!.delistedAt).toBeNull(); + }); + + test('supports country filter, case-insensitive exact ISIN, literal wildcards, delisting semantics, explicit schema, and deterministic ordering', async () => { + const f = await createIsolatedFixture(); + // Use admin pool (default search_path) with explicit schema option to verify schema quoting + const port = createPostgresSymbolSearchPort({ + executor: createPgExecutor(f.admin), + schema: f.schema, + }); + + // (d) country: 'CA' returns only CA-venue listings + const caRows = await port.searchSymbols({ + query: 'OLDCO', + limit: 20, + country: 'CA', + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([ + { id: 114, mic: 'XTSE' }, + ]); + + // (e) Case-insensitive exact ISIN match with partial-ISIN negative + const isinRows = await port.searchSymbols({ + query: 'ca1040000004', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(isinRows.map(r => r.listingId)).toEqual([104]); + + const partialIsinRows = await port.searchSymbols({ + query: 'CA104000', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(partialIsinRows).toEqual([]); + + // Literal wildcard matching: %, _, and \ are escaped + const wildRows = await port.searchSymbols({ + query: '100% Pure_Wild\\', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(wildRows.map(r => r.listingId)).toEqual([112]); + + // Delisting boundary: 108 confirmed delisted on cutoff (2024-06-30), 109 active, 110 null reason, 111 future delist (2024-09-15) + const allDelist = await port.searchSymbols({ + query: 'Delist Boundary', + limit: 1, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(allDelist.map(r => ({ id: r.listingId, delistedAt: r.delistedAt }))).toEqual([ + { id: 108, delistedAt: '2024-06-30' }, + { id: 109, delistedAt: null }, + { id: 110, delistedAt: null }, + { id: 111, delistedAt: '2024-09-15' }, + ]); + + const activeAsOfCutoff = await port.searchSymbols({ + query: 'Delist Boundary', + limit: 20, + includeDelisted: false, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(activeAsOfCutoff.map(r => r.listingId)).toEqual([109, 110, 111]); + + // Repeated pinned query produces identical deterministic rows + const repeat = await port.searchSymbols({ + query: 'Delist Boundary', + limit: 1, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(repeat).toEqual(allDelist); + }); + + test('composes with createSearchSymbolsTool through MCP for ranking, truncation, clamping, and future delisting masking', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createSearchSymbolsTool({ + port, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + + const callTool = async (args: Record): Promise => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'mcp-pg-1', + method: 'tools/call', + params: { + name: 'search_symbols', + arguments: args, + }, + }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw!) as { + result: { isError?: boolean; content: Array<{ text: string }> }; + }; + expect(parsed.result.isError).toBeUndefined(); + return JSON.parse(parsed.result.content[0]!.text) as SearchSymbolsResultPayload; + }; + + // Ranking & truncation: exact ticker OLDCO (101) > prefix OLDCO2 (113) > name Alpha Oldco Canada (114) + const oldcoPayload = await callTool({ query: 'OLDCO', limit: 2 }); + expect(oldcoPayload.scope).toBe('vault_fenced'); + expect(oldcoPayload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS); + expect(oldcoPayload.truncated).toBe(true); + expect(oldcoPayload.rowCount).toBe(2); + expect(oldcoPayload.rows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 101, ticker: 'OLDCO' }, + { id: 113, ticker: 'OLDCO2' }, + ]); + // Post-cutoff lastBarDate (2024-12-31) is clamped to vaultCutoffDate (2024-06-30) + expect(oldcoPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE); + + // Future delisting (111: listed_to=2024-09-15, delist_reason=bankruptcy_cancelled) is masked to null and clamped + const futureDelistPayload = await callTool({ + query: 'DLST4', + includeDelisted: false, + }); + expect(futureDelistPayload.rowCount).toBe(1); + expect(futureDelistPayload.rows[0]!.listingId).toBe(111); + expect(futureDelistPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE); + expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull(); + }); +}); From 90ab20c301d8f7cb88cb6afcadb0dfe5cae13b4c Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 08:56:23 -0500 Subject: [PATCH 2/5] =?UTF-8?q?T-158:=20M2.1k=20=E2=80=94=20PostgreSQL=20s?= =?UTF-8?q?ecurity-master=20adapter=20for=20the=20MCP=20copilot=20`search?= =?UTF-8?q?=5Fsymbols`=20tool:=20`SymbolSearchPort`=20over=20an=20injected?= =?UTF-8?q?=20executor=20in=20`libs/research/src/mcp/adapters/postgres-sym?= =?UTF-8?q?bol-search.ts`=20(as-of-cutoff=20ticker=20resolution,=20paramet?= =?UTF-8?q?erized=20SQL,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mcp-symbol-search-adapter.test.ts | 101 ++++++++++++++---- 1 file changed, 81 insertions(+), 20 deletions(-) diff --git a/test/postgres/mcp-symbol-search-adapter.test.ts b/test/postgres/mcp-symbol-search-adapter.test.ts index a66a0b8c..6f5e253f 100644 --- a/test/postgres/mcp-symbol-search-adapter.test.ts +++ b/test/postgres/mcp-symbol-search-adapter.test.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto'; import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; +import { Client, Pool, type PoolConfig } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { @@ -46,21 +46,45 @@ function createPgExecutor(pool: Pool): SymbolSearchExecutor { }; } -async function createIsolatedFixture() { - const safeUrl = assertSafetyDatabaseUrl(url); +function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + + const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; + const options = [...existingOptions, schemaOptions].join(' '); + + return { + connectionString: parsed.toString(), + options, + }; +} + +async function createIsolatedFixture(connectionString: string | undefined = url) { + const safeUrl = assertSafetyDatabaseUrl(connectionString); const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: safeUrl }); await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: safeUrl, - options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, - }); + const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); cleanup.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); + const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + if (schemaRows[0]?.current_schema !== schema) { + throw new Error( + `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` + ); + } + const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, logger @@ -95,7 +119,7 @@ async function seedFixture(pool: Pool): Promise { INSERT INTO instrument (instrument_id, primary_isin, canonical_name, security_type, issuer_country) OVERRIDING SYSTEM VALUE VALUES - (101, 'US1010000001', 'Renamed Holdings Inc', 'common', 'US'), + (101, 'CA1010000001', 'Alpha Oldco Canada', 'common', 'CA'), (102, 'US1020000002', 'Gap Rename Corp', 'common', 'US'), (103, 'US1030000003', 'Stealth Future Ventures', 'common', 'US'), (104, 'CA1040000004', 'No History Metals', 'common', 'CA'), @@ -108,7 +132,7 @@ async function seedFixture(pool: Pool): Promise { (111, 'US1110000011', 'Delist Boundary Future', 'common', 'US'), (112, 'US1120000012', '100% Pure_Wild\\Co', 'common', 'US'), (113, 'US1130000013', 'Second Oldco Group', 'common', 'US'), - (114, 'CA1140000014', 'Alpha Oldco Canada', 'common', 'CA') + (114, 'US1140000014', 'Renamed Holdings Inc', 'common', 'US') `); await client.query(` @@ -118,7 +142,7 @@ async function seedFixture(pool: Pool): Promise { ) OVERRIDING SYSTEM VALUE VALUES - (101, 101, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active'), + (101, 101, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active'), (102, 102, 'XNYS', 'GAPNEW', '', 'USD', '2019-01-01', '2024-12-31', 'active'), (103, 103, 'XNAS', 'FUTROOT', '', 'USD', '2020-01-01', NULL, NULL), (104, 104, 'XTSE', 'NOHIST', 'A', 'CAD', '2021-03-15', '2024-06-28', 'active'), @@ -131,14 +155,14 @@ async function seedFixture(pool: Pool): Promise { (111, 111, 'XNAS', 'DLST4', '', 'USD', '2015-01-01', '2024-09-15', 'bankruptcy_cancelled'), (112, 112, 'XNYS', 'WILD', '', 'USD', '2020-01-01', '2024-06-28', 'active'), (113, 113, 'XNAS', 'OLDCO2', '', 'USD', '2020-01-01', '2024-06-28', 'active'), - (114, 114, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active') + (114, 114, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active') `); await client.query(` INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source) VALUES - (101, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'), - (101, 'NEWCO', '2024-07-01', NULL, 'eod'), + (114, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'), + (114, 'NEWCO', '2024-07-01', NULL, 'eod'), (102, 'GAPOLD', '2019-01-01', '2024-05-31', 'eod'), (102, 'GAPNEW', '2024-07-01', NULL, 'eod'), (103, 'FUTROOT', '2024-07-15', NULL, 'eod'), @@ -169,6 +193,22 @@ describe('PostgreSQL symbol search safety guard', () => { assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); }); + + test('preserves isolated schema search_path precedence over URL startup options', () => { + const schema = 'stock_bot_safety_fixture_options'; + const urlWithOptions = + 'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic'; + const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema); + + expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false); + + const client = new Client(poolConfig); + const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } }) + .connectionParameters.options; + expect(resolvedOptions).toBe( + `-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000` + ); + }); }); describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { @@ -184,15 +224,15 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { vaultCutoffTs: VAULT_CUTOFF_TS, }); expect(oldcoRows.map(r => r.listingId)).toEqual([101, 113, 114]); - expect(oldcoRows[0]).toEqual({ - listingId: 101, - instrumentId: 101, + expect(oldcoRows[2]).toEqual({ + listingId: 114, + instrumentId: 114, ticker: 'OLDCO', classSuffix: null, name: 'Renamed Holdings Inc', mic: 'XNAS', currency: 'USD', - isin: 'US1010000001', + isin: 'US1140000014', firstBarDate: '2018-01-02', lastBarDate: '2024-12-31', delistedAt: null, @@ -325,7 +365,7 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { vaultCutoffTs: VAULT_CUTOFF_TS, }); expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([ - { id: 114, mic: 'XTSE' }, + { id: 101, mic: 'XTSE' }, ]); // (e) Case-insensitive exact ISIN match with partial-ISIN negative @@ -421,14 +461,15 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { return JSON.parse(parsed.result.content[0]!.text) as SearchSymbolsResultPayload; }; - // Ranking & truncation: exact ticker OLDCO (101) > prefix OLDCO2 (113) > name Alpha Oldco Canada (114) + // Ranking & truncation: adapter returns ascending listing_id [101 (name), 113 (prefix), 114 (exact)]; + // MCP tool must re-rank to exact ticker OLDCO (114) > prefix OLDCO2 (113) and drop name match ZOLD (101) const oldcoPayload = await callTool({ query: 'OLDCO', limit: 2 }); expect(oldcoPayload.scope).toBe('vault_fenced'); expect(oldcoPayload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS); expect(oldcoPayload.truncated).toBe(true); expect(oldcoPayload.rowCount).toBe(2); expect(oldcoPayload.rows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ - { id: 101, ticker: 'OLDCO' }, + { id: 114, ticker: 'OLDCO' }, { id: 113, ticker: 'OLDCO2' }, ]); // Post-cutoff lastBarDate (2024-12-31) is clamped to vaultCutoffDate (2024-06-30) @@ -444,4 +485,24 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { expect(futureDelistPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE); expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull(); }); + + test('isolates fixture schema even when the safety database URL includes startup options', async () => { + const parsed = new URL(assertSafetyDatabaseUrl(url)); + parsed.searchParams.set('options', '-c statement_timeout=30000 -c search_path=public'); + + const f = await createIsolatedFixture(parsed.toString()); + const { rows } = await f.pool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + expect(rows[0]?.current_schema).toBe(f.schema); + + const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); + const matches = await port.searchSymbols({ + query: 'OLDCO', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(matches.map(r => r.listingId)).toEqual([101, 113, 114]); + }); }); From acfd6a92daa6e8855f11a676673205895f8eb4e3 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:02:09 -0500 Subject: [PATCH 3/5] T-158: tests --- .../test/mcp-postgres-symbol-search.test.ts | 114 +++++++++++++++--- .../mcp-symbol-search-adapter.test.ts | 91 +++++++++++++- 2 files changed, 180 insertions(+), 25 deletions(-) diff --git a/libs/research/test/mcp-postgres-symbol-search.test.ts b/libs/research/test/mcp-postgres-symbol-search.test.ts index ea9a3edd..d4fb71c5 100644 --- a/libs/research/test/mcp-postgres-symbol-search.test.ts +++ b/libs/research/test/mcp-postgres-symbol-search.test.ts @@ -1,10 +1,10 @@ import { describe, expect, test } from 'bun:test'; import { MarketDataStoreValidationError } from '../src/market-data-store'; import { + createPostgresSymbolSearchPort, PostgresSymbolSearchError, type SymbolSearchExecutor, type SymbolSearchQuery, - createPostgresSymbolSearchPort, } from '../src/mcp/index'; interface RecordedCall { @@ -70,13 +70,7 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { expect(call.text).not.toContain(';'); expect(call.text).not.toContain(injection); expect(call.text).not.toContain('DROP TABLE'); - expect(call.params).toEqual([ - '2024-06-30', - `%${injection}%`, - injection, - null, - true, - ]); + expect(call.params).toEqual(['2024-06-30', `%${injection}%`, injection, null, true]); }); test('escapes %, _, and backslash literals in the ILIKE pattern while preserving raw query for ISIN', async () => { @@ -91,13 +85,7 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { expect(fake.calls).toHaveLength(1); const call = fake.calls[0]!; expect(call.text).toContain("ESCAPE '\\'"); - expect(call.params).toEqual([ - '2024-06-30', - '%A\\%B\\_C\\\\D%', - 'A%B_C\\D', - null, - true, - ]); + expect(call.params).toEqual(['2024-06-30', '%A\\%B\\_C\\\\D%', 'A%B_C\\D', null, true]); }); test('converts vaultCutoffTs epoch-ms to UTC calendar date across midnight boundaries', async () => { @@ -173,10 +161,16 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { expect(sql).toContain('h_past.valid_from <= $1::date'); // Both fallback resolution and root ILIKE predicate are gated by NOT root_state.is_future expect(sql).toContain('WHEN NOT root_state.is_future THEN l.ticker_root'); - expect(sql).toContain("OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')"); + expect(sql).toContain( + "OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')" + ); // delisted_at derivation and $5 filter - expect(sql).toContain("WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to"); - expect(sql).toContain('($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)'); + expect(sql).toContain( + "WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to" + ); + expect(sql).toContain( + '($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)' + ); }); test('quotes optional validated schema on all security-master tables and omits prefix when unset', async () => { @@ -302,7 +296,9 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { for (const opts of invalidOptions) { let caught: unknown; try { - createPostgresSymbolSearchPort(opts as Parameters[0]); + createPostgresSymbolSearchPort( + opts as Parameters[0] + ); } catch (err) { caught = err; } @@ -411,3 +407,83 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { ); }); }); + +describe('createPostgresSymbolSearchPort (QA edge cases)', () => { + test('accepts a pg.Pool-shaped executor whose query method lives on the prototype', async () => { + class PrototypeExecutor { + readonly calls: RecordedCall[] = []; + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + this.calls.push({ text, params }); + return { rows: [makeRawRow()] as unknown as readonly Row[] }; + } + } + const executor = new PrototypeExecutor(); + const port = createPostgresSymbolSearchPort({ executor }); + + const rows = await port.searchSymbols(BASE_QUERY); + + expect(rows.map(r => r.listingId)).toEqual([101]); + expect(executor.calls).toHaveLength(1); + }); + + test('accepts minimal valid schema identifiers and quotes them', async () => { + for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor, schema }); + await port.searchSymbols(BASE_QUERY); + expect(fake.calls[0]!.text).toContain(`FROM "${schema}".listing l`); + } + }); + + test('propagates executor failures unchanged without retrying', async () => { + const failure = new Error('connection terminated'); + let attempts = 0; + const executor: SymbolSearchExecutor = { + async query() { + attempts += 1; + throw failure; + }, + }; + const port = createPostgresSymbolSearchPort({ executor }); + + await expect(port.searchSymbols(BASE_QUERY)).rejects.toBe(failure); + expect(attempts).toBe(1); + }); + + test('binds the UTC calendar date for an instant that is already the next day east of UTC', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + // 2024-02-29T23:30Z is 2024-03-01 in UTC+1 zones; the adapter must still bind the UTC date. + await port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Date.UTC(2024, 1, 29, 23, 30) }); + + expect(fake.calls[0]!.params?.[0]).toBe('2024-02-29'); + }); + + test('returns an empty array (not null) when the executor returns no rows', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + expect(await port.searchSymbols(BASE_QUERY)).toEqual([]); + }); + + test('rejects the whole result when any row in a batch is malformed', async () => { + const fake = createFakeExecutor([ + makeRawRow(), + makeRawRow({ listing_id: 102, last_bar_date: '2024-04-31' }), + ]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + let caught: unknown; + try { + await port.searchSymbols(BASE_QUERY); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresSymbolSearchError); + expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW'); + }); +}); diff --git a/test/postgres/mcp-symbol-search-adapter.test.ts b/test/postgres/mcp-symbol-search-adapter.test.ts index 6f5e253f..d0270313 100644 --- a/test/postgres/mcp-symbol-search-adapter.test.ts +++ b/test/postgres/mcp-symbol-search-adapter.test.ts @@ -4,11 +4,11 @@ import { Client, Pool, type PoolConfig } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { - type SearchSymbolsResultPayload, - type SymbolSearchExecutor, createMcpServer, createPostgresSymbolSearchPort, createSearchSymbolsTool, + type SearchSymbolsResultPayload, + type SymbolSearchExecutor, } from '../../libs/research/src/mcp/index'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); @@ -182,7 +182,9 @@ async function seedFixture(pool: Pool): Promise { describe('PostgreSQL symbol search safety guard', () => { test('rejects unsafe database targets before connecting', () => { - expect(() => assertSafetyDatabaseUrl(undefined)).toThrow('Dedicated stock_bot_safety database required'); + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( + 'Dedicated stock_bot_safety database required' + ); expect(() => assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') ).toThrow('Dedicated stock_bot_safety database required'); @@ -364,9 +366,7 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { includeDelisted: true, vaultCutoffTs: VAULT_CUTOFF_TS, }); - expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([ - { id: 101, mic: 'XTSE' }, - ]); + expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([{ id: 101, mic: 'XTSE' }]); // (e) Case-insensitive exact ISIN match with partial-ISIN negative const isinRows = await port.searchSymbols({ @@ -486,6 +486,85 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull(); }); + test('moves as-of resolution with the cutoff date, including a near-midnight UTC instant', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); + const search = (query: string, vaultCutoffTs: number, includeDelisted = true) => + port.searchSymbols({ query, limit: 20, includeDelisted, vaultCutoffTs }); + const lastMsOfCutoffDay = Date.UTC(2024, 5, 30, 23, 59, 59, 999); + const dayAfterCutoff = Date.UTC(2024, 6, 1, 0, 0, 0, 0); + + // Last millisecond of 2024-06-30 UTC still resolves the pre-rename ticker. + const lateOld = await search('OLDCO', lastMsOfCutoffDay); + expect(lateOld.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 101, ticker: 'ZOLD' }, + { id: 113, ticker: 'OLDCO2' }, + { id: 114, ticker: 'OLDCO' }, + ]); + expect(await search('NEWCO', lastMsOfCutoffDay)).toEqual([]); + + // One day later the rename, the GAPNEW start and the IPO become visible, and OLDCO no longer resolves to 114. + const nextOld = await search('OLDCO', dayAfterCutoff); + expect(nextOld.map(r => r.listingId)).toEqual([101, 113]); + const nextNew = await search('NEWCO', dayAfterCutoff); + expect(nextNew.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 114, ticker: 'NEWCO' }, + ]); + const nextGap = await search('GAPNEW', dayAfterCutoff); + expect(nextGap.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 102, ticker: 'GAPNEW' }, + ]); + expect(await search('GAPOLD', dayAfterCutoff)).toEqual([]); + expect((await search('IPO25', dayAfterCutoff)).map(r => r.listingId)).toEqual([106]); + + // A cutoff on the future delisting date makes that delisting confirmed and filterable. + const onFutureDelist = await search('Delist Boundary', Date.UTC(2024, 8, 15), false); + expect(onFutureDelist.map(r => r.listingId)).toEqual([109, 110]); + }); + + test('projects identical calendar dates regardless of the session TimeZone', async () => { + const f = await createIsolatedFixture(); + const client = await f.pool.connect(); + try { + await client.query("SET TimeZone = 'Pacific/Kiritimati'"); + const executor: SymbolSearchExecutor = { + query>(text: string, params?: readonly unknown[]) { + return client.query( + text, + params === undefined ? undefined : [...params] + ) as unknown as Promise<{ + readonly rows: readonly Row[]; + }>; + }, + }; + const port = createPostgresSymbolSearchPort({ executor }); + + const rows = await port.searchSymbols({ + query: 'Delist Boundary', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + expect( + rows.map(r => ({ + id: r.listingId, + first: r.firstBarDate, + last: r.lastBarDate, + delistedAt: r.delistedAt, + })) + ).toEqual([ + { id: 108, first: '2015-01-01', last: '2024-06-30', delistedAt: '2024-06-30' }, + { id: 109, first: '2015-01-01', last: '2024-06-28', delistedAt: null }, + { id: 110, first: '2015-01-01', last: '2024-06-28', delistedAt: null }, + { id: 111, first: '2015-01-01', last: '2024-09-15', delistedAt: '2024-09-15' }, + ]); + } finally { + await client.query('RESET TimeZone'); + client.release(); + } + }); + test('isolates fixture schema even when the safety database URL includes startup options', async () => { const parsed = new URL(assertSafetyDatabaseUrl(url)); parsed.searchParams.set('options', '-c statement_timeout=30000 -c search_path=public'); From d65016c851c686fb2b4e3c17173eb38e6993cd5a Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:10:20 -0500 Subject: [PATCH 4/5] =?UTF-8?q?T-159:=20M2.1l=20=E2=80=94=20PostgreSQL=20`?= =?UTF-8?q?trial=5Fledger`=20adapter=20for=20the=20MCP=20copilot=20`file?= =?UTF-8?q?=5Ffinding`=20tool:=20`TrialRefLookupPort`=20over=20an=20inject?= =?UTF-8?q?ed=20executor=20in=20`libs/research/src/mcp/adapters/postgres-t?= =?UTF-8?q?rial-ref.ts`=20(research-visible=20=3D=20`sample=5Fend`=20befor?= =?UTF-8?q?e=20the=20Vault=20cutoff=20date,=20parameterized=20SQL,=20no=20?= =?UTF-8?q?new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/mcp/adapters/postgres-trial-ref.ts | 150 +++++++ libs/research/src/mcp/index.ts | 1 + .../test/mcp-postgres-trial-ref.test.ts | 420 ++++++++++++++++++ 3 files changed, 571 insertions(+) create mode 100644 libs/research/src/mcp/adapters/postgres-trial-ref.ts create mode 100644 libs/research/test/mcp-postgres-trial-ref.test.ts diff --git a/libs/research/src/mcp/adapters/postgres-trial-ref.ts b/libs/research/src/mcp/adapters/postgres-trial-ref.ts new file mode 100644 index 00000000..249227d0 --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-trial-ref.ts @@ -0,0 +1,150 @@ +/** + * Read-only PostgreSQL `trial_ledger` adapter implementing {@link TrialRefLookupPort} + * for the MCP copilot `file_finding` tool. + * + * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is + * injected via {@link TrialRefExecutor}. + */ + +import type { TrialRefLookupPort } from '../tools/file-finding'; +import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input'; + +const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; +const FOUR_DIGIT_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; +const CANONICAL_POSITIVE_BIGINT_RE = /^[1-9][0-9]{0,18}$/; +const MAX_SIGNED_BIGINT_STR = '9223372036854775807'; + +/** Error codes thrown by {@link PostgresTrialRefError}. */ +export type PostgresTrialRefErrorCode = + | 'INVALID_EXECUTOR' + | 'INVALID_SCHEMA' + | 'INVALID_VAULT_CUTOFF'; + +/** Typed validation error thrown by the PostgreSQL trial-ref lookup adapter. */ +export class PostgresTrialRefError extends RangeError { + readonly code: PostgresTrialRefErrorCode; + + constructor(code: PostgresTrialRefErrorCode, message: string) { + super(message); + this.name = 'PostgresTrialRefError'; + this.code = code; + 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 TrialRefExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** Factory options for {@link createPostgresTrialRefLookupPort}. */ +export interface PostgresTrialRefLookupPortOptions { + readonly executor: TrialRefExecutor; + /** Authoritative UTC epoch-ms Vault cutoff; trials with `sample_end < cutoffDate` are research-visible. */ + readonly vaultCutoffTs: number; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; +} + +interface TrialVisibilityRow { + readonly visible?: unknown; +} + +function isCanonicalPositiveBigInt(value: unknown): value is string { + if (typeof value !== 'string' || !CANONICAL_POSITIVE_BIGINT_RE.test(value)) { + return false; + } + if (value.length === MAX_SIGNED_BIGINT_STR.length && value > MAX_SIGNED_BIGINT_STR) { + return false; + } + return true; +} + +function buildTrialVisibilitySql(schemaPrefix: string): string { + return `SELECT 1 AS visible FROM ${schemaPrefix}trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1`; +} + +function validateFactoryOptions(options: PostgresTrialRefLookupPortOptions): { + readonly executor: TrialRefExecutor; + readonly cutoffDate: string; + readonly schemaPrefix: string; +} { + if (typeof options !== 'object' || options === null) { + throw new PostgresTrialRefError( + 'INVALID_EXECUTOR', + 'Invalid options: expected an object with a TrialRefExecutor.' + ); + } + + const { executor, vaultCutoffTs, schema } = options; + if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { + throw new PostgresTrialRefError( + 'INVALID_EXECUTOR', + 'Invalid executor: expected an object with a callable query(text, params?) method.' + ); + } + + let schemaPrefix = ''; + if (schema !== undefined) { + if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) { + throw new PostgresTrialRefError( + 'INVALID_SCHEMA', + 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' + ); + } + schemaPrefix = `"${schema}".`; + } + + let validatedCutoffTs: number; + try { + validatedCutoffTs = validateVaultCutoffTs(vaultCutoffTs); + } catch { + throw new PostgresTrialRefError( + 'INVALID_VAULT_CUTOFF', + 'Invalid vaultCutoffTs: expected a finite safe-integer epoch-ms timestamp within ECMAScript Date bounds.' + ); + } + + const cutoffDate = utcDateOf(validatedCutoffTs); + if (!FOUR_DIGIT_DATE_RE.test(cutoffDate) || cutoffDate.startsWith('0000-')) { + throw new PostgresTrialRefError( + 'INVALID_VAULT_CUTOFF', + 'Invalid vaultCutoffTs: resolved UTC date must be a four-digit PostgreSQL calendar date (0001-01-01 through 9999-12-31).' + ); + } + + return { executor, cutoffDate, schemaPrefix }; +} + +/** + * Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger`. + * + * Only trials with `sample_end < cutoffDate` (exclusive UTC Vault cutoff date) are + * research-visible. Unknown, malformed, and Vault-only references all return `false`. + */ +export function createPostgresTrialRefLookupPort( + options: PostgresTrialRefLookupPortOptions +): TrialRefLookupPort { + const { executor, cutoffDate, schemaPrefix } = validateFactoryOptions(options); + const sql = buildTrialVisibilitySql(schemaPrefix); + + return { + async hasResearchVisibleTrial(trialRef: string): Promise { + if (!isCanonicalPositiveBigInt(trialRef)) { + return false; + } + + const result = await executor.query(sql, [trialRef, cutoffDate]); + if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { + throw new TypeError('Invalid executor response: expected an object with a rows array.'); + } + return result.rows.length > 0; + }, + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index f8f50f75..e598bcfa 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,4 +1,5 @@ export * from './adapters/postgres-symbol-search'; +export * from './adapters/postgres-trial-ref'; export * from './copilot-server'; export * from './protocol'; export * from './server'; diff --git a/libs/research/test/mcp-postgres-trial-ref.test.ts b/libs/research/test/mcp-postgres-trial-ref.test.ts new file mode 100644 index 00000000..614e6d18 --- /dev/null +++ b/libs/research/test/mcp-postgres-trial-ref.test.ts @@ -0,0 +1,420 @@ +import { describe, expect, test } from 'bun:test'; +import { + type AppendFindingResult, + FILE_FINDING_ERROR_FILING_FAILED, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + FILE_FINDING_INITIAL_STATUS, + type FileFindingResultPayload, + type FiledFindingRecord, + type FindingWritePort, + PostgresTrialRefError, + type TrialRefExecutor, + createFileFindingTool, + createMcpServer, + createPostgresTrialRefLookupPort, +} from '../src/mcp/index'; +import { utcDateOf } from '../src/mcp/tools/vault-fenced-input'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function createFakeExecutor(rows: readonly Record[] = []): { + readonly calls: RecordedCall[]; + readonly executor: TrialRefExecutor; +} { + const calls: RecordedCall[] = []; + const executor: TrialRefExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return { rows: rows as readonly Row[] }; + }, + }; + return { calls, executor }; +} + +function createFakeWritePort(): { + readonly appended: FiledFindingRecord[]; + readonly port: FindingWritePort; +} { + const appended: FiledFindingRecord[] = []; + const port: FindingWritePort = { + async appendFinding(record: FiledFindingRecord): Promise { + appended.push(record); + return { + status: 'created', + id: record.id, + createdAt: record.createdAt, + }; + }, + }; + return { appended, port }; +} + +const CUTOFF_MIDNIGHT_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); // 2025-06-30T00:00:00.000Z + +describe('createPostgresTrialRefLookupPort', () => { + test('rejects missing or non-callable executor with INVALID_EXECUTOR', () => { + const invalidOptions: unknown[] = [ + null, + undefined, + {}, + { executor: null, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, + { executor: {}, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, + { executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, + ]; + + for (const opts of invalidOptions) { + let caught: unknown; + try { + createPostgresTrialRefLookupPort( + opts as Parameters[0] + ); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect(caught).toBeInstanceOf(RangeError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); + } + }); + + test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { + const fake = createFakeExecutor([]); + const badSchemas: unknown[] = [ + '', + 'Bad-Schema', + 'a;drop', + '1schema', + 'bad.name', + 'space name', + 'public"; DROP TABLE trial_ledger; --', + 123, + null, + ]; + + for (const schema of badSchemas) { + let caught: unknown; + try { + createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + schema: schema as string, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_SCHEMA'); + } + + expect(fake.calls).toHaveLength(0); + }); + + test('rejects invalid or extended-year vaultCutoffTs with INVALID_VAULT_CUTOFF', () => { + const fake = createFakeExecutor([]); + const badCutoffs: unknown[] = [ + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + '2025-06-30', + null, + undefined, + 123.45, + Date.parse('+010000-01-01T00:00:00.000Z'), + Date.parse('-000001-01-01T00:00:00.000Z'), + Date.parse('0000-01-01T00:00:00.000Z'), + ]; + + for (const vaultCutoffTs of badCutoffs) { + let caught: unknown; + try { + createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: vaultCutoffTs as number, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF'); + } + + expect(fake.calls).toHaveLength(0); + }); + + test('returns true for a visible trial with one parameterized read-only SELECT and exact params', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + const visible = await port.hasResearchVisibleTrial('42'); + + expect(visible).toBe(true); + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text.trimStart().startsWith('SELECT')).toBe(true); + expect(call.text).not.toContain(';'); + expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); + expect(call.text).toContain('FROM trial_ledger'); + expect(call.text).toContain('trial_id = $1::bigint'); + expect(call.text).toContain('sample_end < $2::date'); + expect(call.text).toContain('LIMIT 1'); + expect(call.params).toEqual(['42', '2025-06-30']); + expect(typeof call.params?.[0]).toBe('string'); + }); + + test('returns false when the executor returns empty rows (unknown or Vault-only trial)', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + const visible = await port.hasResearchVisibleTrial('42'); + + expect(visible).toBe(false); + expect(fake.calls).toHaveLength(1); + expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']); + }); + + test('maps midnight and non-midnight UTC vaultCutoffTs to the same UTC date as utcDateOf', async () => { + const nonMidnightTs = Date.UTC(2025, 5, 30, 23, 59, 59, 999); + const nextDayTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); + + const fakeSameDay = createFakeExecutor([{ visible: 1 }]); + const sameDayPort = createPostgresTrialRefLookupPort({ + executor: fakeSameDay.executor, + vaultCutoffTs: nonMidnightTs, + }); + await sameDayPort.hasResearchVisibleTrial('7'); + expect(fakeSameDay.calls[0]!.params).toEqual(['7', utcDateOf(nonMidnightTs)]); + expect(fakeSameDay.calls[0]!.params?.[1]).toBe('2025-06-30'); + + const fakeNextDay = createFakeExecutor([{ visible: 1 }]); + const nextDayPort = createPostgresTrialRefLookupPort({ + executor: fakeNextDay.executor, + vaultCutoffTs: nextDayTs, + }); + await nextDayPort.hasResearchVisibleTrial('7'); + expect(fakeNextDay.calls[0]!.params).toEqual(['7', '2025-07-01']); + }); + + test('returns false with zero executor calls for malformed, injection-shaped, overflowing, and non-string refs', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + const invalidRefs: unknown[] = [ + '', + ' 42', + '42 ', + '042', + '0', + '-1', + '+1', + '1.0', + '1e3', + '0x10', + '42; DROP TABLE trial_ledger', + '9223372036854775808', + '10000000000000000000', + 42, + 42n, + null, + undefined, + {}, + ]; + + for (const ref of invalidRefs) { + const result = await port.hasResearchVisibleTrial(ref as string); + expect(result).toBe(false); + } + + expect(fake.calls).toHaveLength(0); + }); + + test('queries the maximum signed 64-bit BIGINT verbatim as a string without numeric coercion', async () => { + const maxBigIntRef = '9223372036854775807'; + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + const visible = await port.hasResearchVisibleTrial(maxBigIntRef); + + expect(visible).toBe(true); + expect(fake.calls).toHaveLength(1); + expect(fake.calls[0]!.text).not.toContain(maxBigIntRef); + expect(fake.calls[0]!.params).toEqual([maxBigIntRef, '2025-06-30']); + }); + + test('quotes validated optional schema and leaves table unqualified when omitted', async () => { + const fakeDefault = createFakeExecutor([]); + const defaultPort = createPostgresTrialRefLookupPort({ + executor: fakeDefault.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + await defaultPort.hasResearchVisibleTrial('1'); + expect(fakeDefault.calls[0]!.text).toContain('FROM trial_ledger '); + + const fakeScoped = createFakeExecutor([]); + const scopedPort = createPostgresTrialRefLookupPort({ + executor: fakeScoped.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + schema: 'research_x', + }); + await scopedPort.hasResearchVisibleTrial('1'); + expect(fakeScoped.calls[0]!.text).toContain('FROM "research_x".trial_ledger '); + }); + + test('propagates executor rejections unchanged without retrying', async () => { + const failure = new Error('postgres connection lost'); + let attempts = 0; + const executor: TrialRefExecutor = { + async query() { + attempts += 1; + throw failure; + }, + }; + const port = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure); + expect(attempts).toBe(1); + }); + + test('accepts a pg.Pool-shaped executor with query on its prototype', async () => { + class PoolLikeExecutor { + readonly calls: RecordedCall[] = []; + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + this.calls.push({ text, params }); + return { rows: [{ visible: 1 }] as unknown as readonly Row[] }; + } + } + + const executor = new PoolLikeExecutor(); + const port = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + expect(await port.hasResearchVisibleTrial('99')).toBe(true); + expect(executor.calls).toHaveLength(1); + }); +}); + +describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', () => { + async function callFileFinding( + executor: TrialRefExecutor, + trialRefs: readonly string[] + ): Promise<{ + readonly appended: FiledFindingRecord[]; + readonly result: { readonly content: readonly { type: string; text: string }[]; readonly isError?: boolean }; + }> { + const trialLookup = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + const { appended, port } = createFakeWritePort(); + const tool = createFileFindingTool({ + port, + trialLookup, + newId: () => 'finding-0001', + now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0), + }); + const server = createMcpServer({ + name: 'test-copilot', + version: '0.1.0', + tools: [tool], + }); + + const rawResponse = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: 'file_finding', + arguments: { + kind: 'finding', + title: 'Pre-vault momentum signal', + summary: 'Observed stable rank IC across US equities prior to cutoff.', + trialRefs, + }, + }, + }) + ); + + const parsed = JSON.parse(rawResponse!) as { + readonly result: { + readonly content: readonly { type: string; text: string }[]; + readonly isError?: boolean; + }; + }; + return { appended, result: parsed.result }; + } + + test('files a pending_review finding and returns a created receipt when the trial is visible', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const { appended, result } = await callFileFinding(fake.executor, ['42']); + + expect(result.isError).toBeUndefined(); + const payload = JSON.parse(result.content[0]!.text) as FileFindingResultPayload; + expect(payload).toEqual({ + id: 'finding-0001', + createdAt: '2025-06-29T12:00:00.000Z', + created: true, + }); + expect(appended).toHaveLength(1); + expect(appended[0]).toEqual({ + id: 'finding-0001', + kind: 'finding', + title: 'Pre-vault momentum signal', + status: FILE_FINDING_INITIAL_STATUS, + createdAt: '2025-06-29T12:00:00.000Z', + summary: 'Observed stable rank IC across US equities prior to cutoff.', + trialRefs: ['42'], + evidenceRefs: [], + }); + expect(fake.calls).toHaveLength(1); + expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']); + }); + + test('returns FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF with zero appends when executor returns no rows', async () => { + const fake = createFakeExecutor([]); + const { appended, result } = await callFileFinding(fake.executor, ['42']); + + expect(result.isError).toBe(true); + expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(appended).toHaveLength(0); + expect(fake.calls).toHaveLength(1); + }); + + test('returns FILE_FINDING_ERROR_FILING_FAILED with zero appends when executor rejects', async () => { + const executor: TrialRefExecutor = { + async query() { + throw new Error('database unavailable'); + }, + }; + const { appended, result } = await callFileFinding(executor, ['42']); + + expect(result.isError).toBe(true); + expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(appended).toHaveLength(0); + }); +}); From ae01904cd6720fb0820cfaff91336811506f4850 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:25:59 -0500 Subject: [PATCH 5/5] T-159: tests --- .../test/mcp-postgres-trial-ref.test.ts | 105 +++++++ test/postgres/mcp-trial-ref-adapter.test.ts | 283 ++++++++++++++++++ 2 files changed, 388 insertions(+) create mode 100644 test/postgres/mcp-trial-ref-adapter.test.ts diff --git a/libs/research/test/mcp-postgres-trial-ref.test.ts b/libs/research/test/mcp-postgres-trial-ref.test.ts index 614e6d18..2f8f4868 100644 --- a/libs/research/test/mcp-postgres-trial-ref.test.ts +++ b/libs/research/test/mcp-postgres-trial-ref.test.ts @@ -418,3 +418,108 @@ describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', () expect(appended).toHaveLength(0); }); }); + +describe('createPostgresTrialRefLookupPort (QA edge cases)', () => { + test('queries in-range 19-digit refs and rejects 19-digit refs above the signed BIGINT max', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + expect(await port.hasResearchVisibleTrial('1000000000000000000')).toBe(true); + expect(await port.hasResearchVisibleTrial('9223372036854775806')).toBe(true); + expect(await port.hasResearchVisibleTrial('9223372036854775900')).toBe(false); + expect(await port.hasResearchVisibleTrial('9999999999999999999')).toBe(false); + + expect(fake.calls.map(c => c.params?.[0])).toEqual([ + '1000000000000000000', + '9223372036854775806', + ]); + }); + + test('rejects trailing-newline, tab, fullwidth-digit, and boxed-String refs without querying', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + for (const ref of ['42\n', '\n42', '4\t2', '42', '42\u0000', new String('42')] as unknown[]) { + expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); + } + expect(fake.calls).toHaveLength(0); + }); + + test('accepts the four-digit PostgreSQL calendar bounds 0001-01-01 and 9999-12-31 as cutoff dates', async () => { + const earliest = Date.parse('0001-01-01T00:00:00.000Z'); + const latest = Date.parse('9999-12-31T23:59:59.999Z'); + + for (const [ts, expected] of [ + [earliest, '0001-01-01'], + [latest, '9999-12-31'], + [Date.UTC(1969, 11, 31, 23, 59, 59, 999), '1969-12-31'], + ] as const) { + const fake = createFakeExecutor([]); + const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: ts }); + await port.hasResearchVisibleTrial('5'); + expect(fake.calls[0]!.params).toEqual(['5', expected]); + } + + let caught: unknown; + try { + createPostgresTrialRefLookupPort({ + executor: createFakeExecutor().executor, + vaultCutoffTs: latest + 1, + }); + } catch (err) { + caught = err; + } + expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF'); + }); + + test('freezes the cutoff date and SQL text at construction across repeated lookups', async () => { + const fake = createFakeExecutor([]); + const options = { executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }; + const port = createPostgresTrialRefLookupPort(options); + + await port.hasResearchVisibleTrial('1'); + (options as { vaultCutoffTs: number }).vaultCutoffTs = Date.UTC(2030, 0, 1); + await port.hasResearchVisibleTrial('2'); + + expect(fake.calls).toHaveLength(2); + expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text); + expect(fake.calls[1]!.params).toEqual(['2', '2025-06-30']); + }); + + test('returns true for multiple matching rows and rejects (not false) on a malformed executor response', async () => { + const many = createFakeExecutor([{ visible: 1 }, { visible: 1 }]); + const manyPort = createPostgresTrialRefLookupPort({ + executor: many.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + expect(await manyPort.hasResearchVisibleTrial('3')).toBe(true); + + for (const response of [null, {}, { rows: 'x' }, { rows: null }]) { + const executor: TrialRefExecutor = { + async query() { + return response as unknown as { readonly rows: readonly never[] }; + }, + }; + const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }); + await expect(port.hasResearchVisibleTrial('3')).rejects.toBeInstanceOf(TypeError); + } + }); + + test('propagates a synchronous executor throw as a rejection with the same error', async () => { + const failure = new Error('pool exhausted'); + const executor = { + query() { + throw failure; + }, + } as unknown as TrialRefExecutor; + const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }); + + await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure); + }); +}); diff --git a/test/postgres/mcp-trial-ref-adapter.test.ts b/test/postgres/mcp-trial-ref-adapter.test.ts new file mode 100644 index 00000000..7c78e11f --- /dev/null +++ b/test/postgres/mcp-trial-ref-adapter.test.ts @@ -0,0 +1,283 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool, type PoolClient } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + type AppendFindingResult, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + type FiledFindingRecord, + createFileFindingTool, + createMcpServer, + createPostgresTrialRefLookupPort, + type TrialRefExecutor, +} from '../../libs/research/src/mcp/index'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('mcp-trial-ref-adapter-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); + +// Vault cutoff date 2025-06-30 (exclusive): sample_end must be < 2025-06-30 to be research-visible. +const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); +const MAX_BIGINT_REF = '9223372036854775807'; +// 2^53 + 1 is not representable as a JS number; Number('9007199254740993') === 9007199254740992. +const ABOVE_SAFE_INT_REF = '9007199254740993'; +const ABOVE_SAFE_INT_NEIGHBOR_REF = '9007199254740992'; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +function assertSafetyDatabaseUrl(connectionString: string | undefined): string { + if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + return connectionString; +} + +function createPgExecutor(queryable: Pool | PoolClient): TrialRefExecutor { + return { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + return queryable.query( + text, + params === undefined ? undefined : [...params] + ) as unknown as Promise<{ readonly rows: readonly Row[] }>; + }, + }; +} + +async function createIsolatedFixture() { + const safeUrl = assertSafetyDatabaseUrl(url); + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: safeUrl }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: safeUrl, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + const readOnlyPool = new Pool({ + connectionString: safeUrl, + options: `-c search_path=${schema} -c default_transaction_read_only=on -c statement_timeout=5000`, + }); + cleanup.push(async () => { + await readOnlyPool.end(); + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + // Bootstrap pre-additive tables needed by the research migration track. + for (const filename of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + ]) { + await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + } + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + await runPostgresMigrations(postgres, { track: 'research' }); + await seedTrials(pool); + + return { admin, pool, readOnlyPool, schema }; +} + +async function seedTrials(pool: Pool): Promise { + const trials: readonly (readonly [string, string])[] = [ + ['1', '2025-06-29'], // last research-visible day + ['2', '2025-06-30'], // sample_end == cutoff: Vault-only + ['3', '2025-07-15'], // sample_end after cutoff: Vault-only + [ABOVE_SAFE_INT_REF, '2024-01-31'], + [MAX_BIGINT_REF, '2020-01-31'], + ]; + for (const [trialId, sampleEnd] of trials) { + await pool.query( + `INSERT INTO trial_ledger ( + trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash, + sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series + ) + OVERRIDING SYSTEM VALUE + VALUES ($1::bigint, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), + '2020-01-01'::date, $2::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`, + [trialId, sampleEnd] + ); + } +} + +describe.skipIf(!url)('PostgreSQL MCP trial-ref lookup adapter', () => { + test('exposes only trials with sample_end strictly before the UTC Vault cutoff date', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(f.pool), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + expect(await port.hasResearchVisibleTrial('1')).toBe(true); + expect(await port.hasResearchVisibleTrial('2')).toBe(false); + expect(await port.hasResearchVisibleTrial('3')).toBe(false); + expect(await port.hasResearchVisibleTrial('4')).toBe(false); // unknown + expect(await port.hasResearchVisibleTrial(MAX_BIGINT_REF)).toBe(true); + }); + + test('matches BIGINT ids above 2^53 exactly without numeric coercion', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(f.pool), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_REF)).toBe(true); + expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_NEIGHBOR_REF)).toBe(false); + }); + + test('moves the visibility boundary with the cutoff date, including a near-midnight UTC instant', async () => { + const f = await createIsolatedFixture(); + const executor = createPgExecutor(f.pool); + const lastMsOfCutoffDay = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 59, 59, 999), + }); + const nextDay = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0), + }); + + expect(await lastMsOfCutoffDay.hasResearchVisibleTrial('2')).toBe(false); + expect(await nextDay.hasResearchVisibleTrial('2')).toBe(true); + expect(await nextDay.hasResearchVisibleTrial('3')).toBe(false); + }); + + test('runs in a read-only session and is unaffected by the session TimeZone', async () => { + const f = await createIsolatedFixture(); + const client = await f.readOnlyPool.connect(); + try { + await client.query("SET TimeZone = 'Pacific/Kiritimati'"); + const port = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(client), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + expect(await port.hasResearchVisibleTrial('1')).toBe(true); + expect(await port.hasResearchVisibleTrial('2')).toBe(false); + } finally { + await client.query('RESET TimeZone'); + client.release(); + } + }); + + test('qualifies trial_ledger with an explicit schema when the session search_path does not include it', async () => { + const f = await createIsolatedFixture(); + const client = await f.admin.connect(); + try { + // Pin a search_path that cannot contain trial_ledger, independent of the shared public schema. + await client.query('SET search_path TO pg_catalog'); + const unqualified = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(client), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const qualified = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(client), + vaultCutoffTs: VAULT_CUTOFF_TS, + schema: f.schema, + }); + + expect(await qualified.hasResearchVisibleTrial('1')).toBe(true); + expect(await qualified.hasResearchVisibleTrial('2')).toBe(false); + // Missing relation must surface as a rejection, never as "not visible". + await expect(unqualified.hasResearchVisibleTrial('1')).rejects.toMatchObject({ + code: '42P01', + }); + } finally { + await client.query('RESET search_path'); + client.release(); + } + }); + + test('leaves trial_ledger untouched and never executes an injection-shaped ref', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(f.pool), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + expect(await port.hasResearchVisibleTrial('1 OR 1=1')).toBe(false); + expect(await port.hasResearchVisibleTrial("1'; DELETE FROM trial_ledger; --")).toBe(false); + + const { rows } = await f.pool.query<{ n: string }>('SELECT count(*)::text AS n FROM trial_ledger'); + expect(rows[0]!.n).toBe('5'); + }); + + test('files through createFileFindingTool only when every trial ref is research-visible', async () => { + const f = await createIsolatedFixture(); + const trialLookup = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(f.pool), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const appended: FiledFindingRecord[] = []; + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: { + async appendFinding(record: FiledFindingRecord): Promise { + appended.push(record); + return { status: 'created', id: record.id, createdAt: record.createdAt }; + }, + }, + trialLookup, + newId: () => 'finding-pg-0001', + now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0), + }), + ], + }); + + const call = async (trialRefs: readonly string[]) => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: 'file_finding', + arguments: { + kind: 'finding', + title: 'Pre-vault signal', + summary: 'Research-visible evidence only.', + trialRefs, + }, + }, + }) + ); + return (JSON.parse(raw!) as { result: { isError?: boolean; content: { text: string }[] } }) + .result; + }; + + const mixed = await call(['1', '2']); + expect(mixed.isError).toBe(true); + expect(mixed.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(appended).toHaveLength(0); + + const visible = await call(['1', MAX_BIGINT_REF]); + expect(visible.isError).toBeUndefined(); + expect(appended).toHaveLength(1); + expect(appended[0]!.trialRefs).toEqual(['1', MAX_BIGINT_REF]); + }); +});