From 272d3366030fe85467fcfe93cd5872e6376cb62a Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 11:05:08 -0500 Subject: [PATCH] =?UTF-8?q?T-165:=20M2.1l=20(re-queue)=20=E2=80=94=20Postg?= =?UTF-8?q?reSQL=20`trial=5Fledger`=20adapter=20for=20the=20MCP=20copilot?= =?UTF-8?q?=20`file=5Ffinding`=20tool:=20`TrialRefLookupPort`=20over=20an?= =?UTF-8?q?=20injected=20executor=20in=20`libs/research/src/mcp/adapters/p?= =?UTF-8?q?ostgres-trial-ref.ts`=20(research-visible=20=3D=20`sample=5Fend?= =?UTF-8?q?`=20before=20the=20Vault=20cutoff=20date,=20parameterized=20SQL?= =?UTF-8?q?,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/mcp/adapters/postgres-trial-ref.ts | 165 ++++++++ libs/research/src/mcp/index.ts | 1 + .../test/mcp-postgres-trial-ref.test.ts | 361 ++++++++++++++++++ test/postgres/mcp-trial-ref-adapter.test.ts | 350 +++++++++++++++++ 4 files changed, 877 insertions(+) create mode 100644 libs/research/src/mcp/adapters/postgres-trial-ref.ts create mode 100644 libs/research/test/mcp-postgres-trial-ref.test.ts create mode 100644 test/postgres/mcp-trial-ref-adapter.test.ts diff --git a/libs/research/src/mcp/adapters/postgres-trial-ref.ts b/libs/research/src/mcp/adapters/postgres-trial-ref.ts new file mode 100644 index 00000000..adeb9825 --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-trial-ref.ts @@ -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>( + 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 { + if (!isCanonicalPositiveBigInt(trialRef)) { + return false; + } + + const result = await executor.query(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; + }, + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 2af06a5e..a6aab4ad 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -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'; diff --git a/libs/research/test/mcp-postgres-trial-ref.test.ts b/libs/research/test/mcp-postgres-trial-ref.test.ts new file mode 100644 index 00000000..cffaf1a8 --- /dev/null +++ b/libs/research/test/mcp-postgres-trial-ref.test.ts @@ -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[] = []): { + readonly calls: RecordedCall[]; + readonly executor: TrialRefExecutor; +} { + const calls: RecordedCall[] = []; + const executor: TrialRefExecutor = { + async query>( + 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[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>( + 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); + }); +}); diff --git a/test/postgres/mcp-trial-ref-adapter.test.ts b/test/postgres/mcp-trial-ref-adapter.test.ts new file mode 100644 index 00000000..9fc8029b --- /dev/null +++ b/test/postgres/mcp-trial-ref-adapter.test.ts @@ -0,0 +1,350 @@ +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)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +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 | Pick +): TrialRefExecutor { + return { + query>( + 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 }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.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 { + 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); + + // 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) => { + 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); + }); +});