From 5654b9cc0519ee6b53b88dc0c45acfde55dd9226 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:35:55 -0500 Subject: [PATCH] =?UTF-8?q?T-161:=20M2.1j=20(re-queue)=20=E2=80=94=20Postg?= =?UTF-8?q?reSQL=20findings=20adapter=20for=20the=20MCP=20copilot:=20`Find?= =?UTF-8?q?ingWritePort`=20(atomic=20idempotent=20append)=20+=20`listFindi?= =?UTF-8?q?ngs`=20/=20`listProviderCaveats`=20readers=20over=20an=20inject?= =?UTF-8?q?ed=20executor=20in=20`libs/research/src/mcp/adapters/postgres-f?= =?UTF-8?q?indings.ts`=20(no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 7 + .../src/mcp/adapters/postgres-findings.ts | 653 +++++++++++++++++ libs/research/src/mcp/index.ts | 1 + .../test/mcp-postgres-findings.test.ts | 674 ++++++++++++++++++ test/postgres/mcp-findings-adapter.test.ts | 537 ++++++++++++++ 5 files changed, 1872 insertions(+) create mode 100644 libs/research/src/mcp/adapters/postgres-findings.ts create mode 100644 libs/research/test/mcp-postgres-findings.test.ts create mode 100644 test/postgres/mcp-findings-adapter.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index cf49f406..2de5f04b 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -264,6 +264,13 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`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. +### PostgreSQL Findings & Provider Caveats Adapter + +- **`createPostgresFindingWritePort({ executor, schema? })`** and **`createPostgresKnowledgeReaders({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `PostgresFindingsExecutor`, `PostgresFindingsOptions`, `PostgresKnowledgeReaders`, `PostgresFindingsError`, and `PostgresFindingsErrorCode`) back `file_finding` (`FindingWritePort`) and the `findings` / `provider_caveats` halves of `read_knowledge` (`Pick`) over `37-research-findings.sql` with zero runtime `pg` dependency. +- **Inputs, schema & row validation:** Validates `executor.query` (`INVALID_EXECUTOR`) and optional `schema` against `^[a-z_][a-z0-9_]*$` (`INVALID_SCHEMA`; defaults to the executor's `search_path`), binds every caller value via `$n` parameters, issues zero `UPDATE`/`DELETE` statements, and fails closed (`INVALID_ROW`) on malformed result envelopes, non-1D/non-string ref arrays, unknown `kind`, or invalid timestamps (converting PostgreSQL `Date` values or strictly parsed timezone-qualified ISO-8601 strings to UTC ISO-8601 output). +- **Atomic idempotency & fresh-snapshot requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass a fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` transaction) so concurrent callers can observe the committed winner. +- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`), and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`), returning all eligible rows ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing. + ### 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-findings.ts b/libs/research/src/mcp/adapters/postgres-findings.ts new file mode 100644 index 00000000..38bfdfb9 --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-findings.ts @@ -0,0 +1,653 @@ +/** + * PostgreSQL adapter for the MCP copilot findings and provider caveats tables + * (`37-research-findings.sql`), implementing {@link FindingWritePort} for + * `file_finding` and the `listFindings` / `listProviderCaveats` readers of + * {@link KnowledgePort} for `read_knowledge`. + * + * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is + * injected via {@link PostgresFindingsExecutor}. + */ + +import { + type AppendFindingResult, + FILE_FINDING_KINDS, + type FileFindingKind, + type FiledFindingComparablePayload, + type FiledFindingRecord, + type FindingWritePort, + areFiledFindingPayloadsEqual, +} from '../tools/file-finding'; +import type { + FindingQuery, + FindingRecord, + KnowledgePort, + ProviderCaveatQuery, + ProviderCaveatRecord, +} from '../tools/read-knowledge'; +import { MAX_ECMASCRIPT_EPOCH_MS } from '../tools/vault-fenced-input'; + +const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; +const ISO_INSTANT_RE = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/; +const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const FILE_FINDING_KIND_SET: ReadonlySet = new Set(FILE_FINDING_KINDS); + +/** Error codes thrown by {@link PostgresFindingsError}. */ +export type PostgresFindingsErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | 'INVALID_ROW'; + +/** Typed validation error thrown by the PostgreSQL findings adapter. */ +export class PostgresFindingsError extends RangeError { + readonly code: PostgresFindingsErrorCode; + + constructor(code: PostgresFindingsErrorCode, message: string) { + super(message); + this.name = 'PostgresFindingsError'; + 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. + * + * For {@link createPostgresFindingWritePort}, the executor should run each call on + * a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`) rather than inside a + * `REPEATABLE READ` / `SERIALIZABLE` transaction so concurrent idempotent callers + * can observe the committed winner after `ON CONFLICT ... DO NOTHING`. + */ +export interface PostgresFindingsExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** Factory options for {@link createPostgresFindingWritePort} and {@link createPostgresKnowledgeReaders}. */ +export interface PostgresFindingsOptions { + readonly executor: PostgresFindingsExecutor; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; +} + +/** PostgreSQL-backed subset of {@link KnowledgePort} (`findings` and `provider_caveats`). */ +export type PostgresKnowledgeReaders = Pick; + +interface RawFindingReceiptRow { + readonly id: unknown; + readonly created_at: unknown; +} + +interface RawStoredFindingForReplayRow { + readonly id: unknown; + readonly kind: unknown; + readonly title: unknown; + readonly summary: unknown; + readonly created_at: unknown; + readonly trial_refs: unknown; + readonly evidence_refs: unknown; +} + +interface RawFindingRow { + readonly id: unknown; + readonly title: unknown; + readonly status: unknown; + readonly created_at: unknown; + readonly summary: unknown; + readonly trial_refs: unknown; + readonly evidence_refs: unknown; +} + +interface RawProviderCaveatRow { + readonly id: unknown; + readonly provider: unknown; + readonly dataset: unknown; + readonly caveat: unknown; + readonly created_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 utcDateMs( + year: number, + monthIndex: number, + day: number, + hours: number, + minutes: number, + seconds: number, + ms: number +): number { + const date = new Date(0); + date.setUTCFullYear(year, monthIndex, day); + date.setUTCHours(hours, minutes, seconds, ms); + return date.getTime(); +} + +function escapeLikePattern(value: string): string { + return value.replace(/[\\%_]/g, '\\$&'); +} + +function quoteTable(schemaPrefix: string, table: string): string { + return `${schemaPrefix}${table}`; +} + +function validateFactoryOptions(options: PostgresFindingsOptions): { + readonly executor: PostgresFindingsExecutor; + readonly schemaPrefix: string; +} { + if (typeof options !== 'object' || options === null) { + throw new PostgresFindingsError( + 'INVALID_EXECUTOR', + 'Invalid options: expected an object with a PostgresFindingsExecutor.' + ); + } + + const { executor, schema } = options; + if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { + throw new PostgresFindingsError( + '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 PostgresFindingsError( + 'INVALID_SCHEMA', + 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' + ); + } + + return { executor, schemaPrefix: `"${schema}".` }; +} + +function extractRows(result: unknown): readonly Row[] { + if ( + typeof result !== 'object' || + result === null || + !Array.isArray((result as { readonly rows?: unknown }).rows) + ) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid executor response: expected an object with a rows array.' + ); + } + return (result as { readonly rows: readonly Row[] }).rows; +} + +function parseNonEmptyString(value: unknown, field: string): string { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a non-empty string.` + ); + } + return value; +} + +function parseFindingKind(value: unknown): FileFindingKind { + if (typeof value !== 'string' || !FILE_FINDING_KIND_SET.has(value)) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings row: "kind" must be "finding" or "dead_end".' + ); + } + return value as FileFindingKind; +} + +function parseStringArray(value: unknown, field: string): readonly string[] { + if (!Array.isArray(value)) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a one-dimensional string array.` + ); + } + const result: string[] = []; + for (let i = 0; i < value.length; i += 1) { + const entry: unknown = value[i]; + if (typeof entry !== 'string') { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}[${i}]" must be a string.` + ); + } + result.push(entry); + } + return result; +} + +function parseTimestampIso(value: unknown, field: string): string { + if (value instanceof Date) { + const ms = value.getTime(); + if (!Number.isFinite(ms) || Math.abs(ms) >= MAX_ECMASCRIPT_EPOCH_MS) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a finite Date.` + ); + } + return new Date(ms).toISOString(); + } + + if (typeof value !== 'string') { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a Date or timezone-qualified ISO-8601 timestamp string.` + ); + } + + const match = ISO_INSTANT_RE.exec(value); + if (match === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a timezone-qualified ISO-8601 timestamp string.` + ); + } + + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const hours = Number(match[4]); + const minutes = Number(match[5]); + const seconds = Number(match[6]); + const fractional = match[7]; + const tzToken = match[8]; + const tzSign = match[9]; + const tzHoursRaw = match[10]; + const tzMinutesRaw = match[11]; + + if (month < 1 || month > 12) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range calendar month.` + ); + } + const maxDay = daysInUtcMonth(year, month - 1); + if (day < 1 || day > maxDay) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range calendar day.` + ); + } + if (hours > 23 || minutes > 59 || seconds > 59) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range time of day.` + ); + } + + let ms = 0; + if (fractional !== undefined) { + ms = Number(fractional.slice(0, 3).padEnd(3, '0')); + } + + let offsetMs = 0; + if (tzToken !== 'Z') { + const offsetHours = Number(tzHoursRaw); + const offsetMinutes = Number(tzMinutesRaw); + if (offsetHours > 23 || offsetMinutes > 59) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range timezone offset.` + ); + } + const sign = tzSign === '+' ? 1 : -1; + offsetMs = sign * (offsetHours * 60 + offsetMinutes) * 60_000; + } + + const epochMs = utcDateMs(year, month - 1, day, hours, minutes, seconds, ms) - offsetMs; + if (!Number.isFinite(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" is outside the valid ECMAScript timestamp range.` + ); + } + + return new Date(epochMs).toISOString(); +} + +function parseReceiptRow(raw: unknown): { readonly id: string; readonly createdAt: string } { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings receipt row: expected a non-null object.' + ); + } + const row = raw as RawFindingReceiptRow; + return { + id: parseNonEmptyString(row.id, 'id'), + createdAt: parseTimestampIso(row.created_at, 'created_at'), + }; +} + +function parseStoredFindingForReplayRow(raw: unknown): { + readonly id: string; + readonly createdAt: string; + readonly payload: FiledFindingComparablePayload; +} { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings replay row: expected a non-null object.' + ); + } + const row = raw as RawStoredFindingForReplayRow; + const id = parseNonEmptyString(row.id, 'id'); + const kind = parseFindingKind(row.kind); + const title = parseNonEmptyString(row.title, 'title'); + const summary = parseNonEmptyString(row.summary, 'summary'); + const createdAt = parseTimestampIso(row.created_at, 'created_at'); + const trialRefs = parseStringArray(row.trial_refs, 'trial_refs'); + const evidenceRefs = parseStringArray(row.evidence_refs, 'evidence_refs'); + + return { + id, + createdAt, + payload: { + kind, + title, + summary, + trialRefs, + evidenceRefs, + }, + }; +} + +function parseFindingRow(raw: unknown): FindingRecord { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings row: expected a non-null object.' + ); + } + const row = raw as RawFindingRow; + return { + id: parseNonEmptyString(row.id, 'id'), + title: parseNonEmptyString(row.title, 'title'), + status: parseNonEmptyString(row.status, 'status'), + createdAt: parseTimestampIso(row.created_at, 'created_at'), + summary: parseNonEmptyString(row.summary, 'summary'), + trialRefs: parseStringArray(row.trial_refs, 'trial_refs'), + evidenceRefs: parseStringArray(row.evidence_refs, 'evidence_refs'), + }; +} + +function parseProviderCaveatRow(raw: unknown): ProviderCaveatRecord { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid provider_caveats row: expected a non-null object.' + ); + } + const row = raw as RawProviderCaveatRow; + return { + id: parseNonEmptyString(row.id, 'id'), + provider: parseNonEmptyString(row.provider, 'provider'), + dataset: parseNonEmptyString(row.dataset, 'dataset'), + caveat: parseNonEmptyString(row.caveat, 'caveat'), + createdAt: parseTimestampIso(row.created_at, 'created_at'), + }; +} + +function isPostgresUniqueViolation(err: unknown): boolean { + return ( + typeof err === 'object' && + err !== null && + (err as { readonly code?: unknown }).code === '23505' + ); +} + +function buildInsertFindingSql(schemaPrefix: string, keyed: boolean): string { + const findingsTable = quoteTable(schemaPrefix, 'findings'); + const lines = [ + `INSERT INTO ${findingsTable} (`, + ' id,', + ' kind,', + ' title,', + ' summary,', + ' status,', + ' created_at,', + ' trial_refs,', + ' evidence_refs,', + ' idempotency_key', + ')', + 'VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9)', + ]; + if (keyed) { + lines.push('ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING'); + } + lines.push('RETURNING id, created_at'); + return lines.join('\n'); +} + +function buildSelectByIdempotencyKeySql(schemaPrefix: string): string { + const findingsTable = quoteTable(schemaPrefix, 'findings'); + return [ + 'SELECT', + ' id,', + ' kind,', + ' title,', + ' summary,', + ' created_at,', + ' trial_refs,', + ' evidence_refs', + `FROM ${findingsTable}`, + 'WHERE idempotency_key = $1::text', + ].join('\n'); +} + +/** + * Creates an append-only PostgreSQL {@link FindingWritePort} backed by the + * `findings` table (`37-research-findings.sql`). + */ +export function createPostgresFindingWritePort(options: PostgresFindingsOptions): FindingWritePort { + const { executor, schemaPrefix } = validateFactoryOptions(options); + const unkeyedInsertSql = buildInsertFindingSql(schemaPrefix, false); + const keyedInsertSql = buildInsertFindingSql(schemaPrefix, true); + const selectByKeySql = buildSelectByIdempotencyKeySql(schemaPrefix); + + return { + async appendFinding( + record: FiledFindingRecord, + idempotencyKey?: string + ): Promise { + const insertParams: readonly unknown[] = [ + record.id, + record.kind, + record.title, + record.summary, + record.status, + record.createdAt, + [...record.trialRefs], + [...record.evidenceRefs], + idempotencyKey ?? null, + ]; + + if (idempotencyKey === undefined) { + const result = await executor.query(unkeyedInsertSql, insertParams); + const rows = extractRows(result); + if (rows.length !== 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected 1 inserted findings row, received ${rows.length}.` + ); + } + const receipt = parseReceiptRow(rows[0]); + return { + status: 'created', + id: receipt.id, + createdAt: receipt.createdAt, + }; + } + + let insertRows: readonly RawFindingReceiptRow[]; + try { + const result = await executor.query(keyedInsertSql, insertParams); + insertRows = extractRows(result); + } catch (err) { + if (!isPostgresUniqueViolation(err)) { + throw err; + } + // A concurrent same-ID retry can collide on the primary key before the + // partial idempotency_key index; resolve only if the stored row for this + // key has the exact same ID, otherwise propagate the primary-key error. + const lookupResult = await executor.query(selectByKeySql, [ + idempotencyKey, + ]); + const lookupRows = extractRows(lookupResult); + if (lookupRows.length === 0) { + throw err; + } + if (lookupRows.length > 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected at most 1 stored finding for idempotency_key, received ${lookupRows.length}.` + ); + } + const stored = parseStoredFindingForReplayRow(lookupRows[0]); + if (stored.id !== record.id) { + throw err; + } + return areFiledFindingPayloadsEqual(stored.payload, record) + ? { status: 'replayed', id: stored.id, createdAt: stored.createdAt } + : { status: 'conflict' }; + } + + if (insertRows.length === 1) { + const receipt = parseReceiptRow(insertRows[0]); + return { + status: 'created', + id: receipt.id, + createdAt: receipt.createdAt, + }; + } + + if (insertRows.length > 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected 0 or 1 inserted findings rows, received ${insertRows.length}.` + ); + } + + // Separate SELECT on a fresh READ COMMITTED snapshot so a concurrent winner + // committed during ON CONFLICT DO NOTHING is visible. + const winnerResult = await executor.query(selectByKeySql, [ + idempotencyKey, + ]); + const winnerRows = extractRows(winnerResult); + if (winnerRows.length !== 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected 1 stored finding for idempotency_key after conflict, received ${winnerRows.length}.` + ); + } + + const stored = parseStoredFindingForReplayRow(winnerRows[0]); + return areFiledFindingPayloadsEqual(stored.payload, record) + ? { status: 'replayed', id: stored.id, createdAt: stored.createdAt } + : { status: 'conflict' }; + }, + }; +} + +/** + * Creates read-only PostgreSQL readers (`listFindings` and `listProviderCaveats`) + * for composing {@link KnowledgePort} in `read_knowledge`. + */ +export function createPostgresKnowledgeReaders( + options: PostgresFindingsOptions +): PostgresKnowledgeReaders { + const { executor, schemaPrefix } = validateFactoryOptions(options); + const findingsTable = quoteTable(schemaPrefix, 'findings'); + const caveatsTable = quoteTable(schemaPrefix, 'provider_caveats'); + + return { + async listFindings(q: FindingQuery): Promise { + const lines = [ + 'SELECT', + ' id,', + ' title,', + ' status,', + ' created_at,', + ' summary,', + ' trial_refs,', + ' evidence_refs', + `FROM ${findingsTable}`, + ]; + const params: unknown[] = []; + + if (q.id !== undefined) { + params.push(q.id); + lines.push('WHERE id = $1::text'); + } else if (q.query !== undefined) { + params.push(`%${escapeLikePattern(q.query)}%`); + lines.push("WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'"); + } + + lines.push('ORDER BY id ASC'); + + const result = await executor.query(lines.join('\n'), params); + const rows = extractRows(result); + const mapped: FindingRecord[] = []; + for (let i = 0; i < rows.length; i += 1) { + mapped.push(parseFindingRow(rows[i])); + } + return mapped; + }, + + async listProviderCaveats(q: ProviderCaveatQuery): Promise { + const lines = [ + 'SELECT', + ' id,', + ' provider,', + ' dataset,', + ' caveat,', + ' created_at', + `FROM ${caveatsTable}`, + ]; + const conditions: string[] = []; + const params: unknown[] = []; + + if (q.provider !== undefined) { + params.push(q.provider); + conditions.push(`lower(provider) = lower($${params.length}::text)`); + } + + if (q.id !== undefined) { + params.push(q.id); + conditions.push(`id = $${params.length}::text`); + } else if (q.query !== undefined) { + params.push(`%${escapeLikePattern(q.query)}%`); + const idx = params.length; + conditions.push( + `(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\')` + ); + } + + if (conditions.length > 0) { + lines.push(`WHERE ${conditions.join(' AND ')}`); + } + + lines.push('ORDER BY id ASC'); + + const result = await executor.query(lines.join('\n'), params); + const rows = extractRows(result); + const mapped: ProviderCaveatRecord[] = []; + for (let i = 0; i < rows.length; i += 1) { + mapped.push(parseProviderCaveatRow(rows[i])); + } + return mapped; + }, + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index f8f50f75..2af06a5e 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,3 +1,4 @@ +export * from './adapters/postgres-findings'; export * from './adapters/postgres-symbol-search'; export * from './copilot-server'; export * from './protocol'; diff --git a/libs/research/test/mcp-postgres-findings.test.ts b/libs/research/test/mcp-postgres-findings.test.ts new file mode 100644 index 00000000..ebdf3464 --- /dev/null +++ b/libs/research/test/mcp-postgres-findings.test.ts @@ -0,0 +1,674 @@ +import { describe, expect, test } from 'bun:test'; +import { + type FiledFindingRecord, + type PostgresFindingsExecutor, + PostgresFindingsError, + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, +} from '../src/mcp/index'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +type QueryHandler = ( + text: string, + params: readonly unknown[] | undefined, + callIndex: number +) => Promise<{ readonly rows: readonly Record[] }> | { readonly rows: readonly Record[] }; + +function createSequenceExecutor(handler: QueryHandler): { + readonly calls: RecordedCall[]; + readonly executor: PostgresFindingsExecutor; +} { + const calls: RecordedCall[] = []; + const executor: PostgresFindingsExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + const idx = calls.length; + calls.push({ text, params }); + const res = await handler(text, params, idx); + return res as unknown as { readonly rows: readonly Row[] }; + }, + }; + return { calls, executor }; +} + +function createFakeExecutor(rows: readonly Record[] = []): { + readonly calls: RecordedCall[]; + readonly executor: PostgresFindingsExecutor; +} { + return createSequenceExecutor(() => ({ rows })); +} + +const FIXED_TS = '2026-01-15T12:34:56.789Z'; + +function makeFiledRecord(overrides: Partial = {}): FiledFindingRecord { + return { + id: 'finding-001', + kind: 'finding', + title: 'Momentum decays after 5 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Cross-sectional rank IC turns negative past day 5.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +function makeRawFindingRow(overrides: Record = {}): Record { + return { + id: 'finding-001', + title: 'Momentum decays after 5 sessions', + status: 'pending_review', + created_at: new Date(FIXED_TS), + summary: 'Cross-sectional rank IC turns negative past day 5.', + trial_refs: ['101', '102'], + evidence_refs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +function makeRawReplayRow(overrides: Record = {}): Record { + return { + id: 'finding-001', + kind: 'finding', + title: 'Momentum decays after 5 sessions', + summary: 'Cross-sectional rank IC turns negative past day 5.', + created_at: new Date(FIXED_TS), + trial_refs: ['101', '102'], + evidence_refs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +function makeRawCaveatRow(overrides: Record = {}): Record { + return { + id: 'caveat-001', + provider: 'EODHD', + dataset: 'eodIntraday1M', + caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.', + created_at: new Date(FIXED_TS), + ...overrides, + }; +} + +function assertNoMutationOrReaderLimitSql(calls: readonly RecordedCall[], checkNoLimit = false): void { + for (const call of calls) { + expect(call.text).not.toMatch(/\bUPDATE\b/i); + expect(call.text).not.toMatch(/\bDELETE\b/i); + expect(call.text).not.toMatch(/\bTRUNCATE\b/i); + if (checkNoLimit) { + expect(call.text).not.toMatch(/\bLIMIT\b/i); + } + } +} + +describe('createPostgresFindingWritePort (fake executor)', () => { + test('unkeyed append issues plain parameterized INSERT with NULL key and never interpolates values', async () => { + const injection = "'; DROP TABLE findings; --"; + const fake = createFakeExecutor([{ id: 'finding-inj', created_at: new Date(FIXED_TS) }]); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + const record = makeFiledRecord({ + id: 'finding-inj', + title: injection, + summary: `summary ${injection}`, + trialRefs: [injection], + evidenceRefs: [`ev:${injection}`], + }); + + const outcome = await port.appendFinding(record); + + expect(outcome).toEqual({ + status: 'created', + id: 'finding-inj', + createdAt: FIXED_TS, + }); + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text).toContain('INSERT INTO findings'); + expect(call.text).not.toContain('ON CONFLICT'); + expect(call.text).toContain('RETURNING id, created_at'); + expect(call.text).not.toContain(injection); + expect(call.text).not.toContain(';'); + expect(call.params).toEqual([ + 'finding-inj', + 'finding', + injection, + `summary ${injection}`, + 'pending_review', + FIXED_TS, + [injection], + [`ev:${injection}`], + null, + ]); + assertNoMutationOrReaderLimitSql(fake.calls); + }); + + test('keyed append uses partial-index ON CONFLICT DO NOTHING and returns created on 1 returned row', async () => { + const fake = createFakeExecutor([ + { id: 'finding-001', created_at: '2026-01-15T14:34:56.789+02:00' }, + ]); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + const outcome = await port.appendFinding(makeFiledRecord(), 'idem-key-1'); + + expect(outcome).toEqual({ + status: 'created', + id: 'finding-001', + createdAt: FIXED_TS, + }); + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text).toContain( + 'ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING' + ); + expect(call.text).not.toContain('idem-key-1'); + expect(call.params).toEqual([ + 'finding-001', + 'finding', + 'Momentum decays after 5 sessions', + 'Cross-sectional rank IC turns negative past day 5.', + 'pending_review', + FIXED_TS, + ['101', '102'], + ['snap:2026-01-15:ic'], + 'idem-key-1', + ]); + assertNoMutationOrReaderLimitSql(fake.calls); + }); + + test('keyed append reads winner in separate SELECT on 0 rows and returns replayed with stored metadata', async () => { + const fake = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + return { rows: [] }; + } + return { + rows: [ + makeRawReplayRow({ + id: 'finding-original', + created_at: '2026-01-15T07:34:56.789999-05:00', + }), + ], + }; + }); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + // Incoming call has a new id and createdAt, but identical comparable payload + const outcome = await port.appendFinding( + makeFiledRecord({ + id: 'finding-retry-new-id', + createdAt: '2026-01-16T00:00:00.000Z', + }), + 'idem-replay' + ); + + expect(outcome).toEqual({ + status: 'replayed', + id: 'finding-original', + createdAt: FIXED_TS, + }); + expect(fake.calls).toHaveLength(2); + expect(fake.calls[1]!.text).toContain('SELECT'); + expect(fake.calls[1]!.text).toContain('WHERE idempotency_key = $1::text'); + expect(fake.calls[1]!.params).toEqual(['idem-replay']); + assertNoMutationOrReaderLimitSql(fake.calls); + }); + + test('keyed append returns conflict when stored payload differs on any comparable field', async () => { + const diffs: readonly Partial[] = [ + { kind: 'dead_end' }, + { title: 'Different title' }, + { summary: 'Different summary' }, + { trialRefs: ['101'] }, + { trialRefs: ['102', '101'] }, + { evidenceRefs: [] }, + ]; + + for (const diff of diffs) { + const fake = createSequenceExecutor((_text, _params, idx) => + idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] } + ); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + const outcome = await port.appendFinding(makeFiledRecord(diff), 'idem-conflict'); + expect(outcome).toEqual({ status: 'conflict' }); + expect(fake.calls).toHaveLength(2); + assertNoMutationOrReaderLimitSql(fake.calls); + } + }); + + test('keyed append resolves same-ID 23505 retry as replayed or conflict, and propagates unrelated 23505 or other errors', async () => { + const pkErr = Object.assign(new Error('duplicate key value violates unique constraint'), { + code: '23505', + }); + + // Same ID + identical payload -> replayed + const fakeReplay = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow({ id: 'finding-001' })] }; + }); + const replayPort = createPostgresFindingWritePort({ executor: fakeReplay.executor }); + expect(await replayPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({ + status: 'replayed', + id: 'finding-001', + createdAt: FIXED_TS, + }); + expect(fakeReplay.calls).toHaveLength(2); + + // Same ID + different payload -> conflict + const fakeConflict = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow({ id: 'finding-001', title: 'Other title' })] }; + }); + const conflictPort = createPostgresFindingWritePort({ executor: fakeConflict.executor }); + expect(await conflictPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({ + status: 'conflict', + }); + + // Unrelated PK collision: no stored row for idempotency_key -> propagate pkErr + const fakeMissing = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [] }; + }); + const missingPort = createPostgresFindingWritePort({ executor: fakeMissing.executor }); + await expect(missingPort.appendFinding(makeFiledRecord(), 'idem-unrelated')).rejects.toBe( + pkErr + ); + + // Unrelated PK collision: stored row for idempotency_key has different ID -> propagate pkErr + const fakeDifferentId = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow({ id: 'finding-other' })] }; + }); + const diffIdPort = createPostgresFindingWritePort({ executor: fakeDifferentId.executor }); + await expect(diffIdPort.appendFinding(makeFiledRecord(), 'idem-other-id')).rejects.toBe(pkErr); + + // Non-23505 error -> propagates immediately without SELECT + const checkErr = Object.assign(new Error('check violation'), { code: '23514' }); + const fakeOther = createSequenceExecutor(() => { + throw checkErr; + }); + const otherPort = createPostgresFindingWritePort({ executor: fakeOther.executor }); + await expect(otherPort.appendFinding(makeFiledRecord(), 'idem-check')).rejects.toBe(checkErr); + expect(fakeOther.calls).toHaveLength(1); + + // Unkeyed 23505 -> propagates immediately without SELECT + const fakeUnkeyed = createSequenceExecutor(() => { + throw pkErr; + }); + const unkeyedPort = createPostgresFindingWritePort({ executor: fakeUnkeyed.executor }); + await expect(unkeyedPort.appendFinding(makeFiledRecord())).rejects.toBe(pkErr); + expect(fakeUnkeyed.calls).toHaveLength(1); + }); + + test('quotes explicit schema on INSERT and replay SELECT, and omits prefix when unset', async () => { + const fakeScoped = createSequenceExecutor((_text, _params, idx) => + idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] } + ); + const scopedPort = createPostgresFindingWritePort({ + executor: fakeScoped.executor, + schema: 'custom_research_1', + }); + await scopedPort.appendFinding(makeFiledRecord(), 'idem-schema'); + + expect(fakeScoped.calls[0]!.text).toContain('INSERT INTO "custom_research_1".findings'); + expect(fakeScoped.calls[1]!.text).toContain('FROM "custom_research_1".findings'); + assertNoMutationOrReaderLimitSql(fakeScoped.calls); + }); +}); + +describe('createPostgresKnowledgeReaders (fake executor)', () => { + test('listFindings binds exact id (taking precedence over query), escaped ILIKE query, and unfiltered queries with ORDER BY id ASC and no LIMIT', async () => { + const injection = "'; DELETE FROM findings; --"; + const fake = createFakeExecutor([makeRawFindingRow()]); + const readers = createPostgresKnowledgeReaders({ executor: fake.executor }); + + // Unfiltered + const allRows = await readers.listFindings({}); + expect(allRows).toEqual([ + { + id: 'finding-001', + title: 'Momentum decays after 5 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Cross-sectional rank IC turns negative past day 5.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:2026-01-15:ic'], + }, + ]); + expect(fake.calls[0]!.text).not.toContain('WHERE'); + expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY id ASC')).toBe(true); + expect(fake.calls[0]!.params).toEqual([]); + + // Exact id takes precedence over query + await readers.listFindings({ id: injection, query: 'ignored' }); + expect(fake.calls[1]!.text).toContain('WHERE id = $1::text'); + expect(fake.calls[1]!.text).not.toContain('ILIKE'); + expect(fake.calls[1]!.text).not.toContain(injection); + expect(fake.calls[1]!.params).toEqual([injection]); + + // Escaped ILIKE query on title and summary + await readers.listFindings({ query: '100% pure_wild\\path' }); + expect(fake.calls[2]!.text).toContain( + "WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'" + ); + expect(fake.calls[2]!.params).toEqual(['%100\\% pure\\_wild\\\\path%']); + + assertNoMutationOrReaderLimitSql(fake.calls, true); + }); + + test('listProviderCaveats combines case-insensitive provider with id or escaped ILIKE query and no LIMIT', async () => { + const fake = createFakeExecutor([ + makeRawCaveatRow({ created_at: '2026-01-15T12:34:56.789Z' }), + ]); + const readers = createPostgresKnowledgeReaders({ + executor: fake.executor, + schema: 'custom_research_2', + }); + + // Unfiltered + const rows = await readers.listProviderCaveats({}); + expect(rows).toEqual([ + { + id: 'caveat-001', + provider: 'EODHD', + dataset: 'eodIntraday1M', + caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.', + createdAt: FIXED_TS, + }, + ]); + expect(fake.calls[0]!.text).toContain('FROM "custom_research_2".provider_caveats'); + expect(fake.calls[0]!.text).not.toContain('WHERE'); + expect(fake.calls[0]!.params).toEqual([]); + + // Provider + exact id (id takes precedence over query) + await readers.listProviderCaveats({ + provider: 'eodhd', + id: 'caveat-001', + query: 'ignored', + }); + expect(fake.calls[1]!.text).toContain( + 'WHERE lower(provider) = lower($1::text) AND id = $2::text' + ); + expect(fake.calls[1]!.text).not.toContain('ILIKE'); + expect(fake.calls[1]!.params).toEqual(['eodhd', 'caveat-001']); + + // Provider + query with wildcards + await readers.listProviderCaveats({ + provider: 'QuoteMedia', + query: '50%_ratio\\inv', + }); + expect(fake.calls[2]!.text).toContain( + "WHERE lower(provider) = lower($1::text) AND (provider ILIKE $2::text ESCAPE '\\' OR dataset ILIKE $2::text ESCAPE '\\' OR caveat ILIKE $2::text ESCAPE '\\')" + ); + expect(fake.calls[2]!.params).toEqual(['QuoteMedia', '%50\\%\\_ratio\\\\inv%']); + + // Query only + await readers.listProviderCaveats({ query: 'split' }); + expect(fake.calls[3]!.text).toContain( + "WHERE (provider ILIKE $1::text ESCAPE '\\' OR dataset ILIKE $1::text ESCAPE '\\' OR caveat ILIKE $1::text ESCAPE '\\')" + ); + expect(fake.calls[3]!.params).toEqual(['%split%']); + + assertNoMutationOrReaderLimitSql(fake.calls, true); + }); +}); + +describe('PostgreSQL findings adapter validation (fake executor)', () => { + 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) { + for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) { + let caught: unknown; + try { + factory(opts as Parameters[0]); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresFindingsError); + expect((caught as PostgresFindingsError).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 findings; --', + 'space name', + 123, + null, + ]; + + for (const schema of badSchemas) { + for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) { + let caught: unknown; + try { + factory({ executor: fake.executor, schema: schema as string }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresFindingsError); + expect((caught as PostgresFindingsError).code).toBe('INVALID_SCHEMA'); + } + } + + expect(fake.calls).toHaveLength(0); + }); + + test('accepts prototype-method executors', async () => { + class ProtoExecutor { + async query>(): Promise<{ readonly rows: readonly Row[] }> { + return { rows: [makeRawFindingRow()] as unknown as readonly Row[] }; + } + } + const readers = createPostgresKnowledgeReaders({ executor: new ProtoExecutor() }); + const rows = await readers.listFindings({}); + expect(rows).toHaveLength(1); + expect(rows[0]!.id).toBe('finding-001'); + }); + + test('rejects invalid result envelopes and missing/duplicate receipt or winner rows with INVALID_ROW', async () => { + const badEnvelopeExecutor: PostgresFindingsExecutor = { + async query() { + return { rows: 'not-an-array' as unknown as readonly never[] }; + }, + }; + const badWritePort = createPostgresFindingWritePort({ executor: badEnvelopeExecutor }); + const badReaders = createPostgresKnowledgeReaders({ executor: badEnvelopeExecutor }); + + for (const op of [ + () => badWritePort.appendFinding(makeFiledRecord()), + () => badWritePort.appendFinding(makeFiledRecord(), 'k1'), + () => badReaders.listFindings({}), + () => badReaders.listProviderCaveats({}), + ]) { + let caught: unknown; + try { + await op(); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresFindingsError); + expect((caught as PostgresFindingsError).code).toBe('INVALID_ROW'); + } + + // Unkeyed insert returning 0 rows or 2 rows + for (const rows of [[], [{ id: 'a', created_at: FIXED_TS }, { id: 'b', created_at: FIXED_TS }]]) { + const port = createPostgresFindingWritePort({ executor: createFakeExecutor(rows).executor }); + await expect(port.appendFinding(makeFiledRecord())).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Keyed insert returning 2 rows + const dupInsertPort = createPostgresFindingWritePort({ + executor: createFakeExecutor([ + { id: 'a', created_at: FIXED_TS }, + { id: 'b', created_at: FIXED_TS }, + ]).executor, + }); + await expect(dupInsertPort.appendFinding(makeFiledRecord(), 'k-dup')).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + + // Keyed conflict lookup returning 0 rows or 2 rows + for (const lookupRows of [[], [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })]]) { + const fake = createSequenceExecutor((_t, _p, idx) => + idx === 0 ? { rows: [] } : { rows: lookupRows } + ); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + await expect(port.appendFinding(makeFiledRecord(), 'k-missing-or-dup')).rejects.toMatchObject( + { + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + } + ); + } + + // 23505 lookup returning 2 rows + const pkErr = Object.assign(new Error('dup'), { code: '23505' }); + const fakeDup23505 = createSequenceExecutor((_t, _p, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })] }; + }); + const dup23505Port = createPostgresFindingWritePort({ executor: fakeDup23505.executor }); + await expect(dup23505Port.appendFinding(makeFiledRecord(), 'k-dup-23505')).rejects.toMatchObject( + { + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + } + ); + }); + + test('rejects malformed timestamps, invalid kinds on replay, and non-string or nested arrays with INVALID_ROW', async () => { + const badTimestamps: readonly unknown[] = [ + null, + 1700000000000, + new Date(Number.NaN), + '', + '2026-01-15', + '2026-01-15T12:34:56', + '2026-02-30T00:00:00Z', + '2026-01-15T24:00:00Z', + '2026-01-15T12:00:00+25:00', + 'not-a-timestamp', + ]; + + for (const badTs of badTimestamps) { + const findingReaders = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawFindingRow({ created_at: badTs })]).executor, + }); + await expect(findingReaders.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + + const caveatReaders = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawCaveatRow({ created_at: badTs })]).executor, + }); + await expect(caveatReaders.listProviderCaveats({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Invalid kind on replay + for (const badKind of ['hypothesis', 'FINDING', '', null, 42]) { + const fake = createSequenceExecutor((_t, _p, idx) => + idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow({ kind: badKind })] } + ); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + await expect(port.appendFinding(makeFiledRecord(), 'k-bad-kind')).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Invalid ref arrays (nested arrays, null elements, non-arrays) + const badArrays: readonly unknown[] = [null, '101', [101], ['101', null], [['101']]]; + for (const badArr of badArrays) { + const readers = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawFindingRow({ trial_refs: badArr })]).executor, + }); + await expect(readers.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + + const readersEv = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawFindingRow({ evidence_refs: badArr })]).executor, + }); + await expect(readersEv.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Non-object rows & blank strings + const badFindingRows: readonly unknown[] = [ + null, + makeRawFindingRow({ id: ' ' }), + makeRawFindingRow({ title: '' }), + makeRawFindingRow({ status: null }), + makeRawFindingRow({ summary: '' }), + ]; + for (const badRow of badFindingRows) { + const readers = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([badRow as Record]).executor, + }); + await expect(readers.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + const badCaveatRows: readonly unknown[] = [ + null, + makeRawCaveatRow({ id: '' }), + makeRawCaveatRow({ provider: ' ' }), + makeRawCaveatRow({ dataset: '' }), + makeRawCaveatRow({ caveat: null }), + ]; + for (const badRow of badCaveatRows) { + const readers = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([badRow as Record]).executor, + }); + await expect(readers.listProviderCaveats({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + }); +}); diff --git a/test/postgres/mcp-findings-adapter.test.ts b/test/postgres/mcp-findings-adapter.test.ts new file mode 100644 index 00000000..51636f7d --- /dev/null +++ b/test/postgres/mcp-findings-adapter.test.ts @@ -0,0 +1,537 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Client, Pool, type PoolConfig } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + type FileFindingResultPayload, + type FiledFindingRecord, + type PostgresFindingsExecutor, + type ReadKnowledgeResultPayload, + createFileFindingTool, + createMcpServer, + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, + createReadKnowledgeTool, +} from '../../libs/research/src/mcp/index'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('mcp-findings-adapter-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); + +const FIXED_TS = '2026-01-15T12:34:56.789Z'; + +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): PostgresFindingsExecutor { + 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[] }>; + }, + }; +} + +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(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)}` + ); + } + + // 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' }); + + return { admin, pool, schema }; +} + +function makeFinding(overrides: Partial = {}): FiledFindingRecord { + return { + id: `finding-${randomUUID()}`, + kind: 'finding', + title: 'Momentum factor decays after 5 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Cross-sectional rank IC turns negative past day 5.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +describe('PostgreSQL findings adapter 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'); + }); + + test('preserves isolated schema search_path precedence over URL startup options', () => { + const schema = 'stock_bot_safety_findings_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 findings & provider caveats adapter', () => { + test('supports unkeyed inserts, keyed created -> replayed -> conflict, same-ID retries, and unrelated duplicate PK errors', async () => { + const f = await createIsolatedFixture(); + const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) }); + + // Two independent unkeyed inserts produce two distinct rows. + const u1 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' })); + const u2 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-2' })); + expect(u1).toEqual({ status: 'created', id: 'f-unkeyed-1', createdAt: FIXED_TS }); + expect(u2).toEqual({ status: 'created', id: 'f-unkeyed-2', createdAt: FIXED_TS }); + + // Keyed create -> replay -> conflict + const original = makeFinding({ + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + const created = await writePort.appendFinding(original, 'idem-roundtrip'); + expect(created).toEqual({ + status: 'created', + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + + // Replay with new generated ID and timestamp returns original stored ID and timestamp. + const replayed = await writePort.appendFinding( + { + ...original, + id: 'f-keyed-retry-new-id', + createdAt: '2026-01-16T00:00:00.000Z', + }, + 'idem-roundtrip' + ); + expect(replayed).toEqual({ + status: 'replayed', + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + + // Same-ID retry (triggers PK 23505) resolves cleanly as replayed / conflict. + const sameIdReplay = await writePort.appendFinding(original, 'idem-roundtrip'); + expect(sameIdReplay).toEqual({ + status: 'replayed', + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + const sameIdConflict = await writePort.appendFinding( + { ...original, title: 'Mutated title on same-ID retry' }, + 'idem-roundtrip' + ); + expect(sameIdConflict).toEqual({ status: 'conflict' }); + + // Different payload with new ID returns conflict and leaves row count unchanged. + const conflict = await writePort.appendFinding( + { ...original, id: 'f-keyed-conflict', summary: 'Different summary' }, + 'idem-roundtrip' + ); + expect(conflict).toEqual({ status: 'conflict' }); + + // Unrelated duplicate primary key (collides with unkeyed row f-unkeyed-1) propagates 23505. + let pkError: unknown; + try { + await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' }), 'idem-fresh-unrelated'); + } catch (err) { + pkError = err; + } + expect((pkError as { code?: string } | null)?.code).toBe('23505'); + + const countRow = (await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings')) + .rows[0]; + expect(countRow?.c).toBe(3); + }); + + test('concurrent same-key appends on separate connections leave exactly one stored row for identical and differing payloads', async () => { + const f = await createIsolatedFixture(); + const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) }); + + // Concurrent identical payloads + const recA = makeFinding({ id: 'f-race-same-a', createdAt: '2026-01-15T10:00:00.000Z' }); + const recB = { ...recA, id: 'f-race-same-b', createdAt: '2026-01-15T10:00:01.000Z' }; + + const sameOutcomes = await Promise.all([ + writePort.appendFinding(recA, 'idem-race-same'), + writePort.appendFinding(recB, 'idem-race-same'), + ]); + const sameStatuses = sameOutcomes.map(o => o.status).sort(); + expect(sameStatuses).toEqual(['created', 'replayed']); + + const winnerSame = sameOutcomes.find(o => o.status === 'created')!; + const loserSame = sameOutcomes.find(o => o.status === 'replayed')!; + expect(loserSame.id).toBe(winnerSame.id); + expect(loserSame.createdAt).toBe(winnerSame.createdAt); + + const storedSame = ( + await f.pool.query<{ id: string }>( + 'SELECT id FROM findings WHERE idempotency_key = $1', + ['idem-race-same'] + ) + ).rows; + expect(storedSame).toEqual([{ id: winnerSame.id }]); + + // Concurrent differing payloads + const diffA = makeFinding({ + id: 'f-race-diff-a', + title: 'Race title A', + createdAt: '2026-01-15T11:00:00.000Z', + }); + const diffB = makeFinding({ + id: 'f-race-diff-b', + title: 'Race title B', + createdAt: '2026-01-15T11:00:01.000Z', + }); + + const diffOutcomes = await Promise.all([ + writePort.appendFinding(diffA, 'idem-race-diff'), + writePort.appendFinding(diffB, 'idem-race-diff'), + ]); + const diffStatuses = diffOutcomes.map(o => o.status).sort(); + expect(diffStatuses).toEqual(['conflict', 'created']); + + const winnerDiff = diffOutcomes.find(o => o.status === 'created')!; + const storedDiff = ( + await f.pool.query<{ id: string }>( + 'SELECT id FROM findings WHERE idempotency_key = $1', + ['idem-race-diff'] + ) + ).rows; + expect(storedDiff).toEqual([{ id: winnerDiff.id }]); + }); + + test('readers return all eligible candidates in deterministic id order with mixed-case, provider, exact-id precedence, wildcard escaping, and explicit schema', async () => { + const f = await createIsolatedFixture(); + // Use admin pool (default search_path) with explicit schema option to verify quoting. + const writePort = createPostgresFindingWritePort({ + executor: createPgExecutor(f.admin), + schema: f.schema, + }); + const readers = createPostgresKnowledgeReaders({ + executor: createPgExecutor(f.admin), + schema: f.schema, + }); + + await writePort.appendFinding( + makeFinding({ + id: 'f-003', + title: '100% Pure_Wild\\Match', + summary: 'Literal wildcard finding.', + createdAt: '2026-01-15T03:00:00.000Z', + }) + ); + await writePort.appendFinding( + makeFinding({ + id: 'f-001', + title: '100X PureAWildXMatch', + summary: 'Near-match without literal wildcards.', + createdAt: '2026-01-15T01:00:00.000Z', + }) + ); + await writePort.appendFinding( + makeFinding({ + id: 'f-002', + title: 'Alpha Drift Signal', + summary: 'Observed on TSX equities.', + createdAt: '2026-01-15T02:00:00.000Z', + }) + ); + + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES + ('c-003', 'EODHD', 'eodIntraday1M', '100% split_adjusted\\bars', '2026-01-15T03:00:00.000Z'), + ('c-001', 'QuoteMedia', 'qmSplits', '100X splitXadjustedYbars', '2026-01-15T01:00:00.000Z'), + ('c-002', 'EODHD', 'eodPrices', 'Daily raw OHLCV needs un-adjustment.', '2026-01-15T02:00:00.000Z')` + ); + + // Deterministic id ASC order for unfiltered reads + expect((await readers.listFindings({})).map(r => r.id)).toEqual(['f-001', 'f-002', 'f-003']); + expect((await readers.listProviderCaveats({})).map(r => r.id)).toEqual([ + 'c-001', + 'c-002', + 'c-003', + ]); + + // Mixed-case query matching + expect((await readers.listFindings({ query: 'tsx EQUITIES' })).map(r => r.id)).toEqual([ + 'f-002', + ]); + expect((await readers.listProviderCaveats({ query: 'DAILY RAW' })).map(r => r.id)).toEqual([ + 'c-002', + ]); + + // Case-insensitive provider filter + expect((await readers.listProviderCaveats({ provider: 'eodhd' })).map(r => r.id)).toEqual([ + 'c-002', + 'c-003', + ]); + + // Exact id is case-sensitive and takes precedence over query + expect( + (await readers.listFindings({ id: 'f-002', query: 'does-not-match' })).map(r => r.id) + ).toEqual(['f-002']); + expect(await readers.listFindings({ id: 'F-002' })).toEqual([]); + + // Provider condition still applies with exact id + expect( + (await readers.listProviderCaveats({ id: 'c-002', provider: 'eodhd', query: 'nope' })).map( + r => r.id + ) + ).toEqual(['c-002']); + expect( + await readers.listProviderCaveats({ id: 'c-002', provider: 'quotemedia' }) + ).toEqual([]); + + // Literal wildcard escaping: matches f-003 / c-003 and excludes near-matches f-001 / c-001 + expect((await readers.listFindings({ query: '100% Pure_Wild\\' })).map(r => r.id)).toEqual([ + 'f-003', + ]); + expect( + (await readers.listProviderCaveats({ query: '100% split_adjusted\\' })).map(r => r.id) + ).toEqual(['c-003']); + }); + + test('round-trips createFileFindingTool -> createReadKnowledgeTool through MCP server', async () => { + const f = await createIsolatedFixture(); + const executor = createPgExecutor(f.pool); + const writePort = createPostgresFindingWritePort({ executor }); + const readers = createPostgresKnowledgeReaders({ executor }); + + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ('caveat-eod-1', 'EODHD', 'eodIntraday1M', 'Retroactively split-adjusted.', $1::timestamptz)`, + [FIXED_TS] + ); + + let idSeq = 0; + const allowedTrials = new Set(['101', '102']); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: writePort, + trialLookup: { + hasResearchVisibleTrial(ref) { + return allowedTrials.has(ref); + }, + }, + newId: () => { + idSeq += 1; + return `finding-mcp-${idSeq}`; + }, + now: () => new Date(FIXED_TS), + }), + createReadKnowledgeTool({ + port: { + listLibraryCards: async () => [], + ...readers, + }, + }), + ], + }); + + const callTool = async (name: string, args: Record) => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: `req-${name}`, + method: 'tools/call', + params: { name, arguments: args }, + }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw!) as { + result: { isError?: boolean; content: Array<{ text: string }> }; + }; + return parsed.result; + }; + + // File a new finding through MCP + const fileRes = await callTool('file_finding', { + kind: 'finding', + title: 'Post-earnings drift persists 3 sessions', + summary: 'Positive rank IC across research-visible trials 101 and 102.', + trialRefs: ['102', '101'], + evidenceRefs: ['snap:b', 'snap:a'], + idempotencyKey: 'mcp-idem-1', + }); + expect(fileRes.isError).toBeUndefined(); + const receipt = JSON.parse(fileRes.content[0]!.text) as FileFindingResultPayload; + expect(receipt).toEqual({ + id: 'finding-mcp-1', + createdAt: FIXED_TS, + created: true, + }); + + // Retry with reordered & duplicate refs -> normalized replay with original receipt + const retryRes = await callTool('file_finding', { + kind: 'finding', + title: 'Post-earnings drift persists 3 sessions', + summary: 'Positive rank IC across research-visible trials 101 and 102.', + trialRefs: ['101', '102', '101'], + evidenceRefs: ['snap:a', 'snap:b', 'snap:a'], + idempotencyKey: 'mcp-idem-1', + }); + expect(retryRes.isError).toBeUndefined(); + const retryReceipt = JSON.parse(retryRes.content[0]!.text) as FileFindingResultPayload; + expect(retryReceipt).toEqual({ + id: 'finding-mcp-1', + createdAt: FIXED_TS, + created: false, + }); + + // Unavailable / Vault-only trial ref returns error and writes zero rows + const deniedRes = await callTool('file_finding', { + kind: 'dead_end', + title: 'Should not persist', + summary: 'References unavailable trial.', + trialRefs: ['999-vault'], + }); + expect(deniedRes.isError).toBe(true); + expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + + // Read back the filed finding by receipt ID via read_knowledge + const readRes = await callTool('read_knowledge', { + source: 'findings', + id: receipt.id, + }); + expect(readRes.isError).toBeUndefined(); + const knowledge = JSON.parse(readRes.content[0]!.text) as ReadKnowledgeResultPayload; + expect(knowledge).toEqual({ + rowCount: 1, + sources: { library: 0, findings: 1, provider_caveats: 0 }, + rows: [ + { + source: 'findings', + id: 'finding-mcp-1', + title: 'Post-earnings drift persists 3 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Positive rank IC across research-visible trials 101 and 102.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:a', 'snap:b'], + truncated: false, + }, + ], + }); + + // Verify provider_caveats case-insensitive filter through read_knowledge + const caveatRes = await callTool('read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + }); + expect(caveatRes.isError).toBeUndefined(); + const caveatsPayload = JSON.parse(caveatRes.content[0]!.text) as ReadKnowledgeResultPayload; + expect(caveatsPayload.rowCount).toBe(1); + expect(caveatsPayload.sources).toEqual({ library: 0, findings: 0, provider_caveats: 1 }); + expect(caveatsPayload.rows[0]).toEqual({ + source: 'provider_caveats', + id: 'caveat-eod-1', + provider: 'EODHD', + dataset: 'eodIntraday1M', + caveat: 'Retroactively split-adjusted.', + createdAt: FIXED_TS, + truncated: false, + }); + + // Confirm only 1 finding row was persisted in total + const totalFindings = ( + await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings') + ).rows[0]?.c; + expect(totalFindings).toBe(1); + }); +});