181 lines
6.1 KiB
TypeScript
181 lines
6.1 KiB
TypeScript
/**
|
|
* Read-only PostgreSQL `trial_ledger` adapter implementing {@link TrialRefLookupPort}
|
|
* for the MCP copilot `file_finding` tool.
|
|
*
|
|
* Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is
|
|
* injected via {@link TrialRefExecutor}.
|
|
*/
|
|
|
|
import type { TrialRefLookupPort } from '../tools/file-finding';
|
|
import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input';
|
|
|
|
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
|
|
const FOUR_DIGIT_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
const CANONICAL_POSITIVE_BIGINT_RE = /^[1-9][0-9]{0,18}$/;
|
|
const MAX_SIGNED_BIGINT_STR = '9223372036854775807';
|
|
|
|
/** Error codes thrown by {@link PostgresTrialRefError}. */
|
|
export type PostgresTrialRefErrorCode =
|
|
| 'INVALID_EXECUTOR'
|
|
| 'INVALID_SCHEMA'
|
|
| 'INVALID_VAULT_CUTOFF'
|
|
| 'INVALID_ROW';
|
|
|
|
/** Typed validation error thrown by the PostgreSQL trial-ref lookup adapter. */
|
|
export class PostgresTrialRefError extends RangeError {
|
|
readonly code: PostgresTrialRefErrorCode;
|
|
|
|
constructor(code: PostgresTrialRefErrorCode, message: string) {
|
|
super(message);
|
|
this.name = 'PostgresTrialRefError';
|
|
this.code = code;
|
|
Object.setPrototypeOf(this, new.target.prototype);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
|
|
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
|
|
*/
|
|
export interface TrialRefExecutor {
|
|
query<Row = Record<string, unknown>>(
|
|
text: string,
|
|
params?: readonly unknown[]
|
|
): Promise<{ readonly rows: readonly Row[] }>;
|
|
}
|
|
|
|
/** Factory options for {@link createPostgresTrialRefLookupPort} / {@link createPostgresTrialRefPort}. */
|
|
export interface PostgresTrialRefLookupPortOptions {
|
|
readonly executor: TrialRefExecutor;
|
|
/** Authoritative UTC epoch-ms Vault cutoff; trials with `sample_end < cutoffDate` are research-visible. */
|
|
readonly vaultCutoffTs: number;
|
|
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
|
|
readonly schema?: string;
|
|
}
|
|
|
|
/** Alias for {@link PostgresTrialRefLookupPortOptions}. */
|
|
export type PostgresTrialRefPortOptions = PostgresTrialRefLookupPortOptions;
|
|
|
|
interface RawTrialRefVisibilityRow {
|
|
readonly visible?: unknown;
|
|
}
|
|
|
|
function isCanonicalPositiveBigInt(value: unknown): value is string {
|
|
if (typeof value !== 'string' || !CANONICAL_POSITIVE_BIGINT_RE.test(value)) {
|
|
return false;
|
|
}
|
|
if (value.length === MAX_SIGNED_BIGINT_STR.length && value > MAX_SIGNED_BIGINT_STR) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function buildTrialVisibilitySql(schemaPrefix: string): string {
|
|
return `SELECT 1 AS visible FROM ${schemaPrefix}trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1`;
|
|
}
|
|
|
|
function validateFactoryOptions(options: PostgresTrialRefLookupPortOptions): {
|
|
readonly executor: TrialRefExecutor;
|
|
readonly cutoffDate: string;
|
|
readonly schemaPrefix: string;
|
|
} {
|
|
if (typeof options !== 'object' || options === null) {
|
|
throw new PostgresTrialRefError(
|
|
'INVALID_EXECUTOR',
|
|
'Invalid options: expected an object with a TrialRefExecutor.'
|
|
);
|
|
}
|
|
|
|
const { executor, vaultCutoffTs, schema } = options;
|
|
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
|
|
throw new PostgresTrialRefError(
|
|
'INVALID_EXECUTOR',
|
|
'Invalid executor: expected an object with a callable query(text, params?) method.'
|
|
);
|
|
}
|
|
|
|
let schemaPrefix = '';
|
|
if (schema !== undefined) {
|
|
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
|
|
throw new PostgresTrialRefError(
|
|
'INVALID_SCHEMA',
|
|
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
|
|
);
|
|
}
|
|
schemaPrefix = `"${schema}".`;
|
|
}
|
|
|
|
let validatedCutoffTs: number;
|
|
try {
|
|
validatedCutoffTs = validateVaultCutoffTs(vaultCutoffTs);
|
|
} catch {
|
|
throw new PostgresTrialRefError(
|
|
'INVALID_VAULT_CUTOFF',
|
|
'Invalid vaultCutoffTs: expected a finite safe-integer epoch-ms timestamp within ECMAScript Date bounds.'
|
|
);
|
|
}
|
|
|
|
const cutoffDate = utcDateOf(validatedCutoffTs);
|
|
if (!FOUR_DIGIT_DATE_RE.test(cutoffDate) || cutoffDate.startsWith('0000-')) {
|
|
throw new PostgresTrialRefError(
|
|
'INVALID_VAULT_CUTOFF',
|
|
'Invalid vaultCutoffTs: resolved UTC date must be a four-digit PostgreSQL calendar date (0001-01-01 through 9999-12-31).'
|
|
);
|
|
}
|
|
|
|
return { executor, cutoffDate, schemaPrefix };
|
|
}
|
|
|
|
/**
|
|
* Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger`
|
|
* (`36-trial-ledger.sql`).
|
|
*
|
|
* Only trials with `sample_end < cutoffDate` (exclusive UTC Vault cutoff date) are
|
|
* research-visible. Unknown, malformed, and Vault-only references all return `false`.
|
|
*/
|
|
export function createPostgresTrialRefLookupPort(
|
|
options: PostgresTrialRefLookupPortOptions
|
|
): TrialRefLookupPort {
|
|
const { executor, cutoffDate, schemaPrefix } = validateFactoryOptions(options);
|
|
const sql = buildTrialVisibilitySql(schemaPrefix);
|
|
|
|
return {
|
|
async hasResearchVisibleTrial(trialRef: string): Promise<boolean> {
|
|
if (!isCanonicalPositiveBigInt(trialRef)) {
|
|
return false;
|
|
}
|
|
|
|
const result = await executor.query<RawTrialRefVisibilityRow>(sql, [trialRef, cutoffDate]);
|
|
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
|
|
throw new PostgresTrialRefError(
|
|
'INVALID_ROW',
|
|
'Invalid executor response: expected an object with a rows array.'
|
|
);
|
|
}
|
|
|
|
if (result.rows.length === 0) {
|
|
return false;
|
|
}
|
|
|
|
if (result.rows.length !== 1) {
|
|
throw new PostgresTrialRefError(
|
|
'INVALID_ROW',
|
|
`Invalid executor response: expected at most 1 trial_ledger row, received ${result.rows.length}.`
|
|
);
|
|
}
|
|
|
|
const raw = result.rows[0];
|
|
if (typeof raw !== 'object' || raw === null || raw.visible !== 1) {
|
|
throw new PostgresTrialRefError(
|
|
'INVALID_ROW',
|
|
'Invalid trial_ledger visibility row: expected an object with visible === 1.'
|
|
);
|
|
}
|
|
|
|
return true;
|
|
},
|
|
};
|
|
}
|
|
|
|
/** Alias for {@link createPostgresTrialRefLookupPort}. */
|
|
export const createPostgresTrialRefPort = createPostgresTrialRefLookupPort;
|