722 lines
23 KiB
TypeScript
722 lines
23 KiB
TypeScript
/**
|
||
* 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 must run each `query()`
|
||
* call in autocommit mode on a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`)
|
||
* rather than inside a `REPEATABLE READ` / `SERIALIZABLE` or explicit `BEGIN`
|
||
* transaction (unless the executor wraps each statement in a `SAVEPOINT` and rolls
|
||
* it back before rethrowing errors). Autocommit ensures that `ON CONFLICT ... DO
|
||
* NOTHING` winner lookups observe the committed winner and that same-ID `23505`
|
||
* primary-key retry lookups do not fail with `25P02` (aborted transaction).
|
||
*/
|
||
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, '\\$&');
|
||
}
|
||
|
||
/**
|
||
* PostgreSQL POSIX regex matching any non-ASCII character (`> 0x7F`).
|
||
*
|
||
* Used alongside ASCII SQL pushdown (`ILIKE` / `lower()`) so rows containing
|
||
* non-ASCII stored text (e.g. `BİST` under `C` collation or `K` U+212A) are
|
||
* kept as candidates and evaluated with JavaScript's `.toLowerCase()` rules.
|
||
*/
|
||
const PG_NON_ASCII_REGEX = "'[^\\x01-\\x7f]'";
|
||
|
||
/**
|
||
* Returns `true` when every UTF-16 code unit in `value` is ASCII (`<= 0x7F`).
|
||
*
|
||
* PostgreSQL `ILIKE` / `lower()` agrees with JavaScript `.toLowerCase()` only
|
||
* when both the selector and the stored text are pure ASCII. Non-ASCII
|
||
* selectors omit SQL casing filters, and ASCII selectors retain non-ASCII
|
||
* stored rows as candidates; all returned rows are then filtered with
|
||
* JavaScript's `.toLowerCase()` rules after validation.
|
||
*/
|
||
function isAsciiOnly(value: string): boolean {
|
||
for (let i = 0; i < value.length; i += 1) {
|
||
if (value.charCodeAt(i) > 0x7f) {
|
||
return false;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
|
||
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[] = [];
|
||
let normalizedQuery: string | null = null;
|
||
|
||
if (q.id !== undefined) {
|
||
params.push(q.id);
|
||
lines.push('WHERE id = $1::text');
|
||
} else if (q.query !== undefined) {
|
||
normalizedQuery = q.query.toLowerCase();
|
||
if (isAsciiOnly(q.query)) {
|
||
params.push(`%${escapeLikePattern(q.query)}%`);
|
||
lines.push(
|
||
`WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\' OR title ~ ${PG_NON_ASCII_REGEX} OR summary ~ ${PG_NON_ASCII_REGEX}`
|
||
);
|
||
}
|
||
}
|
||
|
||
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) {
|
||
const finding = parseFindingRow(rows[i]);
|
||
if (
|
||
normalizedQuery !== null &&
|
||
!finding.title.toLowerCase().includes(normalizedQuery) &&
|
||
!finding.summary.toLowerCase().includes(normalizedQuery)
|
||
) {
|
||
continue;
|
||
}
|
||
mapped.push(finding);
|
||
}
|
||
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[] = [];
|
||
let normalizedProvider: string | null = null;
|
||
let normalizedQuery: string | null = null;
|
||
|
||
if (q.provider !== undefined) {
|
||
normalizedProvider = q.provider.toLowerCase();
|
||
if (isAsciiOnly(q.provider)) {
|
||
params.push(q.provider);
|
||
conditions.push(
|
||
`(lower(provider) = lower($${params.length}::text) OR provider ~ ${PG_NON_ASCII_REGEX})`
|
||
);
|
||
}
|
||
}
|
||
|
||
if (q.id !== undefined) {
|
||
params.push(q.id);
|
||
conditions.push(`id = $${params.length}::text`);
|
||
} else if (q.query !== undefined) {
|
||
normalizedQuery = q.query.toLowerCase();
|
||
if (isAsciiOnly(q.query)) {
|
||
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 '\\' OR provider ~ ${PG_NON_ASCII_REGEX} OR dataset ~ ${PG_NON_ASCII_REGEX} OR caveat ~ ${PG_NON_ASCII_REGEX})`
|
||
);
|
||
}
|
||
}
|
||
|
||
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) {
|
||
const caveat = parseProviderCaveatRow(rows[i]);
|
||
if (
|
||
normalizedProvider !== null &&
|
||
caveat.provider.toLowerCase() !== normalizedProvider
|
||
) {
|
||
continue;
|
||
}
|
||
if (
|
||
normalizedQuery !== null &&
|
||
!caveat.provider.toLowerCase().includes(normalizedQuery) &&
|
||
!caveat.dataset.toLowerCase().includes(normalizedQuery) &&
|
||
!caveat.caveat.toLowerCase().includes(normalizedQuery)
|
||
) {
|
||
continue;
|
||
}
|
||
mapped.push(caveat);
|
||
}
|
||
return mapped;
|
||
},
|
||
};
|
||
}
|