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-208 M2 master audit (design/m2-master-audit.md) against citation rot. // Every repo path it cites must still resolve, every symbol or test it reports as // landed must still be in the file it names, and the audited baseline must stay // pinned. The gaps it reports as missing are deliberately not asserted, so closing // a gap never breaks this test. const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); const audit = readFileSync(join(repoRoot, 'design/m2-master-audit.md'), 'utf8'); const designIndex = readFileSync(join(repoRoot, 'design/README.md'), 'utf8'); // Cited as gaps or future outputs, so they must not be required to exist. const CITED_AS_ABSENT = new Set([ 'scripts/export-notebook-snapshot.ts', 'design/m2-close-evidence.md', 'docs/', 'docs/*.md', 'design/*.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 repoRelative = spans.filter((span) => /^(apps|libs|tools|python|scripts|design|test|database|docs)\//.test(span) ); return [ ...new Set(repoRelative.map((span) => span.replace(/:[\d,-]+$/, '')).flatMap(expandBraces)), ] .filter((p) => !p.includes('*') || CITED_AS_ABSENT.has(p)) .sort(); } function fileContents(file: string): string { return readFileSync(join(repoRoot, file), 'utf8'); } describe('design/m2-master-audit.md citations', () => { test('cites only repo paths that exist, except gaps and future evidence files', () => { 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('paths cited as gaps are still absent, and specs live under design/', () => { expect(existsSync(join(repoRoot, 'docs'))).toBe(false); expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true); }); // [file, symbol or test reported as landed that must still exist in the file] // Gaps reported by the audit (such as `EventsDatasetExists` or the old `events/year=*/part.parquet` // glob) are intentionally omitted so closing those gaps does not break this citation guard. const symbolCitations: Array<[file: string, expected: string]> = [ ['tools/curate-etl/src/parquet_posts.rs', 'EVENT_KIND_POST'], ['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'], ['tools/curate-etl/src/run_curate_fundamentals.rs', 'pub struct CurateFundamentalsArgs'], ['tools/curate-etl/src/cli.rs', 'CurateBars1m('], ['tools/curate-etl/src/cli.rs', 'CurateQmBars1m('], ['tools/curate-etl/src/cli.rs', 'CurateFx1m('], ['tools/curate-etl/src/cli.rs', 'CuratePosts('], ['tools/curate-etl/src/cli.rs', 'CurateFundamentals('], ['tools/curate-etl/src/cli.rs', 'CurateMacro('], ['tools/curate-etl/src/cli.rs', 'SendIlp('], ['tools/curate-etl/src/cli.rs', 'CliAction::CuratePosts'], ['tools/curate-etl/src/cli.rs', 'CliAction::CurateFundamentals'], ['tools/curate-etl/src/cli.rs', 'CliAction::CurateMacro'], ['tools/curate-etl/src/cli.rs', 'CliAction::CurateBars1m'], ['tools/curate-etl/src/cli.rs', 'CliAction::CurateQmBars1m'], ['tools/curate-etl/src/cli.rs', 'CliAction::CurateFx1m'], ['tools/curate-etl/src/cli.rs', 'CliAction::SendIlp'], ['tools/curate-etl/src/main.rs', 'run_send_ilp'], ['tools/curate-etl/src/main.rs', 'run_curate_qm_bars_1m'], [ 'tools/curate-etl/src/fundamentals_tests.rs', 'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2', ], [ 'tools/curate-etl/src/parquet_fundamentals_tests.rs', 'fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm', ], [ 'tools/curate-etl/src/run_curate_bars_1m_tests.rs', 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes', ], ['tools/curate-etl/tests/cli.rs', 'fn send_ilp_cli_help_missing_flag_success_and_partial_error_routing'], ['tools/curate-etl/tests/cli.rs', 'TcpListener::bind("127.0.0.1:0")'], [ 'tools/curate-etl/tests/cli.rs', 'fn send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage', ], ['tools/curate-etl/tests/cli.rs', 'fn send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr'], [ 'tools/curate-etl/tests/curate_macro.rs', 'fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage', ], [ 'tools/curate-etl/tests/curate_macro.rs', 'fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel', ], ['tools/curate-etl/tests/curate_macro.rs', 'fn cli_rerun_on_same_inputs_is_byte_deterministic'], [ 'tools/curate-etl/tests/curate_qm_bars_1m.rs', 'fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants', ], [ 'tools/curate-etl/tests/curate_qm_bars_1m.rs', 'fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards', ], [ 'tools/curate-etl/tests/curate_qm_bars_1m.rs', 'fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped', ], ['tools/curate-etl/src/run_curate_fx_1m.rs', 'bar-start `ts`'], ['libs/data/questdb/src/schema.ts', 'fx_1m: {'], ['libs/data/questdb/src/schema.ts', 'export function getM2IntradayDDL'], ['libs/data/duckdb/src/research-copilot-store.ts', 'export const openResearchCopilotStore'], ['libs/data/duckdb/src/research-copilot-store.ts', 'vaultOperatorAuthorized: false'], ['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 'fundamentalsAsOf enforces restatement non-overwrite'], ['libs/research/src/market-data-store-duckdb.ts', "timeframe === '1m'"], ['libs/research/src/market-data-store-duckdb.ts', 'crossSection('], ['libs/research/src/market-data-store-duckdb.ts', 'async fundamentalsAsOf('], ['libs/research/src/market-data-store-duckdb.ts', 'macroAsOf('], ['libs/research/src/market-data-store-routed.ts', 'return daily.fx(q)'], ['libs/research/src/mcp/tools/analyze-signal.ts', 'discriminatedUnion'], ['libs/research/src/feature-library.ts', 'RET_1D_V1'], ['libs/research/src/feature-library.ts', 'export const FEATURE_INPUT_DATASETS'], ['libs/research/src/notebook-snapshot-node.ts', 'export function createNodeNotebookCommandRunner'], ['scripts/research-copilot-mcp.ts', 'export async function runResearchCopilotMcp'], ['package.json', '"mcp:research-copilot"'], ['design/MILESTONES.md', 'eodIntraday1M'], ['docker-compose.quant.yml', '1048576'], ]; test.each(symbolCitations)('%s contains %p as cited', (file, expected) => { expect(audit).toContain(file.split('/').pop()!); expect(fileContents(file)).toContain(expected); }); test('pins the audited master baseline and accepted M1 separately from the review branch', () => { expect(audit).toContain('d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52'); expect(audit).toContain('d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1'); expect(audit).toContain('git rev-parse master'); expect(audit).toMatch(/not `git rev-parse HEAD`/); }); test('maps every M2 deliverable and exit criterion to a Done/Partial/Missing status', () => { for (const row of ['M2.1', 'M2.2', 'M2.3', 'M2.4', 'EC-1', 'EC-2', 'EC-3']) { const line = audit.split('\n').find((l) => l.startsWith(`| **${row}`)); expect(line, row).toBeDefined(); expect(line!).toMatch(/\|\s*\*\*(Done|Partial|Missing)\b/); } }); test('keeps host and quant checks pending rather than claiming them passed', () => { expect(audit).toMatch(/\*\*PENDING \(host closure\)\*\*/); expect(audit).toMatch(/\*\*PENDING \(host\/`quant`\)\*\*/); expect(audit).toMatch(/\*\*Partial \(Synthetic Done; Live `quant` Missing\)\*\*/); }); test('lists the seven approved backlog keys in dependency order', () => { const keys = [ 'm2-ceo-posts-events-compat', 'm2-store-macro-cross-section-fx1m', 'm2-data-pipeline-m2-inputs-and-probes', 'm2-curate-etl-mongo-and-financials-old', 'm2-python-sdk-m2-parity', 'm2-ec1-snapshot-cli-and-doc-paths', 'm2-host-quant-verification-and-closure', ]; const section = audit.slice(audit.indexOf('## 5. Ordered M2 Closure Backlog')); const rows = section.split('\n').filter((l) => /^\| \*\*\d\*\* \|/.test(l)); expect(rows.map((r) => /`(m2-[a-z0-9-]+)`/.exec(r)?.[1])).toEqual(keys); rows.forEach((row, i) => { for (const dep of [...row.split('|')[4]!.matchAll(/`(m2-[a-z0-9-]+)`/g)].map((m) => m[1]!)) { expect(keys.indexOf(dep), `${keys[i]} depends on ${dep}`).toBeLessThan(i); } }); }); test('proposes no CI workflow and is indexed in design/README.md', () => { expect(audit).not.toMatch(/\.github\/workflows/); expect(designIndex).toContain('[m2-master-audit.md](m2-master-audit.md)'); }); });