T-159: M2.1l — 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
acfd6a92da
commit
d65016c851
3 changed files with 571 additions and 0 deletions
150
libs/research/src/mcp/adapters/postgres-trial-ref.ts
Normal file
150
libs/research/src/mcp/adapters/postgres-trial-ref.ts
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
/**
|
||||
* 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';
|
||||
|
||||
/** 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}. */
|
||||
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;
|
||||
}
|
||||
|
||||
interface TrialVisibilityRow {
|
||||
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`.
|
||||
*
|
||||
* 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<TrialVisibilityRow>(sql, [trialRef, cutoffDate]);
|
||||
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
|
||||
throw new TypeError('Invalid executor response: expected an object with a rows array.');
|
||||
}
|
||||
return result.rows.length > 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
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