import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { describe, expect, test } from 'bun:test'; // Guards the T-204 M2 completion audit (design/m2-completion-audit.md) against // citation rot: every repo path it cites must resolve, every symbol it reports as // landed must still live in the file it names, and the report must keep host-only // verification marked pending. Gaps the audit reports as missing are deliberately // NOT asserted, so landing an M2 fix never breaks this test. const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); const audit = readFileSync(join(repoRoot, 'design/m2-completion-audit.md'), 'utf8'); const designIndex = readFileSync(join(repoRoot, 'design/README.md'), 'utf8'); // Cited as the gap itself (absent today), as already-retired code, as a sandbox env // note, or as the stale pre-rename docs/ location. const CITED_AS_ABSENT = new Set([ 'scripts/research-copilot-mcp.ts', 'apps/stock/analytics', 'python/.venv', 'docs', 'docs/', 'docs/*.md', ]); function expandBraces(path: string): string[] { const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path); if (!match) {return [path];} const [, prefix, options, suffix] = match; return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`)); } function citedRepoPaths(markdown: string): string[] { const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!); const pathLike = spans.filter( (span) => /^(apps|libs|tools|python|scripts|design|test|database|docs)\//.test(span) || /^[A-Za-z0-9_.-]+\.(md|json|yml)$/.test(span) ); return [ ...new Set( pathLike // Strip `:line`, `:a-b`, and `:a-b,c` suffixes and trailing globs. .map((span) => span.replace(/:[\d,-]+$/, '').replace(/\/\*$/, '')) .flatMap(expandBraces) ), ].sort(); } describe('design/m2-completion-audit.md citations', () => { test('cites only repo paths that exist, except those it reports as absent', () => { const cited = citedRepoPaths(audit); expect(cited.length).toBeGreaterThan(40); const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p))); expect(missing).toEqual([]); }); test('docs/ stays absent so the documentation path-drift note holds', () => { expect(existsSync(join(repoRoot, 'docs'))).toBe(false); expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true); }); // Symbols the audit reports as LANDED, keyed by the file it attributes them to. const landedSymbols: Array<[file: string, symbol: string | RegExp]> = [ ['libs/research/src/mcp/copilot-server.ts', 'createResearchCopilotMcpServer'], ['libs/research/src/mcp/host/stdio-host.ts', 'runResearchCopilotStdioHost'], ['libs/data/postgres/src/research-copilot-executor.ts', 'openResearchCopilotExecutor'], ['libs/data/duckdb/src/research-copilot-store.ts', 'openResearchCopilotStore'], ['libs/data/duckdb/src/research-copilot-store.ts', 'vaultOperatorAuthorized: false'], ['libs/research/src/mcp/tools/query-data.ts', 'createQueryDataTool'], ['libs/research/src/notebook-snapshot.ts', 'exportNotebookSnapshot'], ['libs/research/src/notebook-snapshot-node.ts', 'exportNotebookSnapshot'], ['libs/research/src/market-data-store-duckdb.ts', 'fundamentalsAsOf'], ['libs/research/src/market-data-store-routed.ts', 'createRoutedMarketDataStore'], ['libs/research/src/market-data-store-questdb.ts', 'createQuestDbIntradayBarsReader'], ['libs/research/src/feature-library.ts', 'registerSignal'], ['libs/research/src/feature-library.ts', 'runFeatureBatch'], ['libs/research/src/feature-library.ts', 'export const RET_1D_V1'], ['libs/research/src/feature-library.ts', 'export const FEATURE_INPUT_DATASETS'], ['libs/data/questdb/src/schema.ts', 'M2_INTRADAY_SCHEMAS'], ['libs/data/questdb/src/schema.ts', 'getM2IntradayDDL'], // The schema is declarative; DDL keywords are rendered from these fields. ['libs/data/questdb/src/schema.ts', "capacity: 65536, cache: false"], ['libs/data/questdb/src/schema.ts', "partitionBy: 'MONTH'"], ['libs/data/questdb/src/schema.ts', 'dedupUpsertKeys'], ['tools/curate-etl/src/cli.rs', 'SendIlp('], ['tools/curate-etl/src/cli.rs', 'CurateFundamentals('], ['tools/curate-etl/src/cli.rs', 'CuratePosts('], ['tools/curate-etl/src/cli.rs', 'CurateMacro('], ['tools/curate-etl/src/cli.rs', 'CurateBars1m('], ['tools/curate-etl/src/cli.rs', 'CurateFx1m('], ['tools/curate-etl/src/main.rs', 'run_send_ilp('], ['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'], ['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'], ['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/], ['tools/curate-etl/src/ilp_send_tests.rs', 'fn tcp_sends_separate_shards_and_half_closes'], [ 'tools/curate-etl/src/fundamentals_tests.rs', 'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2', ], [ 'tools/curate-etl/src/run_curate_bars_1m_tests.rs', 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes', ], ['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 'restatement non-overwrite'], ['docker-compose.quant.yml', 'hard: 1048576'], ['docker-compose.quant.yml', 'QDB_RAM_USAGE_LIMIT_BYTES=21474836480'], ['database/postgres/init/37-research-findings.sql', 'provider_caveats'], ['database/postgres/init/36-trial-ledger.sql', 'vault_evaluations'], ]; test.each(landedSymbols)('%s contains %p as the audit reports', (file, symbol) => { const source = readFileSync(join(repoRoot, file), 'utf8'); if (typeof symbol === 'string') {expect(source).toContain(symbol);} else {expect(source).toMatch(symbol);} }); test('every MCP tool the audit counts is registered in the copilot server', () => { const server = readFileSync(join(repoRoot, 'libs/research/src/mcp/copilot-server.ts'), 'utf8'); const tools = ['search_symbols', 'query_data', 'analyze_signal', 'event_study', 'file_finding', 'read_knowledge']; for (const tool of tools) {expect(server).toContain(`'${tool}'`);} expect(audit).toContain('6 MCP tools'); }); test('the synthetic split fixture still documents the observed-data comparison as open', () => { // The audit's EC-3 "synthetic only" status rests on this scope note. const fixture = readFileSync(join(repoRoot, 'tools/curate-etl/src/run_curate_bars_1m_tests.rs'), 'utf8'); expect(fixture).toMatch(/Does NOT prove .* against retained `bars_1d` data/); expect(audit).toMatch(/OPEN \(Synthetic Only\)/); }); }); describe('design/m2-completion-audit.md structure and honesty', () => { test('holds M3 and covers every section the task requires', () => { expect(audit).toMatch(/HOLD M3/); expect(audit).toMatch(/^## 1\. Verification Gate Results/m); expect(audit).toMatch(/^## 2\. M2 Deliverables & Exit Criteria Matrix/m); expect(audit).toMatch(/^## 3\. Candidate Causes/m); expect(audit).toMatch(/^## 4\. Concrete Blockers Needing Director Decisions/m); expect(audit).toMatch(/^## 5\. M3 Readiness Mapping/m); }); test('covers all four M2 deliverables and all three M2 exit criteria', () => { for (const area of ['M2.1', 'M2.2', 'M2.3', 'M2.4']) {expect(audit).toContain(`**${area}**`);} for (const ec of ['EC-1', 'EC-2', 'EC-3']) {expect(audit).toContain(`**${ec}:**`);} for (const ec of ['M3 EC-1', 'M3 EC-2', 'M3 EC-3']) {expect(audit).toContain(`**${ec}:**`);} }); test('keeps host-only verification pending and parking causes unattributed', () => { expect(audit).toMatch(/\|\s*\*\*PENDING\*\*\s*\|/); expect(audit).toContain('none of the four items below can be attributed to a specific parked task'); expect(audit).not.toMatch(/EC-3[^|]*\|\s*\*\*SATISFIED/); }); test('asks the director three decisions, each with a recommendation', () => { const decisions = audit.split(/^## 4\./m)[1]!.split(/^## 5\./m)[0]!; expect(decisions.match(/^\d\. \*\*/gm)?.length).toBe(3); expect(decisions.match(/\*Recommended:\*/g)?.length).toBe(3); }); test('carries the teData regime-filter-only limit into macro follow-ups', () => { expect(audit).toContain('design/DATA-CONTRACTS.md:26'); expect(readFileSync(join(repoRoot, 'design/DATA-CONTRACTS.md'), 'utf8').split('\n')[25]).toContain( 'final-revised values only' ); }); test('is indexed exactly once in design/README.md', () => { const rows = designIndex.split('\n').filter((line) => line.includes('(m2-completion-audit.md)')); expect(rows).toHaveLength(1); expect(rows[0]).toMatch(/^\| \*\*\[m2-completion-audit\.md\]\(m2-completion-audit\.md\)\*\* \|.*\|.*\|$/); }); });