T-167: merge dev

This commit is contained in:
Studio 2026-12-02 11:57:28 -05:00
commit 7c0daf9118
9 changed files with 2844 additions and 345 deletions

View file

@ -6,13 +6,15 @@ import { Client, Pool, type PoolClient, type PoolConfig } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
type AppendFindingResult,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
type FileFindingResultPayload,
type FiledFindingRecord,
type TrialRefExecutor,
createFileFindingTool,
createMcpServer,
createPostgresFindingWritePort,
createPostgresTrialRefPort,
createPostgresTrialRefLookupPort,
} from '../../libs/research/src/mcp/index';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
@ -20,9 +22,13 @@ 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);
// Vault cutoff date 2025-06-30 (exclusive): sample_end must be < 2025-06-30 to be research-visible.
const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0);
const FIXED_TS = '2026-01-15T12:34:56.789Z';
const MAX_BIGINT_REF = '9223372036854775807';
// 2^53 + 1 is not representable as a JS number; Number('9007199254740993') === 9007199254740992.
const ABOVE_SAFE_INT_REF = '9007199254740993';
const ABOVE_SAFE_INT_NEIGHBOR_REF = '9007199254740992';
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
@ -83,7 +89,11 @@ function createPgExecutor(
};
}
function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig {
function buildIsolatedPoolConfig(
connectionString: string | undefined,
schema: string,
extraOptions?: string
): PoolConfig {
const safeUrl = assertSafetyDatabaseUrl(connectionString);
const parsed = new URL(safeUrl);
const existingOptions = parsed.searchParams
@ -92,7 +102,9 @@ function buildIsolatedPoolConfig(connectionString: string | undefined, schema: s
.filter(value => value.length > 0);
parsed.searchParams.delete('options');
const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`;
const schemaOptions = extraOptions
? `-c search_path=${schema} ${extraOptions}`
: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`;
const options = [...existingOptions, schemaOptions].join(' ');
return {
@ -111,6 +123,14 @@ async function createIsolatedFixture(connectionString: string | undefined = url)
cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined));
const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
cleanup.push(() => pool.end());
const readOnlyPool = new Pool(
buildIsolatedPoolConfig(
safeUrl,
schema,
'-c default_transaction_read_only=on -c statement_timeout=5000'
)
);
cleanup.push(() => readOnlyPool.end());
const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>(
'SELECT current_schema() AS current_schema'
@ -141,48 +161,31 @@ async function createIsolatedFixture(connectionString: string | undefined = url)
});
await runPostgresMigrations(postgres, { track: 'research' });
await seedTrials(pool);
return { admin, pool, schema };
return { admin, pool, readOnlyPool, 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;
async function seedTrials(pool: Pool): Promise<void> {
const trials: readonly (readonly [string, string])[] = [
['1', '2025-06-29'], // last research-visible day
['2', '2025-06-30'], // sample_end == cutoff: Vault-only
['3', '2025-07-15'], // sample_end after cutoff: Vault-only
[ABOVE_SAFE_INT_REF, '2024-01-31'],
[MAX_BIGINT_REF, '2020-01-31'],
];
for (const [trialId, sampleEnd] of trials) {
await pool.query(
`INSERT INTO trial_ledger (
trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash,
sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series
)
OVERRIDING SYSTEM VALUE
VALUES ($1::bigint, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64),
'2020-01-01'::date, $2::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`,
[trialId, sampleEnd]
);
}
}
describe('PostgreSQL trial-ref adapter safety guard', () => {
@ -227,53 +230,170 @@ describe('PostgreSQL trial-ref adapter safety guard', () => {
});
});
describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => {
test('enforces strict sample_end < vaultCutoffDate across default search_path and explicit schema', async () => {
describe.skipIf(!url)('PostgreSQL MCP trial-ref lookup adapter', () => {
test('exposes only trials with sample_end strictly before the UTC Vault cutoff date', 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({
const port = createPostgresTrialRefLookupPort({
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);
expect(await port.hasResearchVisibleTrial('1')).toBe(true);
expect(await port.hasResearchVisibleTrial('2')).toBe(false);
expect(await port.hasResearchVisibleTrial('3')).toBe(false);
expect(await port.hasResearchVisibleTrial('4')).toBe(false); // unknown
expect(await port.hasResearchVisibleTrial(MAX_BIGINT_REF)).toBe(true);
});
// Explicit schema option against the admin pool (default search_path)
const scopedPort = createPostgresTrialRefPort({
executor: createPgExecutor(f.admin),
test('matches BIGINT ids above 2^53 exactly without numeric coercion', async () => {
const f = await createIsolatedFixture();
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
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);
expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_REF)).toBe(true);
expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_NEIGHBOR_REF)).toBe(false);
});
test('moves the visibility boundary with the cutoff date, including a near-midnight UTC instant', async () => {
const f = await createIsolatedFixture();
const executor = createPgExecutor(f.pool);
const lastMsOfCutoffDay = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 59, 59, 999),
});
const nextDay = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0),
});
expect(await lastMsOfCutoffDay.hasResearchVisibleTrial('2')).toBe(false);
expect(await nextDay.hasResearchVisibleTrial('2')).toBe(true);
expect(await nextDay.hasResearchVisibleTrial('3')).toBe(false);
});
test('runs in a read-only session and is unaffected by the session TimeZone', async () => {
const f = await createIsolatedFixture();
const client = await f.readOnlyPool.connect();
try {
await client.query("SET TimeZone = 'Pacific/Kiritimati'");
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(client),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('1')).toBe(true);
expect(await port.hasResearchVisibleTrial('2')).toBe(false);
} finally {
await client.query('RESET TimeZone');
client.release();
}
});
test('qualifies trial_ledger with an explicit schema when the session search_path does not include it', async () => {
const f = await createIsolatedFixture();
const client = await f.admin.connect();
try {
// Pin a search_path that cannot contain trial_ledger, independent of the shared public schema.
await client.query('SET search_path TO pg_catalog');
const unqualified = createPostgresTrialRefLookupPort({
executor: createPgExecutor(client),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
const qualified = createPostgresTrialRefLookupPort({
executor: createPgExecutor(client),
vaultCutoffTs: VAULT_CUTOFF_TS,
schema: f.schema,
});
expect(await qualified.hasResearchVisibleTrial('1')).toBe(true);
expect(await qualified.hasResearchVisibleTrial('2')).toBe(false);
// Missing relation must surface as a rejection, never as "not visible".
await expect(unqualified.hasResearchVisibleTrial('1')).rejects.toMatchObject({
code: '42P01',
});
} finally {
await client.query('RESET search_path');
client.release();
}
});
test('leaves trial_ledger untouched and never executes an injection-shaped ref', async () => {
const f = await createIsolatedFixture();
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('1 OR 1=1')).toBe(false);
expect(await port.hasResearchVisibleTrial("1'; DELETE FROM trial_ledger; --")).toBe(false);
const { rows } = await f.pool.query<{ n: string }>('SELECT count(*)::text AS n FROM trial_ledger');
expect(rows[0]!.n).toBe('5');
});
test('files through createFileFindingTool only when every trial ref is research-visible', async () => {
const f = await createIsolatedFixture();
const trialLookup = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
const appended: FiledFindingRecord[] = [];
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createFileFindingTool({
port: {
async appendFinding(record: FiledFindingRecord): Promise<AppendFindingResult> {
appended.push(record);
return { status: 'created', id: record.id, createdAt: record.createdAt };
},
},
trialLookup,
newId: () => 'finding-pg-0001',
now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0),
}),
],
});
const call = async (trialRefs: readonly string[]) => {
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'file_finding',
arguments: {
kind: 'finding',
title: 'Pre-vault signal',
summary: 'Research-visible evidence only.',
trialRefs,
},
},
})
);
return (JSON.parse(raw!) as { result: { isError?: boolean; content: { text: string }[] } })
.result;
};
const mixed = await call(['1', '2']);
expect(mixed.isError).toBe(true);
expect(mixed.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(appended).toHaveLength(0);
const visible = await call(['1', MAX_BIGINT_REF]);
expect(visible.isError).toBeUndefined();
expect(appended).toHaveLength(1);
expect(appended[0]!.trialRefs).toEqual(['1', MAX_BIGINT_REF]);
});
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({
const trialLookup = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
@ -320,7 +440,7 @@ describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => {
kind: 'finding',
title: 'Pre-cutoff signal holds across US equities',
summary: 'Positive IC verified strictly before the Vault cutoff.',
trialRefs: [visibleTrialId],
trialRefs: ['1'],
evidenceRefs: ['snap:2025-06-29:ic'],
});
expect(okRes.isError).toBeUndefined();
@ -340,12 +460,12 @@ describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => {
{
id: 'finding-trial-ref-1',
status: 'pending_review',
trial_refs: [visibleTrialId],
trial_refs: ['1'],
},
]);
// 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']) {
for (const deniedRef of ['2', '3', '999999999']) {
const deniedRes = await callFileFinding({
kind: 'dead_end',
title: 'Should be rejected by Vault fence',