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:
Studio 2026-12-02 11:18:28 -05:00
commit 811f006e2f
5 changed files with 1154 additions and 0 deletions

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

View file

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

View file

@ -0,0 +1,263 @@
import { describe, expect, test } from 'bun:test';
import {
createFileFindingTool,
createPostgresTrialRefPort,
FILE_FINDING_ERROR_FILING_FAILED,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
PostgresTrialRefError,
type AppendFindingResult,
type FiledFindingRecord,
type FindingWritePort,
type PostgresTrialRefPortOptions,
type TrialRefExecutor,
} from '../src/mcp/index';
interface RecordedCall {
readonly text: string;
readonly params: readonly unknown[] | undefined;
}
function scriptedExecutor(respond: (params: readonly unknown[] | undefined) => unknown): {
readonly calls: RecordedCall[];
readonly executor: TrialRefExecutor;
} {
const calls: RecordedCall[] = [];
return {
calls,
executor: {
async query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
calls.push({ text, params });
return respond(params) as { readonly rows: readonly Row[] };
},
},
};
}
function recordingWritePort(): {
readonly appended: FiledFindingRecord[];
readonly port: FindingWritePort;
} {
const appended: FiledFindingRecord[] = [];
return {
appended,
port: {
async appendFinding(record): Promise<AppendFindingResult> {
appended.push(record);
return { status: 'created', id: record.id, createdAt: record.createdAt };
},
},
};
}
const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z
const CUTOFF_DATE = '2025-06-30';
const FIXED_EPOCH_MS = Date.UTC(2026, 0, 15, 12, 0, 0);
describe('createPostgresTrialRefPort QA edge cases', () => {
test('snapshots executor, schema and cutoff at construction so later option mutation has no effect', async () => {
const original = scriptedExecutor(() => ({ rows: [] }));
const replacement = scriptedExecutor(() => ({ rows: [{ visible: 1 }] }));
const options: {
-readonly [K in keyof PostgresTrialRefPortOptions]: PostgresTrialRefPortOptions[K];
} = {
executor: original.executor,
vaultCutoffTs: CUTOFF_TS,
schema: 'research_a',
};
const port = createPostgresTrialRefPort(options);
options.executor = replacement.executor;
options.vaultCutoffTs = Date.UTC(2030, 0, 1);
options.schema = 'research_b';
expect(await port.hasResearchVisibleTrial('5')).toBe(false);
expect(replacement.calls).toHaveLength(0);
expect(original.calls).toEqual([
{
text: 'SELECT 1 AS visible FROM "research_a".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1',
params: ['5', CUTOFF_DATE],
},
]);
});
test('binds UTC dates for epoch, pre-1970 and four-digit-year extreme cutoffs', async () => {
const cases: [number, string][] = [
[0, '1970-01-01'],
[-1, '1969-12-31'],
[Date.UTC(2025, 5, 30, 0, 0, 0, 0), '2025-06-30'],
[Date.UTC(2025, 5, 30, 23, 59, 59, 999), '2025-06-30'],
[new Date('0001-01-01T00:00:00.000Z').getTime(), '0001-01-01'],
[new Date('9999-12-31T23:59:59.999Z').getTime(), '9999-12-31'],
];
for (const [vaultCutoffTs, expectedDate] of cases) {
const fake = scriptedExecutor(() => ({ rows: [] }));
const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs });
expect(await port.hasResearchVisibleTrial('1')).toBe(false);
expect(fake.calls[0]?.params).toEqual(['1', expectedDate]);
}
});
test('reports INVALID_EXECUTOR before schema or cutoff errors when several options are invalid', () => {
let caught: unknown;
try {
createPostgresTrialRefPort({
executor: {} as TrialRefExecutor,
vaultCutoffTs: Number.NaN,
schema: 'Bad-Schema',
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect(caught).toBeInstanceOf(RangeError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR');
expect((caught as PostgresTrialRefError).name).toBe('PostgresTrialRefError');
});
test('queries every canonical id across the 1..19 digit range up to the PostgreSQL bigint max', async () => {
const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] }));
const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS });
const accepted = [
'1',
'9',
'10',
'999999999999999999',
'1000000000000000000',
'9223372036854775799',
'9223372036854775806',
'9223372036854775807',
];
for (const ref of accepted) {
expect(await port.hasResearchVisibleTrial(ref)).toBe(true);
}
expect(fake.calls.map(call => call.params?.[0])).toEqual(accepted);
});
test('returns false without querying for out-of-range, unicode-digit, control-char and boxed refs', async () => {
const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] }));
const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS });
const rejected: unknown[] = [
'9223372036854775810',
'9300000000000000000',
'12345678901234567890',
'١', // Arabic-Indic digit one
'1', // full-width digit one
'1\u0000',
' 1',
'1​',
new String('1'),
Number.MAX_SAFE_INTEGER,
];
for (const ref of rejected) {
expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false);
}
expect(fake.calls).toHaveLength(0);
});
test('concurrent lookups each issue their own query and keep their own answers', async () => {
const fake = scriptedExecutor(params => ({
rows: params?.[0] === '2' ? [{ visible: 1 }] : [],
}));
const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS });
const results = await Promise.all(
['1', '2', '3', '2'].map(ref => port.hasResearchVisibleTrial(ref))
);
expect(results).toEqual([false, true, false, true]);
expect(fake.calls).toHaveLength(4);
for (const call of fake.calls) {
expect(call.text).toMatch(/^SELECT 1 AS visible FROM trial_ledger WHERE /);
expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i);
expect(call.params?.[1]).toBe(CUTOFF_DATE);
}
});
test('exposes only the read-only hasResearchVisibleTrial method', () => {
const fake = scriptedExecutor(() => ({ rows: [] }));
const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS });
expect(Object.keys(port)).toEqual(['hasResearchVisibleTrial']);
});
});
describe('createPostgresTrialRefPort composed with file_finding (fake executor)', () => {
function composeTool(respond: (params: readonly unknown[] | undefined) => unknown) {
const fake = scriptedExecutor(respond);
const writes = recordingWritePort();
const tool = createFileFindingTool({
port: writes.port,
trialLookup: createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_TS,
}),
newId: () => 'finding-qa-1',
now: () => FIXED_EPOCH_MS,
});
return { fake, tool, writes };
}
const baseArgs = { kind: 'finding', title: 'QA filing', summary: 'Visible-only summary.' };
test('a visible ref files one finding with the original string ref', async () => {
const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] }));
const res = await tool.execute({ ...baseArgs, trialRefs: ['9223372036854775807'] });
expect(res.isError).toBeUndefined();
expect(fake.calls).toHaveLength(1);
expect(writes.appended).toHaveLength(1);
expect(writes.appended[0]?.trialRefs).toEqual(['9223372036854775807']);
expect(writes.appended[0]?.status).toBe('pending_review');
});
test('a non-canonical ref is reported unavailable without any query or append', async () => {
const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] }));
const res = await tool.execute({ ...baseArgs, trialRefs: ['1; DROP TABLE trial_ledger'] });
expect(res.isError).toBe(true);
expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(fake.calls).toHaveLength(0);
expect(writes.appended).toHaveLength(0);
});
test('one Vault-only ref among visible refs rejects the whole filing with zero appends', async () => {
const { tool, writes } = composeTool(params => ({
rows: params?.[0] === '20' ? [] : [{ visible: 1 }],
}));
const res = await tool.execute({ ...baseArgs, trialRefs: ['10', '20', '30'] });
expect(res.isError).toBe(true);
expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(writes.appended).toHaveLength(0);
});
test('a malformed multi-row response fails closed as filing_failed with zero appends', async () => {
const { tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }, { visible: 1 }] }));
const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] });
expect(res.isError).toBe(true);
expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED);
expect(writes.appended).toHaveLength(0);
});
test('an executor failure fails closed as filing_failed with zero appends', async () => {
const { tool, writes } = composeTool(() => {
throw new Error('connection terminated');
});
const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] });
expect(res.isError).toBe(true);
expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED);
expect(writes.appended).toHaveLength(0);
});
});

View file

@ -0,0 +1,361 @@
import { describe, expect, test } from 'bun:test';
import { MarketDataStoreValidationError } from '../src/market-data-store';
import {
PostgresTrialRefError,
type TrialRefExecutor,
createPostgresTrialRefPort,
} from '../src/mcp/index';
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 };
}
const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z
const CUTOFF_DATE = '2025-06-30';
describe('createPostgresTrialRefPort (fake executor)', () => {
test('issues exact parameterized SELECT with default search_path and explicit quoted schema', async () => {
const fakeDefault = createFakeExecutor([{ visible: 1 }]);
const defaultPort = createPostgresTrialRefPort({
executor: fakeDefault.executor,
vaultCutoffTs: CUTOFF_TS,
});
expect(await defaultPort.hasResearchVisibleTrial('42')).toBe(true);
expect(fakeDefault.calls).toEqual([
{
text: 'SELECT 1 AS visible FROM trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1',
params: ['42', CUTOFF_DATE],
},
]);
const fakeScoped = createFakeExecutor([{ visible: 1 }]);
const scopedPort = createPostgresTrialRefPort({
executor: fakeScoped.executor,
vaultCutoffTs: CUTOFF_TS,
schema: 'research_iso_1',
});
expect(await scopedPort.hasResearchVisibleTrial('42')).toBe(true);
expect(fakeScoped.calls).toEqual([
{
text: 'SELECT 1 AS visible FROM "research_iso_1".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1',
params: ['42', CUTOFF_DATE],
},
]);
});
test('converts vaultCutoffTs once to UTC calendar date across midnight boundaries', async () => {
const lateFake = createFakeExecutor([]);
// 2025-06-30T23:30:00.000Z is already 2025-07-01 in UTC+1 zones; must bind UTC date 2025-06-30.
const latePort = createPostgresTrialRefPort({
executor: lateFake.executor,
vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 30, 0, 0),
});
expect(await latePort.hasResearchVisibleTrial('7')).toBe(false);
expect(lateFake.calls[0]?.params).toEqual(['7', '2025-06-30']);
const nextFake = createFakeExecutor([]);
const nextPort = createPostgresTrialRefPort({
executor: nextFake.executor,
vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0),
});
expect(await nextPort.hasResearchVisibleTrial('7')).toBe(false);
expect(nextFake.calls[0]?.params).toEqual(['7', '2025-07-01']);
});
test('rejects invalid options and executors with INVALID_EXECUTOR before any query', () => {
const invalidOptions: unknown[] = [
null,
undefined,
{},
{ executor: null, vaultCutoffTs: CUTOFF_TS },
{ executor: {}, vaultCutoffTs: CUTOFF_TS },
{ executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_TS },
];
for (const opts of invalidOptions) {
let caught: unknown;
try {
createPostgresTrialRefPort(opts as Parameters<typeof createPostgresTrialRefPort>[0]);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR');
}
});
test('rejects invalid schema identifiers with INVALID_SCHEMA before any query', () => {
const fake = createFakeExecutor([]);
const badSchemas: unknown[] = [
'',
'Public',
'1schema',
'bad-name',
'bad.name',
'public"; DROP TABLE trial_ledger; --',
'space name',
123,
null,
];
for (const schema of badSchemas) {
let caught: unknown;
try {
createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_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('accepts minimal valid schema identifiers and prototype-method pg.Pool-shaped executors', async () => {
for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) {
const fake = createFakeExecutor([]);
const port = createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_TS,
schema,
});
await port.hasResearchVisibleTrial('1');
expect(fake.calls[0]?.text).toContain(`FROM "${schema}".trial_ledger `);
}
class PrototypeExecutor {
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 PrototypeExecutor();
const port = createPostgresTrialRefPort({ executor, vaultCutoffTs: CUTOFF_TS });
expect(await port.hasResearchVisibleTrial('101')).toBe(true);
expect(executor.calls).toHaveLength(1);
});
test('rejects invalid or non-PostgreSQL-date vaultCutoffTs with MarketDataStoreValidationError', () => {
const fake = createFakeExecutor([]);
const yearZeroTs = new Date('0000-06-15T00:00:00.000Z').getTime();
const negativeYearTs = new Date('-000001-01-01T00:00:00.000Z').getTime();
const fiveDigitYearTs = new Date('+010000-01-01T00:00:00.000Z').getTime();
const invalidCutoffs: unknown[] = [
undefined,
null,
'2025-06-30',
Number.NaN,
Number.POSITIVE_INFINITY,
Number.NEGATIVE_INFINITY,
1.5,
Number.MAX_SAFE_INTEGER + 1,
8_640_000_000_000_000,
-8_640_000_000_000_000,
yearZeroTs,
negativeYearTs,
fiveDigitYearTs,
];
for (const vaultCutoffTs of invalidCutoffs) {
let caught: unknown;
try {
createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: vaultCutoffTs as number,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
expect((caught as MarketDataStoreValidationError).field).toBe('vaultCutoffTs');
}
expect(fake.calls).toHaveLength(0);
});
test('returns false with zero executor calls for every invalid, non-canonical, overflow, or injection-shaped ref', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_TS,
});
const invalidRefs: unknown[] = [
'',
' ',
' 1',
'1 ',
'\t1',
'1\n',
'0',
'-1',
'+1',
'01',
'0001',
'1.0',
'1e2',
'1E2',
'0x10',
'1_000',
'abc',
'1; DROP TABLE trial_ledger',
'1 OR 1=1',
'9223372036854775808',
'9999999999999999999',
'10000000000000000000',
1,
0,
null,
undefined,
{},
[],
1n,
];
for (const ref of invalidRefs) {
expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false);
}
expect(fake.calls).toHaveLength(0);
});
test('passes 9223372036854775807 as an exact string without Number coercion and skips 9223372036854775808', async () => {
const fake = createFakeExecutor([{ visible: 1 }]);
const port = createPostgresTrialRefPort({
executor: fake.executor,
vaultCutoffTs: CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('9223372036854775807')).toBe(true);
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]?.params).toEqual(['9223372036854775807', CUTOFF_DATE]);
expect(typeof fake.calls[0]?.params?.[0]).toBe('string');
expect(await port.hasResearchVisibleTrial('9223372036854775808')).toBe(false);
expect(fake.calls).toHaveLength(1);
});
test('returns false for zero rows and true for exactly one valid visibility row', async () => {
const emptyFake = createFakeExecutor([]);
const emptyPort = createPostgresTrialRefPort({
executor: emptyFake.executor,
vaultCutoffTs: CUTOFF_TS,
});
expect(await emptyPort.hasResearchVisibleTrial('123')).toBe(false);
const hitFake = createFakeExecutor([{ visible: 1 }]);
const hitPort = createPostgresTrialRefPort({
executor: hitFake.executor,
vaultCutoffTs: CUTOFF_TS,
});
expect(await hitPort.hasResearchVisibleTrial('123')).toBe(true);
});
test('throws INVALID_ROW for malformed envelopes, invalid singleton rows, and multiple rows (regression)', async () => {
const badResponses: unknown[] = [
null,
undefined,
{},
{ rows: null },
{ rows: 'not-an-array' },
{ rows: {} },
{ rows: [null] },
{ rows: [undefined] },
{ rows: [1] },
{ rows: [{}] },
{ rows: [{ visible: '1' }] },
{ rows: [{ visible: true }] },
{ rows: [{ visible: 0 }] },
{ rows: [{ visible: 2 }] },
{ rows: [{ visible: null }] },
// Regression: multiple rows must fail closed rather than returning true.
{ rows: [{ visible: 1 }, { visible: 1 }] },
];
for (const response of badResponses) {
const executor: TrialRefExecutor = {
async query() {
return response as { readonly rows: readonly never[] };
},
};
const port = createPostgresTrialRefPort({
executor,
vaultCutoffTs: CUTOFF_TS,
});
let caught: unknown;
try {
await port.hasResearchVisibleTrial('101');
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresTrialRefError);
expect((caught as PostgresTrialRefError).code).toBe('INVALID_ROW');
}
});
test('propagates rejected and synchronously thrown executor errors unchanged without retrying', async () => {
const asyncFailure = new Error('connection terminated');
let asyncAttempts = 0;
const asyncExecutor: TrialRefExecutor = {
async query() {
asyncAttempts += 1;
throw asyncFailure;
},
};
const asyncPort = createPostgresTrialRefPort({
executor: asyncExecutor,
vaultCutoffTs: CUTOFF_TS,
});
await expect(asyncPort.hasResearchVisibleTrial('101')).rejects.toBe(asyncFailure);
expect(asyncAttempts).toBe(1);
const syncFailure = new Error('sync driver failure');
let syncAttempts = 0;
const syncExecutor: TrialRefExecutor = {
query() {
syncAttempts += 1;
throw syncFailure;
},
};
const syncPort = createPostgresTrialRefPort({
executor: syncExecutor,
vaultCutoffTs: CUTOFF_TS,
});
await expect(syncPort.hasResearchVisibleTrial('101')).rejects.toBe(syncFailure);
expect(syncAttempts).toBe(1);
});
});

View file

@ -0,0 +1,364 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import { Client, Pool, type PoolClient, type PoolConfig } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
type FileFindingResultPayload,
type TrialRefExecutor,
createFileFindingTool,
createMcpServer,
createPostgresFindingWritePort,
createPostgresTrialRefPort,
} from '../../libs/research/src/mcp/index';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('mcp-trial-ref-adapter-pg-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
// Non-midnight UTC cutoff on 2025-06-30; research-visible requires sample_end < 2025-06-30.
const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500);
const FIXED_TS = '2026-01-15T12:34:56.789Z';
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
// Run every cleanup step even if an earlier one fails, then surface the first failure.
let firstError: unknown;
for (const close of cleanup.splice(0).reverse()) {
try {
await close();
} catch (err) {
firstError ??= err;
}
}
if (firstError !== undefined) {
throw firstError;
}
});
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
if (!connectionString) {
throw new Error('Dedicated stock_bot_safety database required');
}
let parsed: URL;
try {
parsed = new URL(connectionString);
} catch {
throw new Error('Dedicated stock_bot_safety database required');
}
if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
throw new Error('Dedicated stock_bot_safety database required');
}
const client = new Client({ connectionString });
const effectiveDb = (
client as unknown as { connectionParameters?: { database?: unknown } }
).connectionParameters?.database;
if (
typeof effectiveDb !== 'string' ||
!effectiveDb.startsWith('stock_bot_safety') ||
!parsed.pathname.startsWith('/stock_bot_safety')
) {
throw new Error('Dedicated stock_bot_safety database required');
}
return connectionString;
}
function createPgExecutor(
queryable: Pick<Pool, 'query'> | Pick<PoolClient, 'query'>
): TrialRefExecutor {
return {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
return queryable.query(
text,
params === undefined ? undefined : [...params]
) as unknown as Promise<{ readonly rows: readonly Row[] }>;
},
};
}
function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig {
const safeUrl = assertSafetyDatabaseUrl(connectionString);
const parsed = new URL(safeUrl);
const existingOptions = parsed.searchParams
.getAll('options')
.map(value => value.trim())
.filter(value => value.length > 0);
parsed.searchParams.delete('options');
const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`;
const options = [...existingOptions, schemaOptions].join(' ');
return {
connectionString: parsed.toString(),
options,
};
}
async function createIsolatedFixture(connectionString: string | undefined = url) {
const safeUrl = assertSafetyDatabaseUrl(connectionString);
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: safeUrl });
// Registered before CREATE SCHEMA so the admin pool closes even if creation or teardown fails.
cleanup.push(() => admin.end());
await admin.query(`CREATE SCHEMA ${schema}`);
cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined));
const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
cleanup.push(() => pool.end());
const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>(
'SELECT current_schema() AS current_schema'
);
if (schemaRows[0]?.current_schema !== schema) {
throw new Error(
`Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}`
);
}
// Bootstrap pre-additive tables needed by the research migration track.
for (const filename of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
]) {
await pool.query(readFileSync(`${initDir}${filename}`, 'utf8'));
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', {
get: () => ({
connect: () => pool.connect(),
}),
});
await runPostgresMigrations(postgres, { track: 'research' });
return { admin, pool, schema };
}
async function insertTrialRow(
pool: Pool,
sampleEnd: string,
hashChar: string
): Promise<string> {
const { rows } = await pool.query<{ trial_id: string }>(
`INSERT INTO trial_ledger (
principal_id,
stage,
universe_market,
horizon_bucket,
expression_hash,
sample_start,
sample_end,
n_obs,
sharpe_unann,
skewness,
kurtosis,
daily_series
)
VALUES (
'operator',
'signal_ic',
'US_EQ',
'swing_1_10d',
$1,
'2024-01-02'::date,
$2::date,
252,
0.05,
-0.1,
3.2,
ARRAY[0.01, -0.005]::real[]
)
RETURNING trial_id::text AS trial_id`,
[hashChar.repeat(64), sampleEnd]
);
return rows[0]!.trial_id;
}
describe('PostgreSQL trial-ref adapter safety guard', () => {
test('rejects unsafe database targets before connecting', () => {
expect(() => assertSafetyDatabaseUrl(undefined)).toThrow(
'Dedicated stock_bot_safety database required'
);
expect(() =>
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot')
).toThrow('Dedicated stock_bot_safety database required');
expect(() =>
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev')
).toThrow('Dedicated stock_bot_safety database required');
expect(() =>
assertSafetyDatabaseUrl('socket:/stock_bot_safety?db=trading_bot')
).toThrow('Dedicated stock_bot_safety database required');
expect(() =>
assertSafetyDatabaseUrl('http://127.0.0.1:5432/stock_bot_safety_test')
).toThrow('Dedicated stock_bot_safety database required');
expect(() => assertSafetyDatabaseUrl('not-a-valid-url')).toThrow(
'Dedicated stock_bot_safety database required'
);
expect(
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test')
).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test');
});
test('preserves isolated schema search_path precedence over URL startup options', () => {
const schema = 'stock_bot_safety_trial_ref_options';
const urlWithOptions =
'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic';
const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema);
expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false);
const client = new Client(poolConfig);
const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } })
.connectionParameters.options;
expect(resolvedOptions).toBe(
`-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`
);
});
});
describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => {
test('enforces strict sample_end < vaultCutoffDate across default search_path and explicit schema', async () => {
const f = await createIsolatedFixture();
const beforeCutoffId = await insertTrialRow(f.pool, '2025-06-29', 'a');
const onCutoffId = await insertTrialRow(f.pool, '2025-06-30', 'b');
const afterCutoffId = await insertTrialRow(f.pool, '2025-07-01', 'c');
const defaultPort = createPostgresTrialRefPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await defaultPort.hasResearchVisibleTrial(beforeCutoffId)).toBe(true);
expect(await defaultPort.hasResearchVisibleTrial(onCutoffId)).toBe(false);
expect(await defaultPort.hasResearchVisibleTrial(afterCutoffId)).toBe(false);
expect(await defaultPort.hasResearchVisibleTrial('999999999')).toBe(false);
expect(await defaultPort.hasResearchVisibleTrial('1; DROP TABLE trial_ledger')).toBe(false);
// Largest bigint binds through $1::bigint without overflow and is simply unknown.
expect(await defaultPort.hasResearchVisibleTrial('9223372036854775807')).toBe(false);
const { rows: ledgerCount } = await f.pool.query<{ c: number }>(
'SELECT count(*)::int AS c FROM trial_ledger'
);
expect(ledgerCount[0]?.c).toBe(3);
// Explicit schema option against the admin pool (default search_path)
const scopedPort = createPostgresTrialRefPort({
executor: createPgExecutor(f.admin),
vaultCutoffTs: VAULT_CUTOFF_TS,
schema: f.schema,
});
expect(await scopedPort.hasResearchVisibleTrial(beforeCutoffId)).toBe(true);
expect(await scopedPort.hasResearchVisibleTrial(onCutoffId)).toBe(false);
expect(await scopedPort.hasResearchVisibleTrial(afterCutoffId)).toBe(false);
expect(await scopedPort.hasResearchVisibleTrial('999999999')).toBe(false);
});
test('composes with createFileFindingTool and createPostgresFindingWritePort through MCP', async () => {
const f = await createIsolatedFixture();
const visibleTrialId = await insertTrialRow(f.pool, '2025-06-29', '1');
const equalCutoffTrialId = await insertTrialRow(f.pool, '2025-06-30', '2');
const afterCutoffTrialId = await insertTrialRow(f.pool, '2025-07-01', '3');
const executor = createPgExecutor(f.pool);
const trialLookup = createPostgresTrialRefPort({
executor,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
const writePort = createPostgresFindingWritePort({ executor });
let idSeq = 0;
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createFileFindingTool({
port: writePort,
trialLookup,
newId: () => {
idSeq += 1;
return `finding-trial-ref-${idSeq}`;
},
now: () => new Date(FIXED_TS),
}),
],
});
const callFileFinding = async (args: Record<string, unknown>) => {
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 'req-file-finding',
method: 'tools/call',
params: {
name: 'file_finding',
arguments: args,
},
})
);
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw!) as {
result: { isError?: boolean; content: Array<{ text: string }> };
};
return parsed.result;
};
// Visible trial (sample_end = 2025-06-29 < 2025-06-30) succeeds and persists pending_review row.
const okRes = await callFileFinding({
kind: 'finding',
title: 'Pre-cutoff signal holds across US equities',
summary: 'Positive IC verified strictly before the Vault cutoff.',
trialRefs: [visibleTrialId],
evidenceRefs: ['snap:2025-06-29:ic'],
});
expect(okRes.isError).toBeUndefined();
const receipt = JSON.parse(okRes.content[0]!.text) as FileFindingResultPayload;
expect(receipt).toEqual({
id: 'finding-trial-ref-1',
createdAt: FIXED_TS,
created: true,
});
const storedRows = (
await f.pool.query<{ id: string; status: string; trial_refs: string[] }>(
'SELECT id, status, trial_refs FROM findings ORDER BY id ASC'
)
).rows;
expect(storedRows).toEqual([
{
id: 'finding-trial-ref-1',
status: 'pending_review',
trial_refs: [visibleTrialId],
},
]);
// Vault-only (equal to cutoff, after cutoff) and unknown citations all return the same error with zero rows added.
for (const deniedRef of [equalCutoffTrialId, afterCutoffTrialId, '999999999']) {
const deniedRes = await callFileFinding({
kind: 'dead_end',
title: 'Should be rejected by Vault fence',
summary: 'References non-visible trial.',
trialRefs: [deniedRef],
});
expect(deniedRes.isError).toBe(true);
expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
}
const totalFindings = (
await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings')
).rows[0]?.c;
expect(totalFindings).toBe(1);
});
});