T-165: M2.1l (re-queue) — PostgreSQL trial_ledger adapter for the MCP copilot file_finding tool: TrialRefLookupPort over an injected executor in libs/research/src/mcp/adapters/postgres-trial-ref.ts (research-visible = sample_end before the Vault cutoff date, parameterized SQL, no new deps)
This commit is contained in:
parent
2932f5640d
commit
272d336603
4 changed files with 877 additions and 0 deletions
165
libs/research/src/mcp/adapters/postgres-trial-ref.ts
Normal file
165
libs/research/src/mcp/adapters/postgres-trial-ref.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
/**
|
||||
* 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 { MarketDataStoreValidationError } from '../../market-data-store';
|
||||
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 CANONICAL_TRIAL_ID_RE = /^[1-9][0-9]{0,18}$/;
|
||||
const MAX_PG_BIGINT_STR = '9223372036854775807';
|
||||
const PG_ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
/** Error codes thrown by {@link PostgresTrialRefError}. */
|
||||
export type PostgresTrialRefErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | '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 createPostgresTrialRefPort}. */
|
||||
export interface PostgresTrialRefPortOptions {
|
||||
readonly executor: TrialRefExecutor;
|
||||
/** Server-injected Vault cutoff epoch-ms timestamp; trials with `sample_end < utcDate(vaultCutoffTs)` are visible. */
|
||||
readonly vaultCutoffTs: number;
|
||||
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
|
||||
readonly schema?: string;
|
||||
}
|
||||
|
||||
interface RawTrialRefVisibilityRow {
|
||||
readonly visible: unknown;
|
||||
}
|
||||
|
||||
function isCanonicalPositiveBigInt(value: unknown): value is string {
|
||||
if (typeof value !== 'string' || !CANONICAL_TRIAL_ID_RE.test(value)) {
|
||||
return false;
|
||||
}
|
||||
if (value.length === MAX_PG_BIGINT_STR.length && value > MAX_PG_BIGINT_STR) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function buildTrialRefVisibilitySql(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: PostgresTrialRefPortOptions): {
|
||||
readonly executor: TrialRefExecutor;
|
||||
readonly schemaPrefix: string;
|
||||
readonly vaultCutoffDate: 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}".`;
|
||||
}
|
||||
|
||||
const cutoffTs = validateVaultCutoffTs(vaultCutoffTs);
|
||||
const vaultCutoffDate = utcDateOf(cutoffTs);
|
||||
if (!PG_ISO_DATE_RE.test(vaultCutoffDate) || vaultCutoffDate.startsWith('0000-')) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid \`vaultCutoffTs\`: ${String(vaultCutoffTs)} does not produce a PostgreSQL YYYY-MM-DD date.`,
|
||||
'vaultCutoffTs'
|
||||
);
|
||||
}
|
||||
|
||||
return { executor, schemaPrefix, vaultCutoffDate };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger`
|
||||
* (`36-trial-ledger.sql`), enforcing `sample_end < vaultCutoffDate` so unknown and
|
||||
* Vault-only trial references are indistinguishable.
|
||||
*/
|
||||
export function createPostgresTrialRefPort(
|
||||
options: PostgresTrialRefPortOptions
|
||||
): TrialRefLookupPort {
|
||||
const { executor, schemaPrefix, vaultCutoffDate } = validateFactoryOptions(options);
|
||||
const sql = buildTrialRefVisibilitySql(schemaPrefix);
|
||||
|
||||
return {
|
||||
async hasResearchVisibleTrial(trialRef: string): Promise<boolean> {
|
||||
if (!isCanonicalPositiveBigInt(trialRef)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const result = await executor.query<RawTrialRefVisibilityRow>(sql, [
|
||||
trialRef,
|
||||
vaultCutoffDate,
|
||||
]);
|
||||
|
||||
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;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
export * from './adapters/postgres-findings';
|
||||
export * from './adapters/postgres-symbol-search';
|
||||
export * from './adapters/postgres-trial-ref';
|
||||
export * from './copilot-server';
|
||||
export * from './protocol';
|
||||
export * from './server';
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue