T-161: M2.1j (re-queue) — PostgreSQL findings adapter for the MCP copilot: FindingWritePort (atomic idempotent append) + listFindings / listProviderCaveats readers over an injected executor in libs/research/src/mcp/adapters/postgres-findings.ts (no new deps)

This commit is contained in:
Studio 2026-12-02 09:35:55 -05:00
parent ac12439fe2
commit 5654b9cc05
5 changed files with 1872 additions and 0 deletions

View file

@ -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<KnowledgePort, 'listFindings' | 'listProviderCaveats'>`) 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.

View file

@ -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<string> = 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<Row = Record<string, unknown>>(
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<KnowledgePort, 'listFindings' | 'listProviderCaveats'>;
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<Row>(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<AppendFindingResult> {
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<RawFindingReceiptRow>(unkeyedInsertSql, insertParams);
const rows = extractRows<RawFindingReceiptRow>(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<RawFindingReceiptRow>(keyedInsertSql, insertParams);
insertRows = extractRows<RawFindingReceiptRow>(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<RawStoredFindingForReplayRow>(selectByKeySql, [
idempotencyKey,
]);
const lookupRows = extractRows<RawStoredFindingForReplayRow>(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<RawStoredFindingForReplayRow>(selectByKeySql, [
idempotencyKey,
]);
const winnerRows = extractRows<RawStoredFindingForReplayRow>(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<readonly FindingRecord[]> {
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<RawFindingRow>(lines.join('\n'), params);
const rows = extractRows<RawFindingRow>(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<readonly ProviderCaveatRecord[]> {
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<RawProviderCaveatRow>(lines.join('\n'), params);
const rows = extractRows<RawProviderCaveatRow>(result);
const mapped: ProviderCaveatRecord[] = [];
for (let i = 0; i < rows.length; i += 1) {
mapped.push(parseProviderCaveatRow(rows[i]));
}
return mapped;
},
};
}

View file

@ -1,3 +1,4 @@
export * from './adapters/postgres-findings';
export * from './adapters/postgres-symbol-search';
export * from './copilot-server';
export * from './protocol';

View file

@ -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<string, unknown>[] }> | { readonly rows: readonly Record<string, unknown>[] };
function createSequenceExecutor(handler: QueryHandler): {
readonly calls: RecordedCall[];
readonly executor: PostgresFindingsExecutor;
} {
const calls: RecordedCall[] = [];
const executor: PostgresFindingsExecutor = {
async query<Row = Record<string, unknown>>(
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<string, unknown>[] = []): {
readonly calls: RecordedCall[];
readonly executor: PostgresFindingsExecutor;
} {
return createSequenceExecutor(() => ({ rows }));
}
const FIXED_TS = '2026-01-15T12:34:56.789Z';
function makeFiledRecord(overrides: Partial<FiledFindingRecord> = {}): 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<string, unknown> = {}): Record<string, unknown> {
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<string, unknown> = {}): Record<string, unknown> {
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<string, unknown> = {}): Record<string, unknown> {
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<FiledFindingRecord>[] = [
{ 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<typeof createPostgresFindingWritePort>[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<Row = Record<string, unknown>>(): 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<string, unknown>]).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<string, unknown>]).executor,
});
await expect(readers.listProviderCaveats({})).rejects.toMatchObject({
name: 'PostgresFindingsError',
code: 'INVALID_ROW',
});
}
});
});