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:
Studio 2026-12-02 09:10:20 -05:00
parent acfd6a92da
commit d65016c851
3 changed files with 571 additions and 0 deletions

View 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;
},
};
}

View file

@ -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';

View file

@ -0,0 +1,420 @@
import { describe, expect, test } from 'bun:test';
import {
type AppendFindingResult,
FILE_FINDING_ERROR_FILING_FAILED,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
FILE_FINDING_INITIAL_STATUS,
type FileFindingResultPayload,
type FiledFindingRecord,
type FindingWritePort,
PostgresTrialRefError,
type TrialRefExecutor,
createFileFindingTool,
createMcpServer,
createPostgresTrialRefLookupPort,
} from '../src/mcp/index';
import { utcDateOf } from '../src/mcp/tools/vault-fenced-input';
interface RecordedCall {
readonly text: string;
readonly params: readonly unknown[] | undefined;
}
function createFakeExecutor(rows: readonly Record<string, unknown>[] = []): {
readonly calls: RecordedCall[];
readonly executor: TrialRefExecutor;
} {
const calls: RecordedCall[] = [];
const executor: TrialRefExecutor = {
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
calls.push({ text, params });
return { rows: rows as readonly Row[] };
},
};
return { calls, executor };
}
function createFakeWritePort(): {
readonly appended: FiledFindingRecord[];
readonly port: FindingWritePort;
} {
const appended: FiledFindingRecord[] = [];
const port: FindingWritePort = {
async appendFinding(record: FiledFindingRecord): Promise<AppendFindingResult> {
appended.push(record);
return {
status: 'created',
id: record.id,
createdAt: record.createdAt,
};
},
};
return { appended, port };
}
const CUTOFF_MIDNIGHT_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); // 2025-06-30T00:00:00.000Z
describe('createPostgresTrialRefLookupPort', () => {
test('rejects missing or non-callable executor with INVALID_EXECUTOR', () => {
const invalidOptions: unknown[] = [
null,
undefined,
{},
{ executor: null, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
{ executor: {}, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
{ executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
];
for (const opts of invalidOptions) {
let caught: unknown;
try {
createPostgresTrialRefLookupPort(
opts as Parameters<typeof createPostgresTrialRefLookupPort>[0]
);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect(caught).toBeInstanceOf(RangeError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR');
}
});
test('rejects invalid schema names with INVALID_SCHEMA before any query', () => {
const fake = createFakeExecutor([]);
const badSchemas: unknown[] = [
'',
'Bad-Schema',
'a;drop',
'1schema',
'bad.name',
'space name',
'public"; DROP TABLE trial_ledger; --',
123,
null,
];
for (const schema of badSchemas) {
let caught: unknown;
try {
createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
schema: schema as string,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_SCHEMA');
}
expect(fake.calls).toHaveLength(0);
});
test('rejects invalid or extended-year vaultCutoffTs with INVALID_VAULT_CUTOFF', () => {
const fake = createFakeExecutor([]);
const badCutoffs: unknown[] = [
Number.NaN,
Number.POSITIVE_INFINITY,
Number.NEGATIVE_INFINITY,
'2025-06-30',
null,
undefined,
123.45,
Date.parse('+010000-01-01T00:00:00.000Z'),
Date.parse('-000001-01-01T00:00:00.000Z'),
Date.parse('0000-01-01T00:00:00.000Z'),
];
for (const vaultCutoffTs of badCutoffs) {
let caught: unknown;
try {
createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: vaultCutoffTs as number,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF');
}
expect(fake.calls).toHaveLength(0);
});
test('returns true for a visible trial with one parameterized read-only SELECT and exact params', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const visible = await port.hasResearchVisibleTrial('42');
expect(visible).toBe(true);
expect(fake.calls).toHaveLength(1);
const call = fake.calls[0]!;
expect(call.text.trimStart().startsWith('SELECT')).toBe(true);
expect(call.text).not.toContain(';');
expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i);
expect(call.text).toContain('FROM trial_ledger');
expect(call.text).toContain('trial_id = $1::bigint');
expect(call.text).toContain('sample_end < $2::date');
expect(call.text).toContain('LIMIT 1');
expect(call.params).toEqual(['42', '2025-06-30']);
expect(typeof call.params?.[0]).toBe('string');
});
test('returns false when the executor returns empty rows (unknown or Vault-only trial)', async () => {
const fake = createFakeExecutor([]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const visible = await port.hasResearchVisibleTrial('42');
expect(visible).toBe(false);
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']);
});
test('maps midnight and non-midnight UTC vaultCutoffTs to the same UTC date as utcDateOf', async () => {
const nonMidnightTs = Date.UTC(2025, 5, 30, 23, 59, 59, 999);
const nextDayTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0);
const fakeSameDay = createFakeExecutor([{ visible: 1 }]);
const sameDayPort = createPostgresTrialRefLookupPort({
executor: fakeSameDay.executor,
vaultCutoffTs: nonMidnightTs,
});
await sameDayPort.hasResearchVisibleTrial('7');
expect(fakeSameDay.calls[0]!.params).toEqual(['7', utcDateOf(nonMidnightTs)]);
expect(fakeSameDay.calls[0]!.params?.[1]).toBe('2025-06-30');
const fakeNextDay = createFakeExecutor([{ visible: 1 }]);
const nextDayPort = createPostgresTrialRefLookupPort({
executor: fakeNextDay.executor,
vaultCutoffTs: nextDayTs,
});
await nextDayPort.hasResearchVisibleTrial('7');
expect(fakeNextDay.calls[0]!.params).toEqual(['7', '2025-07-01']);
});
test('returns false with zero executor calls for malformed, injection-shaped, overflowing, and non-string refs', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const invalidRefs: unknown[] = [
'',
' 42',
'42 ',
'042',
'0',
'-1',
'+1',
'1.0',
'1e3',
'0x10',
'42; DROP TABLE trial_ledger',
'9223372036854775808',
'10000000000000000000',
42,
42n,
null,
undefined,
{},
];
for (const ref of invalidRefs) {
const result = await port.hasResearchVisibleTrial(ref as string);
expect(result).toBe(false);
}
expect(fake.calls).toHaveLength(0);
});
test('queries the maximum signed 64-bit BIGINT verbatim as a string without numeric coercion', async () => {
const maxBigIntRef = '9223372036854775807';
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefLookupPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const visible = await port.hasResearchVisibleTrial(maxBigIntRef);
expect(visible).toBe(true);
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]!.text).not.toContain(maxBigIntRef);
expect(fake.calls[0]!.params).toEqual([maxBigIntRef, '2025-06-30']);
});
test('quotes validated optional schema and leaves table unqualified when omitted', async () => {
const fakeDefault = createFakeExecutor([]);
const defaultPort = createPostgresTrialRefLookupPort({
executor: fakeDefault.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
await defaultPort.hasResearchVisibleTrial('1');
expect(fakeDefault.calls[0]!.text).toContain('FROM trial_ledger ');
const fakeScoped = createFakeExecutor([]);
const scopedPort = createPostgresTrialRefLookupPort({
executor: fakeScoped.executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
schema: 'research_x',
});
await scopedPort.hasResearchVisibleTrial('1');
expect(fakeScoped.calls[0]!.text).toContain('FROM "research_x".trial_ledger ');
});
test('propagates executor rejections unchanged without retrying', async () => {
const failure = new Error('postgres connection lost');
let attempts = 0;
const executor: TrialRefExecutor = {
async query() {
attempts += 1;
throw failure;
},
};
const port = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure);
expect(attempts).toBe(1);
});
test('accepts a pg.Pool-shaped executor with query on its prototype', async () => {
class PoolLikeExecutor {
readonly calls: RecordedCall[] = [];
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
this.calls.push({ text, params });
return { rows: [{ visible: 1 }] as unknown as readonly Row[] };
}
}
const executor = new PoolLikeExecutor();
const port = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
expect(await port.hasResearchVisibleTrial('99')).toBe(true);
expect(executor.calls).toHaveLength(1);
});
});
describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', () => {
async function callFileFinding(
executor: TrialRefExecutor,
trialRefs: readonly string[]
): Promise<{
readonly appended: FiledFindingRecord[];
readonly result: { readonly content: readonly { type: string; text: string }[]; readonly isError?: boolean };
}> {
const trialLookup = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
});
const { appended, port } = createFakeWritePort();
const tool = createFileFindingTool({
port,
trialLookup,
newId: () => 'finding-0001',
now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0),
});
const server = createMcpServer({
name: 'test-copilot',
version: '0.1.0',
tools: [tool],
});
const rawResponse = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'file_finding',
arguments: {
kind: 'finding',
title: 'Pre-vault momentum signal',
summary: 'Observed stable rank IC across US equities prior to cutoff.',
trialRefs,
},
},
})
);
const parsed = JSON.parse(rawResponse!) as {
readonly result: {
readonly content: readonly { type: string; text: string }[];
readonly isError?: boolean;
};
};
return { appended, result: parsed.result };
}
test('files a pending_review finding and returns a created receipt when the trial is visible', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const { appended, result } = await callFileFinding(fake.executor, ['42']);
expect(result.isError).toBeUndefined();
const payload = JSON.parse(result.content[0]!.text) as FileFindingResultPayload;
expect(payload).toEqual({
id: 'finding-0001',
createdAt: '2025-06-29T12:00:00.000Z',
created: true,
});
expect(appended).toHaveLength(1);
expect(appended[0]).toEqual({
id: 'finding-0001',
kind: 'finding',
title: 'Pre-vault momentum signal',
status: FILE_FINDING_INITIAL_STATUS,
createdAt: '2025-06-29T12:00:00.000Z',
summary: 'Observed stable rank IC across US equities prior to cutoff.',
trialRefs: ['42'],
evidenceRefs: [],
});
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']);
});
test('returns FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF with zero appends when executor returns no rows', async () => {
const fake = createFakeExecutor([]);
const { appended, result } = await callFileFinding(fake.executor, ['42']);
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(appended).toHaveLength(0);
expect(fake.calls).toHaveLength(1);
});
test('returns FILE_FINDING_ERROR_FILING_FAILED with zero appends when executor rejects', async () => {
const executor: TrialRefExecutor = {
async query() {
throw new Error('database unavailable');
},
};
const { appended, result } = await callFileFinding(executor, ['42']);
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_FILING_FAILED);
expect(appended).toHaveLength(0);
});
});