import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { describe, expect, test } from 'bun:test'; import { setLoggerConfig } from '@stock-bot/logger'; import { runPostgresMigrations, type MigrationTrack } from '@stock-bot/postgres'; import { FILE_FINDING_INITIAL_STATUS, FILE_FINDING_KINDS, FILE_FINDING_MAX_EVIDENCE_REFS, FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, FILE_FINDING_MAX_REF_LENGTH, FILE_FINDING_MAX_SUMMARY_LENGTH, FILE_FINDING_MAX_TITLE_LENGTH, FILE_FINDING_MAX_TRIAL_REFS, } from '@stock-bot/research/mcp'; // Static contract checks for 37-research-findings.sql. No database needed, so these run in the // sandbox as well as in Studio's unsandboxed run. They guard against drift between the SQL CHECKs, // the MCP tool limits they mirror, and the design/DATA-CONTRACTS.md copy of the schema. setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); const sqlPath = `${initDir}37-research-findings.sql`; const docPath = fileURLToPath(new URL('../../design/DATA-CONTRACTS.md', import.meta.url)); const readSql = () => readFileSync(sqlPath, 'utf8'); const readDoc = () => readFileSync(docPath, 'utf8'); function stripComments(sql: string): string { return sql .split('\n') .map(line => line.replace(/--.*$/, '').trimEnd()) .join('\n'); } function normalize(sql: string): string { return stripComments(sql).replace(/\s+/g, ' ').trim(); } function tableBlock(sql: string, table: string): string { const match = new RegExp(`CREATE TABLE IF NOT EXISTS ${table} \\(\\n([\\s\\S]*?)\\n\\);`).exec( stripComments(sql) ); if (!match?.[1]) { throw new Error(`CREATE TABLE ${table} not found`); } return match[1].replace(/\s+/g, ' ').trim(); } function docSqlBlock(): string { const doc = readDoc(); const tableStart = doc.indexOf('CREATE TABLE IF NOT EXISTS findings ('); expect(tableStart).toBeGreaterThan(-1); const fenceStart = doc.lastIndexOf('```sql', tableStart); const fenceEnd = doc.indexOf('```', tableStart); return doc.slice(fenceStart + '```sql'.length, fenceEnd).trim(); } function trimCodePointsFromSql(): number[] { const match = /U&'([^']*)'/.exec(stripComments(readSql())); if (!match?.[1]) { throw new Error('research_trim_ecmascript U& character set not found'); } return match[1] .split('\\') .filter(part => part.length > 0) .map(part => { expect(part).toMatch(/^[0-9A-F]{4}$/i); return Number.parseInt(part, 16); }); } async function filesForTrack(track: MigrationTrack): Promise { const postgres = { transaction: async (callback: (client: { query: (sql: string) => unknown }) => Promise) => callback({ query: async () => ({ rows: [] }) }), }; return runPostgresMigrations(postgres as never, { track }); } describe('37-research-findings.sql static contract', () => { test('creates exactly findings and provider_caveats with IF NOT EXISTS and no schema qualifiers', () => { const sql = stripComments(readSql()); const created = [...sql.matchAll(/CREATE TABLE\s+(IF NOT EXISTS\s+)?("?[\w.]+"?)/g)]; expect(created.map(m => m[2])).toEqual(['findings', 'provider_caveats']); expect(created.every(m => m[1] !== undefined)).toBe(true); expect(sql).not.toMatch(/CREATE\s+DATABASE/i); expect(sql).not.toMatch(/^\s*\\c\b/m); expect(sql).not.toMatch(/\bSET\s+search_path\b/i); expect(sql).not.toMatch(/\b(?:TABLE|EXISTS|ON|FROM)\s+"?\w+"?\."?\w+/i); }); test('findings CHECKs mirror the file_finding tool limits exported from file-finding.ts', () => { const findings = tableBlock(readSql(), 'findings'); const kinds = FILE_FINDING_KINDS.map(kind => `'${kind}'`).join(', '); expect(findings).toContain(`CHECK (kind IN (${kinds}))`); expect(findings).toContain(`DEFAULT '${FILE_FINDING_INITIAL_STATUS}'`); expect(findings).toContain( `CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND ${FILE_FINDING_MAX_TITLE_LENGTH})` ); expect(findings).toContain( `CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND ${FILE_FINDING_MAX_SUMMARY_LENGTH})` ); expect(findings).toContain(`CHECK (cardinality(trial_refs) <= ${FILE_FINDING_MAX_TRIAL_REFS})`); expect(findings).toContain( `CHECK (cardinality(evidence_refs) <= ${FILE_FINDING_MAX_EVIDENCE_REFS})` ); expect(findings).toContain( `CHECK (research_finding_refs_valid(trial_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` ); expect(findings).toContain( `CHECK (research_finding_refs_valid(evidence_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` ); expect(findings).toContain( `char_length(idempotency_key) BETWEEN 1 AND ${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH}` ); expect(findings).toContain('created_at TIMESTAMPTZ NOT NULL,'); expect(findings).toMatch(/idempotency_key TEXT CHECK \(idempotency_key IS NULL OR/); }); test('research_trim_ecmascript strips exactly the BMP code points String.prototype.trim() strips', () => { const sqlSet = trimCodePointsFromSql(); const jsSet: number[] = []; for (let cp = 0; cp <= 0xffff; cp++) { if (cp >= 0xd800 && cp <= 0xdfff) { continue; } if (String.fromCharCode(cp).trim() === '') { jsSet.push(cp); } } expect(new Set(sqlSet).size).toBe(sqlSet.length); expect([...sqlSet].sort((a, b) => a - b)).toEqual(jsSet); expect(sqlSet).toHaveLength(25); }); test('both tables are append-only via reject_research_evidence_mutation row and TRUNCATE triggers', () => { const sql = normalize(readSql()); for (const table of ['findings', 'provider_caveats']) { expect(sql).toContain( `DROP TRIGGER IF EXISTS ${table}_retained ON ${table}; CREATE TRIGGER ${table}_retained BEFORE UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();` ); expect(sql).toContain( `DROP TRIGGER IF EXISTS ${table}_no_truncate ON ${table}; CREATE TRIGGER ${table}_no_truncate BEFORE TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();` ); } // The migration must reuse the shared function, never redefine it. expect(sql).not.toMatch(/FUNCTION reject_research_evidence_mutation\s*\(\s*\)\s*RETURNS/i); }); test('design/DATA-CONTRACTS.md documents both tables and indexes exactly as the migration creates them', () => { const doc = docSqlBlock(); const sql = readSql(); expect(tableBlock(doc, 'findings')).toBe(tableBlock(sql, 'findings')); expect(tableBlock(doc, 'provider_caveats')).toBe(tableBlock(sql, 'provider_caveats')); const indexes = (text: string) => [...normalize(text).matchAll(/CREATE (?:UNIQUE )?INDEX IF NOT EXISTS [^;]+;/g)].map( m => m[0] ); expect(indexes(doc)).toEqual(indexes(sql)); expect(indexes(sql)).toHaveLength(3); }); test('37-research-findings.sql runs on research and all tracks right after 36 and never on master', async () => { const research = await filesForTrack('research'); const all = await filesForTrack('all'); const master = await filesForTrack('master'); expect(research.indexOf('37-research-findings.sql')).toBe( research.indexOf('36-trial-ledger.sql') + 1 ); expect(research.indexOf('36-trial-ledger.sql')).toBeGreaterThan(-1); expect(all).toContain('37-research-findings.sql'); expect(master).not.toContain('37-research-findings.sql'); }); });