Compare commits

...

10 commits

Author SHA1 Message Date
Studio
8e2bf1c7f2 T-208: Audit Milestone M2 gaps and exit criteria against master 2026-12-04 11:32:36 -05:00
Studio
f0c8a32512 T-208: tests 2026-12-04 11:28:48 -05:00
Studio
7e25d61edb T-208: Audit Milestone M2 gaps and exit criteria against master 2026-12-04 11:22:47 -05:00
Studio
efd73bda3b T-208: Audit Milestone M2 gaps and exit criteria against master 2026-12-04 11:14:11 -05:00
Studio
d45014a1f6 T-206: M2.3r — tools/curate-etl: curate-qm-bars-1m CLI command (file mode) wiring the existing run_curate_qm_bars_1m into cli.rs + main.rs with parser tests and a binary end-to-end test (no new crates, no bench changes, no live Mongo/QuestDB) 2026-12-04 10:17:13 -05:00
Studio
285c3ddf12 T-206: tests 2026-12-04 10:13:28 -05:00
Studio
618b2f7e59 T-206: edits made in the worktree 2026-12-04 10:04:38 -05:00
Studio
0b1dbcae3d T-206: M2.3r — tools/curate-etl: curate-qm-bars-1m CLI command (file mode) wiring the existing run_curate_qm_bars_1m into cli.rs + main.rs with parser tests and a binary end-to-end test (no new crates, no bench changes, no live Mongo/QuestDB) 2026-12-04 10:04:38 -05:00
Studio
a01a1171bd T-205: M2.1v (port to master) — Runnable stdio entrypoint for the MCP research copilot: scripts/research-copilot-mcp.ts + mcp:research-copilot package script, ported from studio/auto-db2c48b5 (T-196) onto master's existing factories (no new deps, no SSE, no lib rewrites) 2026-12-04 09:58:11 -05:00
Studio
ee61d3b7ae T-205: M2.1v (port to master) — Runnable stdio entrypoint for the MCP research copilot: scripts/research-copilot-mcp.ts + mcp:research-copilot package script, ported from studio/auto-db2c48b5 (T-196) onto master's existing factories (no new deps, no SSE, no lib rewrites) 2026-12-04 09:58:10 -05:00
10 changed files with 2392 additions and 1 deletions

View file

@ -14,7 +14,8 @@ Start here. Every document below has a single responsibility; historical sprint
| **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** | Canonical metric definitions, `trial_ledger` schema, effective-trials DSR ($\hat{N}$), CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, lifecycle gates, and Dual Live Drift + IB/TSX execution rules | Before touching `libs/calculations`, `libs/research`, validation workflows, or paper/live execution |
| **[servers.md](servers.md)** | Host roles (`quant` `12900K` research/data server, `9900K` isolated IB live/paper host, `TrueNAS` cold storage, dev workstation) and port/storage layout | Infrastructure, deployment, and worker sizing |
| **[data-pipeline/rust-migration-evaluation.md](data-pipeline/rust-migration-evaluation.md)** | Evidence-based evaluation of keeping `apps/stock/data-pipeline` in TypeScript vs. moving bulk MongoDB streaming or the full pipeline into Rust (`tools/curate-etl`) | Before `M2` adds PIT fundamentals, `ceoPosts`, or `bars_1m` QuestDB ingestion |
| **[m2-completion-audit.md](m2-completion-audit.md)** | Read-only Milestone `M2` completion audit, gate results & pending host checks, candidate Auto Mode parking causes, director decisions, and `M3` readiness mapping (`T-204`) | Before closing `M2`, queuing remaining `M2` tasks, or starting `M3` |
| **[m2-completion-audit.md](m2-completion-audit.md)** | Historical read-only Milestone `M2` completion audit prior to `T-205`–`T-207` (`T-204`; superseded by `m2-master-audit.md`) | Historical reference for pre-`T-205` M2 state |
| **[m2-master-audit.md](m2-master-audit.md)** | Current read-only Milestone `M2` audit against `master` (post-`T-205`/`T-206`/`T-207`), Done/Partial/Missing matrix, director trade-offs, and 7-task M2 closure backlog (`T-208`) | Before closing `M2`, queuing remaining `M2` tasks, or starting `M3` |
---

127
design/m2-master-audit.md Normal file
View file

@ -0,0 +1,127 @@
# Milestone M2 Master Audit & Closure Plan (T-208)
**Bottom Line:** **HOLD M2 CLOSURE / HOLD M3 — Core M2 infrastructure is ~80% landed on current `master` (including `T-190` `send-ilp`, `T-205` `mcp:research-copilot`, `T-206` `curate-qm-bars-1m`, and `T-207` `curate-macro`), with 6 concrete code/wiring gaps and 1 host/`quant` verification gate remaining before M2 can close.**
All sandbox-runnable TypeScript, ESLint, contract, and Rust native gates passed on local fixtures (including loopback TCP, with zero external network or QA DB contact; `0` errors, `0` warnings; `1,563` Rust tests across `58` suites and `1,050` targeted M2 Bun tests across `65` files). Exit Criterion 2 (2D PIT Q1-after-Q2 restatement non-overwrite) is **Done** in both Rust and real-DuckDB TypeScript fixtures; Exit Criteria 1 and 3 remain **Partial** pending event-kind/glob alignment, `MarketDataStore` read-path completions (`macroAsOf`, `crossSection`, `fx('1m')`), Python `stockbot` M2 parity, `notebook:snapshot` CLI + E2E test, and operator-run host/`quant` QuestDB `10.2.0` verification.
> **Scope, Provenance & Constraints**
> - **Read-only, docs-only audit:** Only `design/m2-master-audit.md` and `design/README.md` are modified. Zero production code, schema, test, build config, or CI changes (project CI is off; zero CI workflows proposed).
> - **Audited `master` baseline vs. review branch:** Audited against `master` and `dev` at verified commit `d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52` (with accepted M1 `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1` confirmed as an ancestor). The review branch is `feat/m2-audit` (prior review HEAD `efd73bda3b9937274be6a47663ac20010922cfbd`, superseded by this revision). When checking the audited baseline outside the sandbox, run `git rev-parse master` — not `git rev-parse HEAD` (which returns the `feat/m2-audit` documentation commit).
> - **Supersedes prior T-203/T-204 snapshots:** Unlike `design/m2-completion-audit.md` (T-204), current `master` (`d45014a1`) now includes `T-190` (`send-ilp`), `T-205` (`scripts/research-copilot-mcp.ts` + `"mcp:research-copilot"`), `T-206` (`curate-qm-bars-1m` CLI), and `T-207` (`curate-macro` CLI). Every status below was re-verified from current source files and test runs.
> - **Documentation path drift:** Canonical specs reside under `design/*.md`, while `AGENTS.md` (lines 43–48), `CLAUDE.md` (lines 3, 7–11), `README.md` (lines 7, 9, 11–13, 142, 264, 435), and `studio.config.json` (lines 46–54) still reference `docs/*.md`. Cleanup is queued in `m2-ec1-snapshot-cli-and-doc-paths`.
> - **Strict database safety:** Zero connections to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`).
---
## 1. Baseline Verification: M1 (`d52aa20`), `T-127` & Option B Rust Architecture
| Baseline Item | Verified State on `master` | Impact on M2 |
| --- | --- | --- |
| **Accepted M1 (`d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1`)** | Landed and intact: security-master & research SQL schemas (`database/postgres/init/34-security-master.sql`, `35-security-master-exchange-seed.sql`, `36-trial-ledger.sql`, `37-research-findings.sql`), Rust Option B `--from-mongo` runners for all 6 M1 commands (`tools/curate-etl/src/run_mongo.rs:1-100`, `mongo_stream.rs`, `mongo_safety.rs`), and Python `stockbot` M1 SDK (`python/stockbot/{__init__,calculations,data,ledger,signals,vault}.py`). | Solid foundation; M2 builds directly on these schemas, adapters, and `ReadOnlyMongoClient`. |
| **`T-127` (Deferred M1 Equity Eligibility & Vault File Isolation)** | Explicitly accepted as deferred in backlog per settled director decision (`d52aa20`). | **Non-blocking for M2.** Does not block EC-1, EC-2, or EC-3. |
| **Settled Rust ETL / `data-pipeline` Decision (Option B)** | Confirmed in `design/data-pipeline/rust-migration-evaluation.md` (including `2026-11-30` Addendum §§A.1–A.4): keep `apps/stock/data-pipeline` in TypeScript (`42` files, `20,349` LOC) for security master Passes 1–6, TSV export, probes, and BullMQ/Hono; keep bulk curation in Rust `tools/curate-etl` (`mongodb = "=3.10.2"` sync `RawDocumentBuf` cursors). | M2's 6 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`) still lack `--from-mongo` wiring in `tools/curate-etl/src/mongo_stream.rs:53-62` (currently 8 M1 collections only). |
| **Post-T-204 Merges (`T-190`, `T-205`, `T-206`, `T-207`)** | All four verified landed: `T-190` `send-ilp` (`tools/curate-etl/src/{ilp_send,cli,main}.rs`), `T-205` desktop MCP stdio entrypoint (`scripts/research-copilot-mcp.ts`, `package.json:56`, `scripts/test/research-copilot-mcp.test.ts`), `T-206` `curate-qm-bars-1m` (`tools/curate-etl/src/{run_curate_qm_bars_1m,cli,main}.rs`), and `T-207` `curate-macro` (`tools/curate-etl/src/{run_curate_macro,cli,main}.rs`). | Removes the T-204 desktop-launch and `curate-qm-bars-1m` CLI blockers. |
---
## 2. Verification Gate Evidence & Research Governance
### 2.1 Sandbox Local Fixture Runs (Programmer-Reported on `feat/m2-audit`, Including Loopback TCP — Zero External Network or QA DB Contact)
| Gate / Suite | Command | Exit | Observed Outcome & Counts |
| --- | --- | :---: | --- |
| **Typecheck** | `bun run typecheck` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.check.json --noEmit`) |
| **Contracts** | `bun run test:contracts` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.contracts.json --noEmit`) |
| **Lint** | `bun run lint:check` | `0` | **PASS** — `0` errors, `0` warnings (`--max-warnings 0`) |
| **Utils** | `bun run test:utils` | `0` | **PASS** — `32` pass, `0` fail (`59` expects, `3` files) |
| **Calculations** | `bun run test:calculations` | `0` | **PASS** — `144` pass, `0` fail (`76,602` expects, `12` files) |
| **Native Rust** | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PASS** — `1,563` passed, `0` failed, `4` ignored across `58` suites (`engine` `150` passed + `curate-etl` unit & integration suites using local fixtures, including loopback TCP in `tools/curate-etl/tests/cli.rs:1787` for `send-ilp`, plus binary tests in `curate_qm_bars_1m.rs` and `curate_macro.rs`, `fundamentals_tests.rs`, `parquet_fundamentals_tests.rs`, and `run_curate_bars_1m_tests.rs`) |
| **Targeted M2 Suites** | `bun test scripts/test/research-copilot-mcp.test.ts scripts/test/security.test.ts libs/research/test/ libs/data/duckdb/test/ libs/data/questdb/test/ libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts` | `0` | **PASS** — `1,050` pass, `0` fail (`80,699` expects, `65` files; includes `7/7` pass in `scripts/test/research-copilot-mcp.test.ts`, real-DuckDB `fundamentalsAsOf` restatement suite, and MCP Vault-fence suite) |
| **Python SDK** | `python3 -m pytest python/tests` | `1` | **SKIPPED (env)** — `/usr/bin/python3: No module named pytest` in sandbox |
### 2.2 Audited Baseline, Studio Unsandboxed & Host-Only Verification Boundary
| Verification Layer | Command / Scope | Status | Notes |
| --- | --- | :---: | --- |
| **Audited `master` Baseline Check** | `git rev-parse master` / `git rev-parse dev` | **Verified (`d45014a1`)** | Reviewer verified `master` and `dev` both at `d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52` with accepted M1 (`d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1`) as an ancestor; `feat/m2-audit` review HEAD is tracked separately. |
| **Studio Unsandboxed Runner (Audit Revision)** | `bun run build` and `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | **Authoritative post-handoff** | Prior revision passed Studio build `#1621` and test run `#1622`; Studio re-runs authoritatively on this revision covering workspace build, `audit:secrets`, worktree-git tooling tests (`scripts/test/`), integration tests, and isolated `stock_bot_safety*` PostgreSQL suites unreachable inside the sandbox. |
| **Future Host M2 Closure Revision** | `git rev-parse master` (at M2 closure), `CARGO_BUILD_JOBS=2 bun run check`, `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` | **PENDING (host closure)** | Future closure commit after M2 code tasks merge; required with retained logs in `design/m2-close-evidence.md` before M2 closure. |
| **`quant` (`10.0.0.51`) & Workstation Live Gates** | Read-only QA Mongo M2 field-shape probe, Quant Research-approved `curate-macro` `--series-map`, QuestDB `10.2.0` preflight (`vm.max_map_count`, `nofile`), bulk 3-feed intraday load + read-back reconciliation (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX`), `0x10` TCP ILP v2 commit, observed `NEXM.V`/`NVDA.US` split check, 1y `1m` PGWire latency, and desktop Claude Code + real `marimo` EC-1 receipt | **PENDING (host/`quant`)** | Tracked in `m2-host-quant-verification-and-closure` (with director replan flag in §4–§5). |
### 2.3 Research Governance & Replay / Financial Invariants Verified
- **Economic owner & durable inputs:** Quant data curation owns immutable Zstd Parquet partitions (`bars_1d`, `adj_factors`, `corporate_actions`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`, `macro`, `features/<name>/v<version>`) and published QuestDB ILP v2 shard files; Quant Research owns the `curate-macro` `--series-map` series and lag-class selections (the approved TSV and its identifier must be retained with macro curation evidence); PostgreSQL owns append-only `trial_ledger`, `vault_evaluations`, `findings`, and `provider_caveats` (`database/postgres/init/36-trial-ledger.sql`, `37-research-findings.sql`, protected by `reject_research_evidence_mutation()`).
- **Holdout Vault & `known_at` boundaries:** Verified by `libs/research/test/mcp-query-data.test.ts` (rejects `scope`/`vault_evaluation_only`, clamps bounds strictly `< vaultCutoffTs`, drops leaky post-cutoff rows) and `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:40`, hardcoding `vaultOperatorAuthorized: false`). **Open FX `1m` availability gap:** `tools/curate-etl/src/run_curate_fx_1m.rs:24-26` preserves bar-start `ts` and `libs/data/questdb/src/schema.ts:33-47` defines `fx_1m` without `known_at`, so filtering on `ts` alone can leak an unclosed bar's close across a cutoff (director confirmation required in §4).
- **Baselines & single-source metrics:** `@stock-bot/calculations` (`144/144` tests passing) remains the sole authority for Sharpe/Sortino/IC/Newey-West/DSR/event-study/recency math; `RET_1D_V1` in `libs/research/src/feature-library.ts:29` documents its zero-return comparison baseline and zero-cost assumption.
- **2D PIT restatement & synthetic split-boundary conservation:**
- Q1 restated after Q2 never overwrites Q2 and updates TTM: verified in Rust (`tools/curate-etl/src/fundamentals_tests.rs:104` `restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2`, `parquet_fundamentals_tests.rs:1107` `restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`).
- `NVDA.US` (`10:1`) and `NEXM.V` (`1:20`) split-unadjustment conservation within `0.5%`: verified on **synthetic** fixtures (`tools/curate-etl/src/run_curate_bars_1m_tests.rs:402` `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`); observed comparison against retained raw `bars_1d` closes remains open on `quant`.
- **Database safety & execution boundary:** Read-only MongoDB/PostgreSQL guards (`assertEnvironmentSafety()`, `MongoDBClient` `mongoReadOnly: true`, Rust `mongo_safety.rs` + sealed `ReadOnlyMongoClient`) remain intact. **Paper and live execution write access is strictly absent from all M2 MCP/research surfaces and remains out of scope until M5.**
---
## 3. Milestone M2 Deliverables & Exit Criteria Matrix
### 3.1 Deliverables (`design/MILESTONES.md` lines 87–98)
| Deliverable | Status | Landed on `master` (Exact Paths, Symbols & Tests) | Missing / Remaining Gaps |
| --- | :---: | --- | --- |
| **M2.1** MCP Server & Notebook Snapshots | **Partial** | - **T-205 landed:** Runnable stdio entrypoint `runResearchCopilotMcp` in `scripts/research-copilot-mcp.ts:77`, `"mcp:research-copilot"` in `package.json:56`, `7/7` tests in `scripts/test/research-copilot-mcp.test.ts`.<br>- All 6 MCP tools (`search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`) in `libs/research/src/mcp/tools/` + `createResearchCopilotMcpServer` (`libs/research/src/mcp/copilot-server.ts`) + `parseResearchCopilotHostConfig` / `runResearchCopilotStdioHost` (`libs/research/src/mcp/host/stdio-host.ts`).<br>- Real Postgres executor (`openResearchCopilotExecutor` in `libs/data/postgres/src/research-copilot-executor.ts`) + real DuckDB store (`openResearchCopilotStore` in `libs/data/duckdb/src/research-copilot-store.ts:33`) + read-only `library.yml` card reader (`libs/research/src/mcp/adapters/library-cards.ts`) + `database/postgres/init/37-research-findings.sql`.<br>- `exportNotebookSnapshot` & Node subprocess adapter (`libs/research/src/notebook-snapshot.ts`, `libs/research/src/notebook-snapshot-node.ts:67`, `libs/research/test/notebook-snapshot*.test.ts`). | 1. `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:37`) and `stdio-host.ts:49-79` open DuckDB-only; optional `RESEARCH_MCP_QUESTDB_*` config + `createRoutedMarketDataStore` composition is missing.<br>2. `analyze_signal` (`libs/research/src/mcp/tools/analyze-signal.ts:121-123`) supports only `source: 'shorts' \| 'fundamentals'` (no `source: 'feature'` for versioned Feature Library signals).<br>3. No runnable `scripts/export-notebook-snapshot.ts` / `"notebook:snapshot"` CLI wrapping `@stock-bot/research/notebook-snapshot-node`.<br>4. No automated E2E stdio test covering `search_symbols` → `query_data` → `analyze_signal` → `event_study` (with `ceo_post`) → `exportNotebookSnapshot` → `file_finding` → `read_knowledge`.<br>5. No `apps/stock/web-api` SSE wrapper (recommended deferred to M4; see §4). |
| **M2.2** PIT Fundamentals, `ceoPosts` & Lagged `teData` | **Partial** | - File-mode Rust CLIs wired in `tools/curate-etl/src/cli.rs` & `main.rs`: `curate-fundamentals` (`cli.rs:102,1636`, `run_curate_fundamentals.rs`), `curate-posts` (`cli.rs:101,1317`, `run_curate_posts.rs`), and **T-207** `curate-macro` (`cli.rs:103,1689`, `run_curate_macro.rs`; binary tests in `tools/curate-etl/tests/curate_macro.rs:178` `cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage`, `:471` `cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel`, `:709` `cli_rerun_on_same_inputs_is_byte_deterministic`).<br>- Real-DuckDB `fundamentalsAsOf` (`libs/research/src/market-data-store-duckdb.ts:2287`, `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`).<br>- 2D PIT restatement tests (`fundamentals_tests.rs:104`, `parquet_fundamentals_tests.rs:1107`). | 1. **`ceoPosts` event-kind & partition mismatch:** `EVENT_KIND_POST = "post"` (`tools/curate-etl/src/parquet_posts.rs:22`) mismatches `'ceo_post'` expected by `market-data-store-duckdb.ts` and `python/stockbot/data.py:21`; `run_curate_posts.rs:133` fails with `EventsDatasetExists` when `<out>/events` exists from `curate-events`; both `market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` glob only `events/year=*/part.parquet` instead of `events/year=*/*.parquet`.<br>2. `MarketDataStore.macroAsOf` throws `MarketDataStoreNotImplementedError` (`libs/research/src/market-data-store-duckdb.ts:2294-2296`).<br>3. `CurateFundamentalsArgs` (`tools/curate-etl/src/run_curate_fundamentals.rs:113-118`) accepts only a single `--qm-financials` path (no `--qm-financials-old` merge or `--curate-inputs` resolution).<br>4. `export-curate-inputs.ts:20-24` does not emit `listing_venues.tsv` (`us_tsx` / `tsxv_cse`).<br>5. `SourceCollection` (`mongo_stream.rs:53-62`), `RAW_BSON_EXPORT_COLLECTIONS` (`export-raw-bson.ts:11-20`), and `FIELD_SHAPE_PROBE_COLLECTIONS` (`source-field-shapes.ts:8-17`) allowlist only the 8 M1 collections (missing `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`).<br>6. `python/stockbot/data.py` lacks `fundamentals_as_of` and `macro_as_of`. |
| **M2.3** QuestDB `10.2.0` Intraday & `send-ilp` | **Partial** | - **T-190 landed:** `send-ilp` multi-socket TCP sender (`tools/curate-etl/src/ilp_send.rs`, `cli.rs:104,2461`, `main.rs:22`, `ilp_send_tests.rs`; binary tests in `tools/curate-etl/tests/cli.rs:1747` `send_ilp_cli_help_missing_flag_success_and_partial_error_routing`, `:1877` `send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage`, `:1939` `send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr`).<br>- **T-206 landed:** `curate-qm-bars-1m` CLI (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`, `cli.rs:99,2277`, `main.rs:39`; binary tests in `tools/curate-etl/tests/curate_qm_bars_1m.rs:336` `curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants`, `:527` `curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards`, `:622` `curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped`) alongside `curate-bars-1m` (`cli.rs:98,2110`) and `curate-fx-1m` (`cli.rs:100,2381`).<br>- QuestDB `10.2.0` query layer, ILP v2 writer, and opt-in `M2_INTRADAY_SCHEMAS` / `getM2IntradayDDL()` (`libs/data/questdb/src/schema.ts:13-63,139`, `libs/data/questdb/test/`).<br>- Vault-fenced QuestDB `bars('1m')` reader (`libs/research/src/market-data-store-questdb.ts`) + `createRoutedMarketDataStore` (`libs/research/src/market-data-store-routed.ts`).<br>- `docker-compose.quant.yml:30-45` (`nofile: 1048576`, `QDB_RAM_USAGE_LIMIT_BYTES=21474836480`, `mem_limit: 28g`). | 1. `fx({ timeframe: '1m' })` throws `MarketDataStoreNotImplementedError` in TS (`libs/research/src/market-data-store-duckdb.ts:1529-1534`, delegated unchanged by `market-data-store-routed.ts:184-186`) and `NotImplementedError` in Python (`python/stockbot/data.py:258-259`); `market-data-store-questdb.ts` reads `bars_1m` only (no `fx_1m` reader). Moreover, `run_curate_fx_1m.rs:24-26` preserves bar-start `ts` and `fx_1m` (`schema.ts:33-47`) has no `known_at` column, so Vault fencing for both FX adapters requires a confirmed bar-close availability rule (see §4).<br>2. `getM2IntradayDDL()` (`libs/data/questdb/src/schema.ts:139`) is pure/opt-in with no runnable initializer script/helper wired to apply it.<br>3. No `--from-mongo` streaming in `mongo_stream.rs` / `run_mongo.rs` (and no allowlist entries in `export-raw-bson.ts` / `source-field-shapes.ts`) for `eodIntraday1M` (`3.40B`) or `qmIntraday` (`173.3M`).<br>4. Live `quant` preflight (`vm.max_map_count`, `nofile`), `0x10` binary-double TCP ILP acceptance (`ilp_send.rs:15-21`), bulk load & PGWire read-back reconciliation of all three approved feeds (`eodIntraday1M` US 2003–2025, `qmIntraday` CA/US 2024–2025, `CAD.FOREX` `1m` ~5.2M bars, including EOD/QM `(ts, listing_id)` overlap reconciliation), observed `NEXM.V`/`NVDA.US` split check, and 1y `1m` PGWire latency benchmark are unverified. |
| **M2.4** Versioned Feature Library (`D04` / `D11`) | **Partial** | - Declarative DuckDB SQL feature definitions, immutable `registerSignal`, Vault-fenced yearly Zstd Parquet `runFeatureBatch`, and built-in `RET_1D_V1` in `libs/research/src/feature-library.ts` (`libs/research/test/feature-library.test.ts`). | 1. `MarketDataStore.crossSection` throws `MarketDataStoreNotImplementedError` (`libs/research/src/market-data-store-duckdb.ts:2283-2285`), blocking read-back of `features/<name>/v<version>/year=*/part.parquet`.<br>2. `FEATURE_INPUT_DATASETS` (`libs/research/src/feature-library.ts:61-68`) omits `'macro'` and `'corporate_actions'`.<br>3. Python `stockbot` (`python/stockbot/{__init__,data,signals}.py`) lacks `register_signal(...)`, batch feature materialization, and `cross_section(...)`. |
### 3.2 Exit Criteria (`design/MILESTONES.md` lines 100–103)
| Exit Criterion | Status | Verified Evidence & Remaining Work |
| --- | :---: | --- |
| **EC-1:** Desktop Claude Code via MCP executes a fundamental + alt-data signal study and event study end-to-end, exports a `marimo check`-clean static HTML snapshot, and files a finding. | **Partial** | **Landed:** `scripts/research-copilot-mcp.ts` (`mcp:research-copilot`) + all 6 MCP tools + `exportNotebookSnapshot`.<br>**Missing:** `ceo_post` event compatibility (`m2-ceo-posts-events-compat`), `notebook:snapshot` CLI + automated E2E stdio test (`m2-ec1-snapshot-cli-and-doc-paths`), and desktop Claude Code + real `marimo` session receipt (`m2-host-quant-verification-and-closure`). |
| **EC-2:** Restatement fixture test proves a restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`. | **Done (Offline Rust + Real-DuckDB)** | Proven offline in `tools/curate-etl/src/fundamentals_tests.rs:104`, `tools/curate-etl/src/parquet_fundamentals_tests.rs:1107`, and real-DuckDB `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`. Python `fundamentals_as_of` parity is tracked in `m2-python-sdk-m2-parity`. |
| **EC-3:** Split-boundary test on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirms `bars_1m` session closes match raw `bars_1d` closes within `0.5%`, and 1y of `1m` bars for one listing loads in `< 250 ms` warm / `< 1 s` cold. | **Partial (Synthetic Done; Live `quant` Missing)** | **Done (synthetic):** `tools/curate-etl/src/run_curate_bars_1m_tests.rs:402` (`split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`).<br>**Missing (live `quant`):** Host/container `vm.max_map_count`/`nofile` preflight, `getM2IntradayDDL()` execution, QuestDB `10.2.0` `0x10` TCP ILP v2 commit check, bulk 3-feed load & PGWire read-back reconciliation (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX` + EOD/QM `(ts, listing_id)` overlap rule), observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` close check (`<= 0.5%`), and pinned 1-year single-listing PGWire latency benchmark (`< 250 ms` warm / `< 1 s` cold). |
---
## 4. Concrete Blockers, Director Trade-Offs & Backlog Replan Flags
Confirm these seven items (4 design trade-offs + 3 operational/environment prerequisites) and the **three backlog replan adjustments** below before coding/closing M2:
### 4.1 Design Trade-Offs Requiring Director Confirmation
1. **Option B `--from-mongo` for the 6 M2 collections vs. `.bson` staging:** Extend `tools/curate-etl` `SourceCollection` + `run_mongo.rs` with direct read-only MongoDB streaming for `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, and `qmIntraday`, or stay on `.bson` staging files for M2?
- *Recommended:* Extend Option B `--from-mongo` to all 6 M2 collections (`m2-curate-etl-mongo-and-financials-old`) so `3.40B` `eodIntraday1M` rows never require `~500–832 GiB` of NVMe scratch space, while keeping file mode for offline tests.
2. **MCP stdio-only for M2 vs. `web-api` SSE wrapper:** Close M2 with the landed desktop stdio server (`bun run mcp:research-copilot`), or also add an HTTP/SSE wrapper inside `apps/stock/web-api` now?
- *Recommended:* Keep M2 stdio-only for desktop Claude Code (EC-1) and defer the network-isolated HTTP/SSE MCP endpoint to M4 containerized campaigns.
3. **`fundamentals_pit`-only vs. physical `fundamentals_bitemporal/part.parquet`:** Keep `curate-fundamentals` writing pre-resolved 2D PIT snapshots (`fundamentals_pit/year=YYYY/part.parquet`), or also materialize a separate raw `fundamentals_bitemporal/part.parquet` table in M2?
- *Recommended:* Keep `fundamentals_pit`-only for M2 (`DATA-CONTRACTS.md` §3A and EC-2 both target `fundamentalsAsOf` over `fundamentals_pit`), and materialize `fundamentals_bitemporal` only if a downstream M3/M4 use case requires unflattened multi-period history.
4. **`fx_1m` bar-close availability & Vault fencing rule *(Unresolved — blocks both TS & Python FX adapters)*:** `tools/curate-etl/src/run_curate_fx_1m.rs:24-26` preserves EODHD bar-start `ts` and `libs/data/questdb/src/schema.ts:33-47` defines `fx_1m` without a `known_at` column. Filtering on `ts` alone can return a bar whose start is before `vaultCutoffTs` (or `asOf`) while its close is at or after the cutoff, leaking an unobservable FX close.
- *Recommended:* Enforce bar-close availability in both TypeScript (`m2-store-macro-cross-section-fx1m`) and Python (`m2-python-sdk-m2-parity`) FX adapters (`bar_close = ts + 60s` strictly `< vaultCutoffTs` and `<= asOf`), backed by a boundary fixture proving a bar spanning or ending at `vaultCutoffTs` is excluded — keeping the `fx_1m` schema unchanged. (Alternative: add a `known_at` `TIMESTAMP` column to `fx_1m` DDL + ILP writer set to `ts + 60s`.)
### 4.2 Operational & Environment Prerequisites
5. **Live read-only QA MongoDB M2 field-shape probe & `curate-macro` `--series-map` ownership:** Run `probe-source-field-shapes.ts` read-only (`studio_stock_bot_read@stock`) once `m2-data-pipeline-m2-inputs-and-probes` allowlists the 6 M2 collections, to confirm live `ceoPosts` numeric timestamp unit (`Seconds` vs `Millis`), `qmFinancials`/`qmFinancials-old` metric paths, and `teData` labels before production curation. **Quant Research** owns the `teData` series selection and lag-class choices in the caller-supplied `--series-map` TSV; retain the approved mapping TSV and its version/hash identifier alongside the macro curation evidence in `design/m2-close-evidence.md`.
6. **`quant` (`10.0.0.51`) QuestDB `10.2.0` operator access:** Required for sysctl (`vm.max_map_count >= 1048576`) & container `nofile = 1048576` preflight, applying `getM2IntradayDDL()`, verifying `0x10` binary-double TCP ILP v2 commits via PGWire `wal_tables()`, loading and reconciling all three approved intraday feeds (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX`), running the observed `NEXM.V`/`NVDA.US` split check, and timing the 1-year `1m` PGWire latency gate.
7. **Workstation `marimo` + desktop Claude Code setup:** Required on the operator workstation with `bun run mcp:research-copilot`, Studio `library.yml`, real `marimo`, and isolated PostgreSQL to record the EC-1 sign-off receipt.
### 4.3 Substantive Backlog Replan Flags for Director (Before Merging Follow-Ups)
The approved 7-key implementation backlog has three gaps discovered during audit review that should be replanned within the existing keys before scheduling:
- **`m2-store-macro-cross-section-fx1m` & `m2-python-sdk-m2-parity` (FX `1m` availability boundary):** Add the confirmed `fx_1m` bar-close availability rule (item 4 above) and a boundary fixture in both TS and Python tests verifying bar-close observability and Vault exclusion for a minute bar spanning or ending at `vaultCutoffTs`.
- **`m2-ec1-snapshot-cli-and-doc-paths` (missing prerequisite):** Add `m2-ceo-posts-events-compat` to `dependsOn` (currently only `m2-store-macro-cross-section-fx1m`). Without it, the EC-1 integration task can start before `curate-posts` emits `'ceo_post'` and co-publishes alongside `curate-events`; require the E2E stdio test to consume co-published `curate-events` + `curate-posts` fixture output so `event_study` proves it reaches the curated CEO post.
- **`m2-host-quant-verification-and-closure` (bulk 3-feed intraday coverage & reconciliation):** Add acceptance requiring retained bulk load and PGWire read-back evidence in QuestDB for all three approved feeds from `design/MILESTONES.md:96` — `eodIntraday1M` (US equity 2003–2025), `qmIntraday` (CA/US equity 2024–2025), and `CAD.FOREX` `1m` (~5.2M bars) — recording source/date coverage, row counts, skipped/dropped counts, and the explicit reconciliation/precedence rule where EOD and QM share a `(ts, listing_id)` dedup key in `bars_1m`.
---
## 5. Ordered M2 Closure Backlog (7 Tasks)
Aligned 1-to-1 with the approved implementation backlog keys (with the three director replan flags marked inline):
| Order | Key | Task | Depends On | Primary Acceptance |
| :---: | --- | --- | --- | --- |
| **1** | `m2-ceo-posts-events-compat` | **M2.2u** — Fix `ceoPosts` event kind (`'ceo_post'`) and co-publish under `<curatedRoot>/events` | *(none)* | `EVENT_KIND_POST = "ceo_post"`; non-clobbering `events/year=YYYY/part-posts.parquet`; TS (`market-data-store-duckdb.ts`) & Python (`data.py`) glob `events/year=*/*.parquet` verified in real-DuckDB combined filing/earnings/`ceo_post` test. |
| **2** | `m2-store-macro-cross-section-fx1m` | **M2.3s** — Implement `MarketDataStore.macroAsOf`, `crossSection`, QuestDB `fx('1m')`, and copilot `1m` routing | *(none)* | Vault-fenced DuckDB `macroAsOf` & `crossSection` tests; QuestDB `fx_1m` reader + `createRoutedMarketDataStore` `fx('1m')` routing + `getM2IntradayDDL()` initializer; optional `RESEARCH_MCP_QUESTDB_*` in `stdio-host.ts`/`openResearchCopilotStore`; `analyze_signal` `source: 'feature'` + `FEATURE_INPUT_DATASETS` (`'macro'`, `'corporate_actions'`). **[Director replan §4.3: confirm `fx_1m` bar-close availability rule + add cutoff-spanning/ending boundary fixture.]** |
| **3** | `m2-data-pipeline-m2-inputs-and-probes` | **M2.2v** — Export `listing_venues.tsv` and extend field-shape probe & BSON fixture exporter for M2 collections | *(none)* | Atomic `listing_venues.tsv` (`us_tsx` / `tsxv_cse`) in `export-curate-inputs.ts`; all 14 M1+M2 collections allowlisted in `source-field-shapes.ts` & `export-raw-bson.ts` with `mongoReadOnly: true`. |
| **4** | `m2-curate-etl-mongo-and-financials-old` | **M2.3t** — Add `--qm-financials-old` merge and Option B `--from-mongo` streaming for M2 collections in `curate-etl` | `m2-ceo-posts-events-compat`, `m2-data-pipeline-m2-inputs-and-probes` | `curate-fundamentals` `--qm-financials-old` + `--curate-inputs`; sealed read-only `--from-mongo` streaming for all 6 M2 collections with byte-identical offline parity tests and zero new crates. |
| **5** | `m2-python-sdk-m2-parity` | **M2.4b** — Add Python `stockbot` `register_signal`, batch feature runner, and M2 `MarketDataStore` methods | `m2-ceo-posts-events-compat`, `m2-store-macro-cross-section-fx1m` | Vault-fenced `fundamentals_as_of`, `macro_as_of`, `cross_section`, optional QuestDB `1m` `bars`/`fx`, and `register_signal(...)` writing contract Zstd Parquet readable identically by TS and Python. **[Director replan §4.3: enforce confirmed `fx_1m` bar-close availability rule + cutoff-spanning/ending boundary fixture.]** |
| **6** | `m2-ec1-snapshot-cli-and-doc-paths` | **M2.1w** — Add notebook snapshot CLI, MCP E2E study+snapshot+finding test, and fix `docs/` → `design/` path drift | `m2-store-macro-cross-section-fx1m`, **`m2-ceo-posts-events-compat` *(replan §4.3)*** | Fail-closed `scripts/export-notebook-snapshot.ts` (`"notebook:snapshot"`); E2E stdio MCP test (`search_symbols` → `file_finding` + snapshot) consuming **co-published `curate-events` + `curate-posts` fixture output** so `event_study` reaches the curated `ceo_post`; `docs/*.md` → `design/*.md` updated in `AGENTS.md`, `CLAUDE.md`, `README.md`, `studio.config.json`, `tools/curate-etl/README.md`. |
| **7** | `m2-host-quant-verification-and-closure` | **M2.5** — Execute host/`quant` M2 preflight, bulk 3-feed intraday load, observed split-boundary & latency checks, and desktop Claude Code EC-1 sign-off | `m2-curate-etl-mongo-and-financials-old`, `m2-python-sdk-m2-parity`, `m2-ec1-snapshot-cli-and-doc-paths` | Retained host `git rev-parse master`, `CARGO_BUILD_JOBS=2 bun run check` + `test/postgres/` + live read-only M2 probe + Quant Research-approved `curate-macro` `--series-map` TSV/ID + `quant` QuestDB `10.2.0` preflight/`0x10` ILP/observed `NEXM.V` & `NVDA.US` split/latency checks + desktop Claude Code EC-1 receipt in `design/m2-close-evidence.md`, marking M2 closed in `design/MILESTONES.md`. **[Director replan §4.3: require retained bulk load + PGWire read-back reconciliation for EOD equity, QM equity, and `CAD.FOREX` FX — source/date coverage, row counts, skips, and EOD/QM `(ts, listing_id)` overlap precedence rule.]** |

View file

@ -53,6 +53,7 @@
"clean:fresh:force": "./scripts/clean.sh --fresh --force",
"backtest": "turbo run backtest",
"benchmark:dataset": "bun run scripts/benchmark-dataset.ts",
"mcp:research-copilot": "bun run scripts/research-copilot-mcp.ts",
"docker:start": "./scripts/docker.sh start --dev",
"docker:stop": "./scripts/docker.sh stop --dev",
"docker:restart": "./scripts/docker.sh restart --dev",

View file

@ -0,0 +1,112 @@
/**
* Runnable stdio entrypoint for the headless MCP research copilot server.
*
* Parses `RESEARCH_MCP_*` environment variables, composes the Vault-fenced
* PostgreSQL executor, DuckDB market data store, and read-only library card
* reader, and serves newline-delimited JSON-RPC 2.0 over stdio.
*
* Fail-closed: configuration or host errors write a single fixed line to
* stderr and exit with code 1 without exposing DSNs, passwords, or raw error
* objects. Stdout carries only MCP protocol bytes.
*/
import { randomUUID } from 'node:crypto';
import {
type LibraryCardReaderHandle,
type ManagedMarketDataStore,
type ManagedPostgresExecutor,
type ResearchCopilotHostConfig,
type ResearchCopilotStdioHostDeps,
type StdioInput,
type StdioOutput,
createLibraryCardReader,
createNodeLibraryCardFs,
parseResearchCopilotHostConfig,
runResearchCopilotStdioHost,
} from '@stock-bot/research/mcp';
export const RESEARCH_COPILOT_CONFIG_ERROR_LINE =
'Research copilot MCP server failed: invalid RESEARCH_MCP_* configuration.\n';
export const RESEARCH_COPILOT_HOST_ERROR_LINE =
'Research copilot MCP server failed while running stdio host.\n';
export interface ResearchCopilotStderr {
write(chunk: string): boolean;
}
export interface ResearchCopilotMcpDeps {
readonly env?: Readonly<Record<string, string | undefined>>;
readonly input?: StdioInput;
readonly output?: StdioOutput;
readonly stderr?: ResearchCopilotStderr;
readonly openExecutor?: ResearchCopilotStdioHostDeps['openExecutor'];
readonly openStore?: ResearchCopilotStdioHostDeps['openStore'];
readonly createLibraryCardReader?: ResearchCopilotStdioHostDeps['createLibraryCardReader'];
readonly newId?: () => string;
readonly now?: () => Date | number;
}
async function defaultOpenExecutor(
config: ResearchCopilotHostConfig
): Promise<ManagedPostgresExecutor> {
const { openResearchCopilotExecutor } = await import(
'../libs/data/postgres/src/research-copilot-executor'
);
return openResearchCopilotExecutor(config);
}
async function defaultOpenStore(
config: ResearchCopilotHostConfig
): Promise<ManagedMarketDataStore> {
const { openResearchCopilotStore } = await import(
'../libs/data/duckdb/src/research-copilot-store'
);
return openResearchCopilotStore(config);
}
function defaultCreateLibraryCardReader(
config: ResearchCopilotHostConfig
): LibraryCardReaderHandle {
return createLibraryCardReader({
root: config.libraryRoot,
fs: createNodeLibraryCardFs(),
});
}
export async function runResearchCopilotMcp(
deps: ResearchCopilotMcpDeps = {}
): Promise<number> {
const stderr = deps.stderr ?? process.stderr;
let config: ResearchCopilotHostConfig;
try {
config = parseResearchCopilotHostConfig(deps.env ?? process.env);
} catch {
stderr.write(RESEARCH_COPILOT_CONFIG_ERROR_LINE);
return 1;
}
try {
await runResearchCopilotStdioHost({
config,
openExecutor: deps.openExecutor ?? defaultOpenExecutor,
openStore: deps.openStore ?? defaultOpenStore,
createLibraryCardReader: deps.createLibraryCardReader ?? defaultCreateLibraryCardReader,
newId: deps.newId ?? randomUUID,
now: deps.now ?? Date.now,
stdio: {
input: deps.input ?? process.stdin,
output: deps.output ?? process.stdout,
},
});
return 0;
} catch {
stderr.write(RESEARCH_COPILOT_HOST_ERROR_LINE);
return 1;
}
}
if (import.meta.main) {
process.exitCode = await runResearchCopilotMcp();
}

View file

@ -0,0 +1,208 @@
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 lineAt(file: string, line: number): string {
return readFileSync(join(repoRoot, file), 'utf8').split('\n')[line - 1] ?? '';
}
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, 1-based line the audit cites, text that line must contain]
const lineCitations: Array<[file: string, line: number, expected: string]> = [
['tools/curate-etl/src/parquet_posts.rs', 22, 'EVENT_KIND_POST'],
['tools/curate-etl/src/run_curate_posts.rs', 133, 'EventsDatasetExists'],
['tools/curate-etl/src/mongo_stream.rs', 53, 'pub enum SourceCollection'],
['tools/curate-etl/src/run_curate_fundamentals.rs', 113, 'pub struct CurateFundamentalsArgs'],
['tools/curate-etl/src/cli.rs', 98, 'CurateBars1m('],
['tools/curate-etl/src/cli.rs', 99, 'CurateQmBars1m('],
['tools/curate-etl/src/cli.rs', 100, 'CurateFx1m('],
['tools/curate-etl/src/cli.rs', 101, 'CuratePosts('],
['tools/curate-etl/src/cli.rs', 102, 'CurateFundamentals('],
['tools/curate-etl/src/cli.rs', 103, 'CurateMacro('],
['tools/curate-etl/src/cli.rs', 104, 'SendIlp('],
['tools/curate-etl/src/cli.rs', 1317, 'CliAction::CuratePosts'],
['tools/curate-etl/src/cli.rs', 1636, 'CliAction::CurateFundamentals'],
['tools/curate-etl/src/cli.rs', 1689, 'CliAction::CurateMacro'],
['tools/curate-etl/src/cli.rs', 2110, 'CliAction::CurateBars1m'],
['tools/curate-etl/src/cli.rs', 2277, 'CliAction::CurateQmBars1m'],
['tools/curate-etl/src/cli.rs', 2381, 'CliAction::CurateFx1m'],
['tools/curate-etl/src/cli.rs', 2461, 'CliAction::SendIlp'],
['tools/curate-etl/src/main.rs', 22, 'run_send_ilp'],
['tools/curate-etl/src/main.rs', 39, 'run_curate_qm_bars_1m'],
[
'tools/curate-etl/src/fundamentals_tests.rs',
104,
'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2',
],
[
'tools/curate-etl/src/parquet_fundamentals_tests.rs',
1107,
'fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm',
],
[
'tools/curate-etl/src/run_curate_bars_1m_tests.rs',
402,
'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes',
],
['tools/curate-etl/tests/cli.rs', 1747, 'fn send_ilp_cli_help_missing_flag_success_and_partial_error_routing'],
['tools/curate-etl/tests/cli.rs', 1787, 'TcpListener::bind("127.0.0.1:0")'],
[
'tools/curate-etl/tests/cli.rs',
1877,
'fn send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage',
],
['tools/curate-etl/tests/cli.rs', 1939, 'fn send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr'],
[
'tools/curate-etl/tests/curate_macro.rs',
178,
'fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage',
],
[
'tools/curate-etl/tests/curate_macro.rs',
471,
'fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel',
],
['tools/curate-etl/tests/curate_macro.rs', 709, 'fn cli_rerun_on_same_inputs_is_byte_deterministic'],
[
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
336,
'fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants',
],
[
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
527,
'fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards',
],
[
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
622,
'fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped',
],
['tools/curate-etl/src/run_curate_fx_1m.rs', 24, 'bar-start `ts`'],
['libs/data/questdb/src/schema.ts', 33, 'fx_1m: {'],
['libs/data/questdb/src/schema.ts', 139, 'export function getM2IntradayDDL'],
['libs/data/duckdb/src/research-copilot-store.ts', 33, 'export const openResearchCopilotStore'],
['libs/data/duckdb/src/research-copilot-store.ts', 40, 'vaultOperatorAuthorized: false'],
['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 251, 'fundamentalsAsOf enforces restatement non-overwrite'],
['libs/research/src/market-data-store-duckdb.ts', 1448, "'events/year=*/part.parquet'"],
['libs/research/src/market-data-store-duckdb.ts', 1529, "timeframe === '1m'"],
['libs/research/src/market-data-store-duckdb.ts', 2283, 'crossSection('],
['libs/research/src/market-data-store-duckdb.ts', 2287, 'async fundamentalsAsOf('],
['libs/research/src/market-data-store-duckdb.ts', 2294, 'macroAsOf('],
['libs/research/src/market-data-store-routed.ts', 185, 'return daily.fx(q)'],
['libs/research/src/mcp/tools/analyze-signal.ts', 122, 'discriminatedUnion'],
['libs/research/src/feature-library.ts', 29, 'RET_1D_V1'],
['libs/research/src/feature-library.ts', 61, 'export const FEATURE_INPUT_DATASETS'],
['libs/research/src/notebook-snapshot-node.ts', 67, 'export function createNodeNotebookCommandRunner'],
['scripts/research-copilot-mcp.ts', 77, 'export async function runResearchCopilotMcp'],
['python/stockbot/data.py', 21, '"ceo_post"'],
['python/stockbot/data.py', 71, 'events/year=*/part.parquet'],
['python/stockbot/data.py', 259, 'NotImplementedError'],
['package.json', 56, '"mcp:research-copilot"'],
['design/MILESTONES.md', 96, 'eodIntraday1M'],
['docker-compose.quant.yml', 35, '1048576'],
];
test.each(lineCitations)('%s:%d contains %p as cited', (file, line, expected) => {
expect(audit).toContain(file.split('/').pop()!);
expect(lineAt(file, line)).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)');
});
});

View file

@ -0,0 +1,332 @@
import { describe, expect, test } from 'bun:test';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store';
import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb';
import {
type LibraryCardReaderHandle,
MCP_PROTOCOL_VERSION,
type PostgresResearchCopilotExecutor,
type ReadKnowledgeResultPayload,
RESEARCH_COPILOT_TOOL_NAMES,
type StdioInput,
type StdioOutput,
} from '@stock-bot/research/mcp';
import {
RESEARCH_COPILOT_HOST_ERROR_LINE,
runResearchCopilotMcp,
} from '../research-copilot-mcp';
const FAKE_PASSWORD = 's3cr@t-default-pw#42';
const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_PASSWORD);
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z';
const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0);
function createMemoryWriter(): {
readonly stream: StdioOutput;
text(): string;
} {
const chunks: string[] = [];
return {
stream: {
write(chunk: string): boolean {
chunks.push(chunk);
return true;
},
},
text: () => chunks.join(''),
};
}
function createMemoryInput(lines: readonly string[]): StdioInput {
return {
async *[Symbol.asyncIterator](): AsyncIterator<string> {
for (const line of lines) {
yield `${line}\n`;
}
},
};
}
function createFakeExecutor(): PostgresResearchCopilotExecutor {
return {
async query<Row = Record<string, unknown>>(): Promise<{ readonly rows: readonly Row[] }> {
return { rows: [] };
},
};
}
function createFakeStore(): MarketDataStore {
return {
async *bars(q: BarQuery): AsyncIterable<BarBatch> {
yield {
listingId: q.listingIds[0] ?? 0,
timeframe: q.timeframe,
rows: [],
};
},
async crossSection() {
throw new MarketDataStoreNotImplementedError('crossSection');
},
async fundamentalsAsOf() {
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
},
async events() {
throw new MarketDataStoreNotImplementedError('events');
},
async shortsAsOf() {
throw new MarketDataStoreNotImplementedError('shortsAsOf');
},
async macroAsOf() {
throw new MarketDataStoreNotImplementedError('macroAsOf');
},
async fx() {
throw new MarketDataStoreNotImplementedError('fx');
},
async universe() {
return [];
},
};
}
function createFakeLibraryReader(): LibraryCardReaderHandle {
return {
async listLibraryCards() {
return [];
},
};
}
describe('scripts/research-copilot-mcp.ts default factory wiring', () => {
test('default createLibraryCardReader resolves master createLibraryCardReader + createNodeLibraryCardFs over a temp dir', async () => {
const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-mcp-lib-'));
try {
await mkdir(join(tempDir, 'cards', 'quant'), { recursive: true });
await writeFile(
join(tempDir, 'library.yml'),
'id: research-lib\nsections:\n quant: Quantitative Methods\n',
'utf8'
);
await writeFile(
join(tempDir, 'cards', 'quant', 'dsr-basics.md'),
[
'---',
'title: "Deflated Sharpe Ratio"',
'summary: "Adjusts Sharpe for multiple testing."',
'matches: ["dsr", "sharpe"]',
'---',
'',
'Use DSR to account for trial count.',
].join('\n'),
'utf8'
);
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const input = createMemoryInput([
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'defaults-test', version: '1.0.0' },
},
}),
JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: {
name: 'read_knowledge',
arguments: {
source: 'library',
id: 'research-lib:quant/dsr-basics',
},
},
}),
]);
const exitCode = await runResearchCopilotMcp({
env: {
RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`,
RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root',
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
RESEARCH_MCP_LIBRARY_ROOT: tempDir,
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }),
},
input,
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
openStore: () => ({
store: createFakeStore(),
close: () => {
closed.push('store');
},
}),
// Intentionally omit createLibraryCardReader to exercise the default factory.
newId: () => '00000000-0000-4000-8000-000000000002',
now: () => FIXED_NOW_MS,
});
expect(exitCode).toBe(0);
expect(stderr.text()).toBe('');
expect(closed).toEqual(['store', 'executor']);
const responses = stdout
.text()
.trim()
.split('\n')
.map(line => JSON.parse(line) as Record<string, unknown>);
expect(responses).toHaveLength(2);
const callResp = responses[1] as {
id: number;
result: {
isError?: boolean;
content: Array<{ type: string; text: string }>;
};
};
expect(callResp.id).toBe(2);
expect(callResp.result.isError).not.toBe(true);
const payload = JSON.parse(callResp.result.content[0]!.text) as ReadKnowledgeResultPayload;
expect(payload.rowCount).toBe(1);
expect(payload.rows).toHaveLength(1);
const firstRow = payload.rows[0];
expect(firstRow?.source).toBe('library');
if (firstRow?.source === 'library') {
expect(firstRow.id).toBe('research-lib:quant/dsr-basics');
expect(firstRow.title).toBe('Deflated Sharpe Ratio');
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}
});
test('default openExecutor resolves master openResearchCopilotExecutor and fails closed without opening a DB socket', async () => {
// Passes parseResearchCopilotHostConfig (valid scheme + host), but fails
// openResearchCopilotExecutor synchronously (missing database path) before creating pg.Pool.
const urlWithoutDatabase = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433`;
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
let openStoreCalled = false;
const exitCode = await runResearchCopilotMcp({
env: {
RESEARCH_MCP_POSTGRES_URL: urlWithoutDatabase,
RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root',
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root',
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }),
},
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
// Intentionally omit openExecutor to exercise lazy import of openResearchCopilotExecutor.
openStore: () => {
openStoreCalled = true;
return { store: createFakeStore(), close: () => undefined };
},
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
expect(stderr.text()).toBe(RESEARCH_COPILOT_HOST_ERROR_LINE);
expect(stderr.text()).not.toContain(FAKE_PASSWORD);
expect(stderr.text()).not.toContain(FAKE_ENCODED_PASSWORD);
expect(stderr.text()).not.toContain(urlWithoutDatabase);
expect(openStoreCalled).toBe(false);
});
test('default openStore resolves master openResearchCopilotStore (in-memory DuckDB) and closes cleanly', async () => {
const tempCuratedRoot = await mkdtemp(join(tmpdir(), 'stockbot-mcp-curated-'));
try {
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const input = createMemoryInput([
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'defaults-store-test', version: '1.0.0' },
},
}),
JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/list',
params: {},
}),
]);
const exitCode = await runResearchCopilotMcp({
env: {
RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`,
RESEARCH_MCP_CURATED_ROOT: tempCuratedRoot,
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root',
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }),
},
input,
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
// Intentionally omit openStore to exercise lazy import of openResearchCopilotStore.
createLibraryCardReader: () => createFakeLibraryReader(),
newId: () => '00000000-0000-4000-8000-000000000003',
now: () => FIXED_NOW_MS,
});
expect(exitCode).toBe(0);
expect(stderr.text()).toBe('');
expect(closed).toEqual(['executor']);
const responses = stdout
.text()
.trim()
.split('\n')
.map(line => JSON.parse(line) as Record<string, unknown>);
expect(responses).toHaveLength(2);
const listResp = responses[1] as {
id: number;
result: { tools: Array<{ name: string }> };
};
expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]);
} finally {
await rm(tempCuratedRoot, { recursive: true, force: true });
}
});
});

View file

@ -0,0 +1,391 @@
import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store';
import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb';
import {
type LibraryCardReaderHandle,
MCP_PROTOCOL_VERSION,
type PostgresResearchCopilotExecutor,
RESEARCH_COPILOT_HOST_NAME,
RESEARCH_COPILOT_HOST_VERSION,
RESEARCH_COPILOT_TOOL_NAMES,
type StdioInput,
type StdioOutput,
} from '@stock-bot/research/mcp';
import {
RESEARCH_COPILOT_CONFIG_ERROR_LINE,
RESEARCH_COPILOT_HOST_ERROR_LINE,
runResearchCopilotMcp,
} from '../research-copilot-mcp';
const FAKE_DECODED_PASSWORD = 's3cr@t pass#99!';
const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD);
const FAKE_POSTGRES_URL = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev?sslmode=disable`;
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z';
const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0);
function buildValidEnv(
overrides: Readonly<Record<string, string | undefined>> = {}
): Record<string, string | undefined> {
return {
PATH: '/usr/local/bin:/usr/bin',
NODE_ENV: 'test',
RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL,
RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro',
RESEARCH_MCP_CURATED_ROOT: '/tmp/fake-curated-root-secret-path',
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
RESEARCH_MCP_LIBRARY_ROOT: '/tmp/fake-library-root-secret-path',
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({
XNYS: [101],
}),
...overrides,
};
}
function createMemoryWriter(): {
readonly stream: StdioOutput;
readonly chunks: string[];
text(): string;
} {
const chunks: string[] = [];
return {
stream: {
write(chunk: string): boolean {
chunks.push(chunk);
return true;
},
},
chunks,
text: () => chunks.join(''),
};
}
function createMemoryInput(lines: readonly string[]): StdioInput {
return {
async *[Symbol.asyncIterator](): AsyncIterator<string> {
for (const line of lines) {
yield `${line}\n`;
}
},
};
}
function createFakeExecutor(): PostgresResearchCopilotExecutor {
return {
async query<Row = Record<string, unknown>>(): Promise<{ readonly rows: readonly Row[] }> {
return { rows: [] };
},
};
}
function createFakeStore(): MarketDataStore {
return {
async *bars(q: BarQuery): AsyncIterable<BarBatch> {
yield {
listingId: q.listingIds[0] ?? 0,
timeframe: q.timeframe,
rows: [],
};
},
async crossSection() {
throw new MarketDataStoreNotImplementedError('crossSection');
},
async fundamentalsAsOf() {
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
},
async events() {
throw new MarketDataStoreNotImplementedError('events');
},
async shortsAsOf() {
throw new MarketDataStoreNotImplementedError('shortsAsOf');
},
async macroAsOf() {
throw new MarketDataStoreNotImplementedError('macroAsOf');
},
async fx() {
throw new MarketDataStoreNotImplementedError('fx');
},
async universe() {
return [];
},
};
}
function createFakeLibraryReader(): LibraryCardReaderHandle {
return {
async listLibraryCards() {
return [];
},
};
}
function assertSingleFixedLineNoSecrets(
stderrText: string,
expectedLine: string,
env: Readonly<Record<string, string | undefined>>
): void {
expect(stderrText).toBe(expectedLine);
expect(stderrText.endsWith('\n')).toBe(true);
expect(stderrText.slice(0, -1)).not.toContain('\n');
const forbidden = [
FAKE_POSTGRES_URL,
FAKE_ENCODED_PASSWORD,
FAKE_DECODED_PASSWORD,
env.RESEARCH_MCP_POSTGRES_URL,
env.RESEARCH_MCP_CURATED_ROOT,
env.RESEARCH_MCP_LIBRARY_ROOT,
env.RESEARCH_MCP_PRINCIPAL_ID,
].filter((value): value is string => typeof value === 'string' && value.length > 0);
for (const secret of forbidden) {
expect(stderrText).not.toContain(secret);
}
}
describe('scripts/research-copilot-mcp.ts', () => {
test('package.json defines mcp:research-copilot pointing to scripts/research-copilot-mcp.ts', () => {
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
const pkg = JSON.parse(readFileSync(join(repoRoot, 'package.json'), 'utf8')) as {
scripts?: Record<string, string>;
};
expect(pkg.scripts?.['mcp:research-copilot']).toBe('bun run scripts/research-copilot-mcp.ts');
});
test('missing required RESEARCH_MCP_* env returns exit code 1, one fixed stderr line, and zero stdout bytes', async () => {
const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: undefined });
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
let openExecutorCalled = false;
let openStoreCalled = false;
const exitCode = await runResearchCopilotMcp({
env,
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => {
openExecutorCalled = true;
return { executor: createFakeExecutor(), close: () => undefined };
},
openStore: () => {
openStoreCalled = true;
return { store: createFakeStore(), close: () => undefined };
},
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env);
expect(openExecutorCalled).toBe(false);
expect(openStoreCalled).toBe(false);
});
test('invalid RESEARCH_MCP_* env fails closed with one fixed stderr line and zero stdout bytes', async () => {
const env = buildValidEnv({
RESEARCH_MCP_POSTGRES_URL: `http://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`,
});
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const exitCode = await runResearchCopilotMcp({
env,
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({ executor: createFakeExecutor(), close: () => undefined }),
openStore: () => ({ store: createFakeStore(), close: () => undefined }),
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env);
});
test('openExecutor failure returns 1 with fixed stderr line leaking no DSN, password, or env values', async () => {
const env = buildValidEnv();
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
let openStoreCalled = false;
const exitCode = await runResearchCopilotMcp({
env,
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => {
throw new Error(
`connect failed for ${FAKE_POSTGRES_URL} (pw=${FAKE_DECODED_PASSWORD}) root=${env.RESEARCH_MCP_CURATED_ROOT}`
);
},
openStore: () => {
openStoreCalled = true;
return { store: createFakeStore(), close: () => undefined };
},
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env);
expect(openStoreCalled).toBe(false);
});
test('openStore failure closes already-opened executor and returns 1 with fixed stderr line', async () => {
const env = buildValidEnv();
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const exitCode = await runResearchCopilotMcp({
env,
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
openStore: () => {
throw new Error(`DuckDB failed for ${env.RESEARCH_MCP_CURATED_ROOT} ${FAKE_POSTGRES_URL}`);
},
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env);
expect(closed).toEqual(['executor']);
});
test('stdio host failure closes store and executor in reverse order and leaks no secrets', async () => {
const env = buildValidEnv();
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const failingInput: StdioInput = {
async *[Symbol.asyncIterator](): AsyncIterator<string> {
throw new Error(`stdin boom ${FAKE_POSTGRES_URL} ${FAKE_DECODED_PASSWORD}`);
},
};
const exitCode = await runResearchCopilotMcp({
env,
input: failingInput,
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
openStore: () => ({
store: createFakeStore(),
close: () => {
closed.push('store');
},
}),
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env);
expect(closed).toEqual(['store', 'executor']);
});
test('MCP initialize + tools/list round trip returns all 6 copilot tools on stdout, exit 0, and closes resources', async () => {
const env = buildValidEnv();
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const input = createMemoryInput([
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'test-client', version: '1.0.0' },
},
}),
JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/list',
params: {},
}),
]);
const exitCode = await runResearchCopilotMcp({
env,
input,
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
openStore: () => ({
store: createFakeStore(),
close: () => {
closed.push('store');
},
}),
createLibraryCardReader: () => createFakeLibraryReader(),
newId: () => '00000000-0000-4000-8000-000000000001',
now: () => FIXED_NOW_MS,
});
expect(exitCode).toBe(0);
expect(stderr.text()).toBe('');
expect(closed).toEqual(['store', 'executor']);
const lines = stdout
.text()
.trim()
.split('\n')
.map(line => JSON.parse(line) as Record<string, unknown>);
expect(lines).toHaveLength(2);
const initResp = lines[0] as {
id: number;
result: {
protocolVersion: string;
serverInfo: { name: string; version: string };
};
};
expect(initResp.id).toBe(1);
expect(initResp.result.protocolVersion).toBe(MCP_PROTOCOL_VERSION);
expect(initResp.result.serverInfo).toEqual({
name: RESEARCH_COPILOT_HOST_NAME,
version: RESEARCH_COPILOT_HOST_VERSION,
});
const listResp = lines[1] as {
id: number;
result: { tools: Array<{ name: string }> };
};
expect(listResp.id).toBe(2);
expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]);
expect(listResp.result.tools).toHaveLength(6);
});
});

View file

@ -70,6 +70,7 @@ use crate::run_curate_macro::CurateMacroArgs;
use crate::run_curate_posts::{
CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE,
};
use crate::run_curate_qm_bars_1m::{CurateQmBars1mArgs, DEFAULT_QM_BARS_1M_MAPPING_SOURCE};
use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE};
use crate::run_mongo::{
CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs,
@ -95,6 +96,7 @@ pub enum CliAction {
CurateEvents(CurateEventsArgs),
CurateEventsMongo(CurateEventsMongoArgs),
CurateBars1m(CurateBars1mArgs),
CurateQmBars1m(CurateQmBars1mArgs),
CurateFx1m(CurateFx1mArgs),
CuratePosts(CuratePostsArgs),
CurateFundamentals(CurateFundamentalsArgs),
@ -163,6 +165,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\
{name} curate-bars-1m --eod-intraday <path> --qm-splits <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\
Curate split-unadjusted 1-minute bars from eodIntraday1M + qmSplits BSON + provider_mapping TSV into bars_1m.shard-<NN>.ilp (default --mapping-source: {DEFAULT_BARS_1M_MAPPING_SOURCE})\n\
{name} curate-qm-bars-1m --qm-intraday <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\
Curate raw 1-minute bars from qmIntraday BSON + provider_mapping TSV into bars_1m_qm.shard-<NN>.ilp (file mode only; default --mapping-source: {DEFAULT_QM_BARS_1M_MAPPING_SOURCE})\n\
{name} curate-fx-1m --eod-intraday <path> --out <dir> --shards <N>\n\
Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-<NN>.ilp\n\
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
@ -222,6 +226,7 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} curate-shorts --ceo-shorts <path> --provider-mapping <path> --out <dir> --shares-short-field <name> [--key-field <name>] [--report-date-field <name>] [--net-change-field <name>] [--pct-float-field <name>] [--mapping-source <name>]\n\
{name} curate-events --qm-filings <path> --qm-earnings <path> --provider-mapping <path> --out <dir> --filings-form-type-field <name> [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--earnings-key-field <name>] [--earnings-report-date-field <name>] [--earnings-announce-time-field <name>] [--earnings-fiscal-period-end-field <name>] [--earnings-actual-eps-field <name>] [--earnings-revenue-field <name>] [--mapping-source <name>]\n\
{name} curate-bars-1m --eod-intraday <path> --qm-splits <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\
{name} curate-qm-bars-1m --qm-intraday <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\
{name} curate-fx-1m --eod-intraday <path> --out <dir> --shards <N>\n\
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
{name} curate-fundamentals --qm-financials <path> --qm-filings <path> --provider-mapping <path> --listing-venues <path> --out <dir> --currency-field <name> --filings-form-type-field <name> --k <N> (--fiscal-period <quarterly|annual> | [--quarterly-tokens <a,b,..>] [--annual-tokens <a,b,..>]) [--financials-key-field <name>] [--period-end-field <name>] [--report-date-field <name>] [--report-period-field <name>] [--revenue-field <path>] [--net-income-field <path>] [--operating-cash-flow-field <path>] [--total-assets-field <path>] [--total-equity-field <path>] [--shares-outstanding-field <path>] [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--mapping-source <name>]\n\
@ -2116,6 +2121,172 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result<CliAction, String> {
}))
}
fn parse_curate_qm_bars_1m_args(args: &[&str]) -> Result<CliAction, String> {
parse_curate_qm_bars_1m_args_inner(args).map_err(|e| sanitize_single_line(&e))
}
fn parse_curate_qm_bars_1m_args_inner(args: &[&str]) -> Result<CliAction, String> {
let mut intraday_path: Option<PathBuf> = None;
let mut provider_mapping_path: Option<PathBuf> = None;
let mut out_dir: Option<PathBuf> = None;
let mut shard_count: Option<usize> = None;
let mut known_at_micros: Option<i64> = None;
let mut mapping_source: Option<String> = None;
let mut i = 0usize;
while i < args.len() {
let token = args[i];
if !token.starts_with("--") {
return Err(format!(
"unexpected positional argument '{token}' for curate-qm-bars-1m"
));
}
let flag_name = token.split_once('=').map_or(token, |(k, _)| k);
if matches!(
flag_name,
"--from-mongo"
| "--mongo-uri"
| "--mongo-uri-env"
| "--batch-size"
| "--limit"
| "--date-gte"
| "--date-lt"
| "--with-qm-prices"
) {
return Err(format!(
"MongoDB streaming flag '{flag_name}' is not supported by curate-qm-bars-1m (file mode only)"
));
}
if !matches!(
flag_name,
"--qm-intraday"
| "--provider-mapping"
| "--out"
| "--shards"
| "--known-at-micros"
| "--mapping-source"
) {
return Err(format!("unknown flag '{flag_name}' for curate-qm-bars-1m"));
}
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
i += 1;
(k, v)
} else {
let Some(&v) = args.get(i + 1) else {
return Err(format!("missing value for flag '{token}'"));
};
if v.starts_with("--") {
return Err(format!("missing value for flag '{token}'"));
}
i += 2;
(token, v)
};
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate flag '{flag_name}'"));
}
if raw.is_empty() {
return Err(format!("empty value for flag '{flag_name}'"));
}
*slot = Some(PathBuf::from(raw));
Ok(())
};
let set_name = |slot: &mut Option<String>, flag_name: &str, raw: &str| -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate flag '{flag_name}'"));
}
if raw.trim().is_empty() {
return Err(format!("empty value for flag '{flag_name}'"));
}
*slot = Some(raw.to_string());
Ok(())
};
match flag {
"--qm-intraday" => set_path(&mut intraday_path, "--qm-intraday", value)?,
"--provider-mapping" => {
set_path(&mut provider_mapping_path, "--provider-mapping", value)?;
}
"--out" => set_path(&mut out_dir, "--out", value)?,
"--shards" => {
if shard_count.is_some() {
return Err("duplicate flag '--shards'".to_string());
}
if value.is_empty() {
return Err("empty value for flag '--shards'".to_string());
}
if !value.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!(
"invalid --shards '{value}' (expected a positive integer >= 1)"
));
}
let parsed = value.parse::<usize>().map_err(|_| {
format!("invalid --shards '{value}' (expected a positive integer >= 1)")
})?;
if parsed == 0 {
return Err(format!(
"invalid --shards '{value}' (expected a positive integer >= 1)"
));
}
shard_count = Some(parsed);
}
"--known-at-micros" => {
if known_at_micros.is_some() {
return Err("duplicate flag '--known-at-micros'".to_string());
}
if value.is_empty() {
return Err("empty value for flag '--known-at-micros'".to_string());
}
if !value.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!(
"invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)"
));
}
let parsed = value.parse::<i64>().map_err(|_| {
format!(
"invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)"
)
})?;
if parsed <= 0 {
return Err(format!(
"invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)"
));
}
known_at_micros = Some(parsed);
}
"--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?,
other => return Err(format!("unknown flag '{other}' for curate-qm-bars-1m")),
}
}
let intraday_path =
intraday_path.ok_or_else(|| "missing required flag '--qm-intraday'".to_string())?;
let provider_mapping_path = provider_mapping_path
.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
let shard_count =
shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?;
let known_at_micros =
known_at_micros.ok_or_else(|| "missing required flag '--known-at-micros'".to_string())?;
Ok(CliAction::CurateQmBars1m(CurateQmBars1mArgs {
intraday_path,
provider_mapping_path,
out_dir,
mapping_source: mapping_source
.unwrap_or_else(|| DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string()),
shard_count,
known_at_micros,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
}))
}
fn parse_curate_fx_1m_args(args: &[&str]) -> Result<CliAction, String> {
let mut intraday_path: Option<PathBuf> = None;
let mut out_dir: Option<PathBuf> = None;
@ -2306,6 +2477,7 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest),
["curate-events", rest @ ..] => parse_curate_events_args(rest),
["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest),
["curate-qm-bars-1m", rest @ ..] => parse_curate_qm_bars_1m_args(rest),
["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest),
["curate-posts", rest @ ..] => parse_curate_posts_args(rest),
["curate-fundamentals", rest @ ..] => parse_curate_fundamentals_args(rest),
@ -4669,6 +4841,357 @@ mod tests {
}
}
#[test]
fn parse_curate_qm_bars_1m_valid_default_and_explicit_mapping_source() {
let parsed = parse_args(&to_args(&[
"curate-qm-bars-1m",
"--qm-intraday",
"qm_intraday.bson",
"--provider-mapping",
"mapping.tsv",
"--out",
"out_dir",
"--shards",
"4",
"--known-at-micros",
"1735689600000000",
]))
.expect("valid curate-qm-bars-1m args with default mapping source");
assert_eq!(
parsed,
CliAction::CurateQmBars1m(CurateQmBars1mArgs {
intraday_path: PathBuf::from("qm_intraday.bson"),
provider_mapping_path: PathBuf::from("mapping.tsv"),
out_dir: PathBuf::from("out_dir"),
mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count: 4,
known_at_micros: 1_735_689_600_000_000,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
})
);
assert_eq!(DEFAULT_QM_BARS_1M_MAPPING_SOURCE, "qm");
let parsed_eq = parse_args(&to_args(&[
"curate-qm-bars-1m",
"--qm-intraday=i2.bson",
"--provider-mapping=m2.tsv",
"--out=o2",
"--shards=2",
"--known-at-micros=9223372036854775807",
"--mapping-source=qm_alt",
]))
.expect("valid curate-qm-bars-1m args with equals form and explicit mapping source");
assert_eq!(
parsed_eq,
CliAction::CurateQmBars1m(CurateQmBars1mArgs {
intraday_path: PathBuf::from("i2.bson"),
provider_mapping_path: PathBuf::from("m2.tsv"),
out_dir: PathBuf::from("o2"),
mapping_source: "qm_alt".to_string(),
shard_count: 2,
known_at_micros: i64::MAX,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
})
);
}
#[test]
fn curate_qm_bars_1m_usage_mentions_command_and_all_flags() {
let expected_flags = [
"--qm-intraday",
"--provider-mapping",
"--out",
"--shards",
"--known-at-micros",
"--mapping-source",
];
let usage = format_usage("curate-etl", "0.1.0");
let usage_stderr = format_usage_stderr("curate-etl");
let usage_line = usage
.lines()
.find(|line| line.trim_start().starts_with("curate-etl curate-qm-bars-1m "))
.expect("format_usage missing curate-qm-bars-1m command line");
let stderr_line = usage_stderr
.lines()
.find(|line| line.trim_start().starts_with("curate-etl curate-qm-bars-1m "))
.expect("format_usage_stderr missing curate-qm-bars-1m command line");
for flag in expected_flags {
assert!(
usage_line.contains(flag),
"format_usage curate-qm-bars-1m line missing {flag}: {usage_line}"
);
assert!(
stderr_line.contains(flag),
"format_usage_stderr curate-qm-bars-1m line missing {flag}: {stderr_line}"
);
}
assert!(
!usage_line.contains("--qm-splits"),
"format_usage curate-qm-bars-1m line must not list --qm-splits: {usage_line}"
);
assert!(
!stderr_line.contains("--qm-splits"),
"format_usage_stderr curate-qm-bars-1m line must not list --qm-splits: {stderr_line}"
);
}
#[test]
fn parse_curate_qm_bars_1m_rejects_missing_required_flags() {
let required: [(&str, &str); 5] = [
("--qm-intraday", "qm_intraday.bson"),
("--provider-mapping", "mapping.tsv"),
("--out", "out_dir"),
("--shards", "2"),
("--known-at-micros", "1735689600000000"),
];
for omit in 0..required.len() {
let mut argv: Vec<&str> = vec!["curate-qm-bars-1m"];
for (idx, &(flag, val)) in required.iter().enumerate() {
if idx != omit {
argv.push(flag);
argv.push(val);
}
}
let err = parse_args(&to_args(&argv)).unwrap_err();
let missing_flag = required[omit].0;
assert!(
err.contains(&format!("missing required flag '{missing_flag}'")),
"expected missing required flag '{missing_flag}', got: {err}"
);
}
}
#[test]
fn parse_curate_qm_bars_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() {
let base = [
"curate-qm-bars-1m",
"--qm-intraday",
"i.bson",
"--provider-mapping",
"m.tsv",
"--out",
"o",
"--shards",
"2",
"--known-at-micros",
"1000",
"--mapping-source",
"qm",
];
// Duplicate flags (path, numeric, and name).
for (flag, extra_val) in [
("--qm-intraday", "i2.bson"),
("--provider-mapping", "m2.tsv"),
("--out", "o2"),
("--shards", "3"),
("--known-at-micros", "2000"),
("--mapping-source", "qm"),
] {
let mut argv = base.to_vec();
argv.push(flag);
argv.push(extra_val);
let err = parse_args(&to_args(&argv)).unwrap_err();
assert!(
err.contains(&format!("duplicate flag '{flag}'")),
"expected duplicate error for {flag}, got: {err}"
);
}
// Empty values via --flag= and whitespace-only --mapping-source.
for flag in [
"--qm-intraday",
"--provider-mapping",
"--out",
"--shards",
"--known-at-micros",
"--mapping-source",
] {
let empty_token = format!("{flag}=");
let err = parse_args(&to_args(&["curate-qm-bars-1m", &empty_token])).unwrap_err();
assert!(
err.contains(&format!("empty value for flag '{flag}'")),
"expected empty value error for {flag}, got: {err}"
);
}
let err =
parse_args(&to_args(&["curate-qm-bars-1m", "--mapping-source", " "])).unwrap_err();
assert!(
err.contains("empty value for flag '--mapping-source'"),
"{err}"
);
// Flag at end of input or followed by another flag.
let err = parse_args(&to_args(&["curate-qm-bars-1m", "--qm-intraday"])).unwrap_err();
assert!(
err.contains("missing value for flag '--qm-intraday'"),
"{err}"
);
let err = parse_args(&to_args(&[
"curate-qm-bars-1m",
"--shards",
"--out",
"o",
]))
.unwrap_err();
assert!(err.contains("missing value for flag '--shards'"), "{err}");
// Unknown flags (including curate-bars-1m-only flags --qm-splits and --eod-intraday),
// both with a value and bare (without consuming a value first).
for unknown_flag in ["--nope", "--qm-splits", "--eod-intraday"] {
let mut unknown = base.to_vec();
unknown.push(unknown_flag);
unknown.push("x");
let err = parse_args(&to_args(&unknown)).unwrap_err();
assert!(
err.contains(&format!("unknown flag '{unknown_flag}' for curate-qm-bars-1m")),
"expected unknown flag error for {unknown_flag}, got: {err}"
);
let err_bare = parse_args(&to_args(&["curate-qm-bars-1m", unknown_flag])).unwrap_err();
assert!(
err_bare.contains(&format!("unknown flag '{unknown_flag}' for curate-qm-bars-1m")),
"expected unknown flag error for bare {unknown_flag}, got: {err_bare}"
);
}
// Positional argument.
let err = parse_args(&to_args(&["curate-qm-bars-1m", "positional"])).unwrap_err();
assert!(
err.contains("unexpected positional argument 'positional' for curate-qm-bars-1m"),
"{err}"
);
// Multiline error sanitization (CR/LF escaped to single line).
let err = parse_args(&to_args(&["curate-qm-bars-1m", "bad\r\narg"])).unwrap_err();
assert!(
!err.contains('\r') && !err.contains('\n'),
"error must be single-line: {err:?}"
);
assert!(err.contains("bad\\r\\narg"), "expected escaped CR/LF: {err}");
}
#[test]
fn parse_curate_qm_bars_1m_rejects_invalid_numeric_flags() {
let base_without_shards = [
"curate-qm-bars-1m",
"--qm-intraday",
"i.bson",
"--provider-mapping",
"m.tsv",
"--out",
"o",
"--known-at-micros",
"1000",
];
for bad_shards in [
"0",
"-1",
"+1",
"abc",
"1.5",
"999999999999999999999999999999999999999",
] {
let mut argv = base_without_shards.to_vec();
argv.push("--shards");
argv.push(bad_shards);
let err = parse_args(&to_args(&argv)).unwrap_err();
assert!(
err.contains("invalid --shards"),
"expected invalid --shards for '{bad_shards}', got: {err}"
);
}
let base_without_known_at = [
"curate-qm-bars-1m",
"--qm-intraday",
"i.bson",
"--provider-mapping",
"m.tsv",
"--out",
"o",
"--shards",
"2",
];
for bad_known_at in [
"0",
"-1",
"-9223372036854775808",
"+1000",
"abc",
"1.5",
"9223372036854775808",
"999999999999999999999999999999",
] {
let mut argv = base_without_known_at.to_vec();
argv.push("--known-at-micros");
argv.push(bad_known_at);
let err = parse_args(&to_args(&argv)).unwrap_err();
assert!(
err.contains("invalid --known-at-micros"),
"expected invalid --known-at-micros for '{bad_known_at}', got: {err}"
);
}
}
#[test]
fn parse_curate_qm_bars_1m_rejects_all_mongo_streaming_flags_without_echoing_values() {
let mongo_flags = [
"--from-mongo",
"--mongo-uri",
"--mongo-uri-env",
"--batch-size",
"--limit",
"--date-gte",
"--date-lt",
"--with-qm-prices",
];
let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock";
for flag in mongo_flags {
// Bare form (at end of argv).
let err_bare = parse_args(&to_args(&["curate-qm-bars-1m", flag])).unwrap_err();
assert!(
err_bare.contains(flag) && err_bare.contains("file mode only"),
"bare {flag} should fail with file-mode error, got: {err_bare}"
);
assert!(
!err_bare.contains('\r') && !err_bare.contains('\n'),
"bare {flag} error must be single-line: {err_bare:?}"
);
// Separated value form.
let err_sep = parse_args(&to_args(&["curate-qm-bars-1m", flag, secret])).unwrap_err();
assert!(
err_sep.contains(flag) && err_sep.contains("file mode only"),
"separated {flag} should fail with file-mode error, got: {err_sep}"
);
assert!(
!err_sep.contains("s3cr3t_pw"),
"separated {flag} error leaked value: {err_sep}"
);
// Equals form.
let eq_token = format!("{flag}={secret}");
let err_eq = parse_args(&to_args(&["curate-qm-bars-1m", &eq_token])).unwrap_err();
assert!(
err_eq.contains(flag) && err_eq.contains("file mode only"),
"equals {flag} should fail with file-mode error, got: {err_eq}"
);
assert!(
!err_eq.contains("s3cr3t_pw"),
"equals {flag} error leaked value: {err_eq}"
);
}
}
#[test]
fn parse_curate_fx_1m_valid_space_and_equals_forms() {
let expected = CliAction::CurateFx1m(CurateFx1mArgs {

View file

@ -36,6 +36,7 @@ use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d};
use curate_etl::run_curate_fx_1m::{format_curate_fx_1m_report, run_curate_fx_1m};
use curate_etl::run_curate_macro::{format_curate_macro_report, run_curate_macro};
use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts};
use curate_etl::run_curate_qm_bars_1m::{format_curate_qm_bars_1m_report, run_curate_qm_bars_1m};
use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts};
use curate_etl::run_mongo::{
run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo,
@ -215,6 +216,17 @@ fn main() -> ExitCode {
ExitCode::FAILURE
}
},
Ok(CliAction::CurateQmBars1m(curate_args)) => match run_curate_qm_bars_1m(&curate_args) {
Ok(report) => {
println!("{}", format_curate_qm_bars_1m_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
let msg = err.to_string().replace('\r', "\\r").replace('\n', "\\n");
eprintln!("error: {msg}");
ExitCode::FAILURE
}
},
Ok(CliAction::CurateFx1m(curate_args)) => match run_curate_fx_1m(&curate_args) {
Ok(report) => {
println!("{}", format_curate_fx_1m_report(&report));

View file

@ -0,0 +1,684 @@
//! End-to-end binary integration tests for `curate-etl curate-qm-bars-1m` (`M2.3r`).
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU64, Ordering};
use bson::raw::{cstr, RawDocumentBuf};
use bson::DateTime as BsonDateTime;
use curate_etl::bars_1m::BARS_1M_SOURCE_QM;
use curate_etl::ilp::{ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M};
use curate_etl::{
et_to_utc_micros, format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, ymd_to_epoch_days,
BsonStreamOptions, CurateQmBars1mArgs, IlpWriterOptions, DEFAULT_QM_BARS_1M_MAPPING_SOURCE,
};
static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(tag: &str) -> Self {
let pid = std::process::id();
let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("curate-etl-it-qm-bars-1m-{tag}-{pid}-{seq}"));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create integration test temp dir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn run_bin(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
.args(args)
.output()
.expect("spawn curate-etl binary")
}
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).expect("valid date")
}
fn et_ts_millis(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 {
let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp");
assert_eq!(micros % 1_000, 0);
micros / 1_000
}
fn make_qm_intraday_doc(
code: &str,
timestamp_ms: i64,
open: f64,
high: f64,
low: f64,
close: f64,
sharevolume: f64,
) -> RawDocumentBuf {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), code);
doc.append(cstr!("timestamp"), BsonDateTime::from_millis(timestamp_ms));
doc.append(cstr!("open"), open);
doc.append(cstr!("high"), high);
doc.append(cstr!("low"), low);
doc.append(cstr!("close"), close);
doc.append(cstr!("sharevolume"), sharevolume);
doc
}
#[allow(clippy::too_many_arguments)]
fn make_qm_intraday_doc_with_adjusted(
code: &str,
timestamp_ms: i64,
open: f64,
high: f64,
low: f64,
close: f64,
sharevolume: f64,
adj_scale: f64,
) -> RawDocumentBuf {
let mut doc = make_qm_intraday_doc(code, timestamp_ms, open, high, low, close, sharevolume);
doc.append(cstr!("adjustedopen"), open / adj_scale);
doc.append(cstr!("adjustedhigh"), high / adj_scale);
doc.append(cstr!("adjustedlow"), low / adj_scale);
doc.append(cstr!("adjustedclose"), close / adj_scale);
doc.append(cstr!("avolume"), sharevolume * adj_scale);
doc
}
fn concat_docs(docs: &[RawDocumentBuf]) -> Vec<u8> {
let mut out = Vec::new();
for doc in docs {
out.extend_from_slice(doc.as_bytes());
}
out
}
fn read_dir_files(dir: &Path) -> BTreeMap<String, Vec<u8>> {
let mut out = BTreeMap::new();
for entry in fs::read_dir(dir).expect("read output dir") {
let entry = entry.expect("dir entry");
let name = entry
.file_name()
.into_string()
.expect("UTF-8 file name in output dir");
let bytes = fs::read(entry.path()).expect("read output file");
out.insert(name, bytes);
}
out
}
fn strip_timing_line(report: &str) -> Vec<&str> {
report
.lines()
.filter(|line| !line.trim_start().starts_with("timing:"))
.collect()
}
fn shard_and_staging_files(dir: &Path) -> Vec<String> {
if !dir.exists() {
return Vec::new();
}
read_dir_files(dir).into_keys().collect()
}
#[derive(Debug)]
struct IlpRow {
table: String,
listing_id: i32,
source: String,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
known_at: i64,
ts: i64,
}
/// Minimal ILP v2 `bars_1m` decoder respecting 8-byte binary `DOUBLE` payloads (`==\x10<8 LE>`)
/// so embedded `0x0a` bytes inside doubles never split rows.
fn decode_rows(data: &[u8]) -> Vec<IlpRow> {
let mut rows = Vec::new();
let mut i = 0usize;
while i < data.len() {
let tag_start = i;
while data[i] != b' ' {
i += 1;
}
let tags = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tags");
i += 1;
let mut parts = tags.split(',');
let table = parts.next().expect("table name").to_string();
let listing_id: i32 = parts
.next()
.expect("listing_id tag")
.strip_prefix("listing_id=")
.expect("listing_id= prefix")
.parse()
.expect("i32 listing_id");
let _session = parts.next().expect("session tag");
let source = parts
.next()
.expect("source tag")
.strip_prefix("source=")
.expect("source= prefix")
.to_string();
assert!(parts.next().is_none(), "unexpected extra ILP tag");
let mut read_f64 = |name: &str| -> f64 {
let prefix = format!("{name}==");
assert!(
data[i..].starts_with(prefix.as_bytes()),
"expected {prefix} at offset {i}"
);
i += prefix.len();
assert_eq!(
data[i], ILP_V2_DOUBLE_TYPE,
"expected binary DOUBLE type tag for {name}"
);
i += 1;
let v = f64::from_le_bytes(data[i..i + 8].try_into().unwrap());
i += 8;
if data[i] == b',' {
i += 1;
}
v
};
let open = read_f64("open");
let high = read_f64("high");
let low = read_f64("low");
let close = read_f64("close");
let volume = read_f64("volume");
assert!(data[i..].starts_with(b"known_at="), "expected known_at=");
i += b"known_at=".len();
let ks = i;
while data[i] != b' ' {
i += 1;
}
let known_at: i64 = std::str::from_utf8(&data[ks..i])
.unwrap()
.strip_suffix('t')
.unwrap()
.parse()
.unwrap();
i += 1;
let ts_start = i;
while data[i] != b'\n' {
i += 1;
}
let ts: i64 = std::str::from_utf8(&data[ts_start..i])
.unwrap()
.strip_suffix('t')
.unwrap()
.parse()
.unwrap();
i += 1;
rows.push(IlpRow {
table,
listing_id,
source,
open,
high,
low,
close,
volume,
known_at,
ts,
});
}
rows
}
struct Fixture {
intraday: PathBuf,
mapping: PathBuf,
}
/// Synthetic `qmIntraday` fixture:
/// - `NVDA` pre-split bar with distinct `adjusted*`/`avolume` fields (ignored) and embedded `0x0a`
/// float byte in `close`.
/// - `NEXM:CA` bar with `-0.0` `sharevolume` (normalized to `+0.0`).
fn write_qm_fixture(dir: &Path, mapping_source: &str) -> (Fixture, f64) {
let close_with_lf_byte = f64::from_le_bytes([0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0x40]);
assert!(close_with_lf_byte.to_le_bytes().contains(&b'\n'));
let intraday = dir.join("qmIntraday.bson");
fs::write(
&intraday,
concat_docs(&[
make_qm_intraday_doc_with_adjusted(
"NVDA",
et_ts_millis(2024, 6, 7, 15, 59),
100.0,
101.0,
99.5,
close_with_lf_byte,
412_390.0,
10.0,
),
make_qm_intraday_doc_with_adjusted(
"NVDA",
et_ts_millis(2024, 6, 10, 15, 59),
121.50,
122.00,
121.20,
121.79,
350_000.0,
1.0,
),
make_qm_intraday_doc_with_adjusted(
"NEXM:CA",
et_ts_millis(2025, 6, 18, 15, 59),
1.21,
1.22,
1.20,
1.215,
-0.0,
0.05,
),
]),
)
.expect("write qmIntraday.bson");
let mapping = dir.join("provider_mapping.tsv");
fs::write(
&mapping,
format!(
"{mapping_source}\tNVDA\t2000-01-01\t\t1001\n\
{mapping_source}\tNEXM:CA\t2000-01-01\t\t1002\n"
),
)
.expect("write provider_mapping.tsv");
(Fixture { intraday, mapping }, close_with_lf_byte)
}
fn bin_args<'a>(
fx: &'a Fixture,
out: &'a Path,
known_at: &'a str,
extra: &[&'a str],
) -> Vec<&'a str> {
let mut argv = vec![
"curate-qm-bars-1m",
"--qm-intraday",
fx.intraday.to_str().unwrap(),
"--provider-mapping",
fx.mapping.to_str().unwrap(),
"--out",
out.to_str().unwrap(),
"--shards",
"2",
"--known-at-micros",
known_at,
];
argv.extend_from_slice(extra);
argv
}
#[test]
fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants() {
let tmp = TempDir::new("parity");
let (fx, close_with_lf_byte) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE);
let known_at_micros: i64 = 1_750_000_000_123_456;
let shard_count: usize = 2;
let bin_out = tmp.path().join("out-bin");
let bin_out_repeat = tmp.path().join("out-bin-repeat");
let direct_out = tmp.path().join("out-direct");
let output = run_bin(&bin_args(&fx, &bin_out, "1750000000123456", &[]));
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"expected exit 0, got {:?}; stderr:\n{stderr}\nstdout:\n{stdout}",
output.status.code()
);
assert!(
stderr.is_empty(),
"expected empty stderr on success, got:\n{stderr}"
);
let direct_args = CurateQmBars1mArgs {
intraday_path: fx.intraday.clone(),
provider_mapping_path: fx.mapping.clone(),
out_dir: direct_out.clone(),
mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(),
shard_count,
known_at_micros,
stream_options: BsonStreamOptions::default(),
ilp_options: IlpWriterOptions::default(),
};
let direct_report = run_curate_qm_bars_1m(&direct_args).expect("direct run_curate_qm_bars_1m");
assert_eq!(direct_report.rows_written, 3, "expected 3 emitted rows");
assert_eq!(
direct_report.intraday_decode.rejected_total(),
0,
"expected zero rejected BSON documents"
);
let direct_formatted = format_curate_qm_bars_1m_report(&direct_report);
assert_eq!(
strip_timing_line(&stdout),
strip_timing_line(&direct_formatted),
"binary stdout report must match direct runner report excluding timing line"
);
assert!(
stdout
.lines()
.any(|line| line.trim_start().starts_with("timing: elapsed_secs=")),
"expected timing line in stdout:\n{stdout}"
);
let bin_files = read_dir_files(&bin_out);
let direct_files = read_dir_files(&direct_out);
let expected_names = vec![
"bars_1m_qm.shard-00.ilp".to_string(),
"bars_1m_qm.shard-01.ilp".to_string(),
];
assert_eq!(
bin_files.keys().cloned().collect::<Vec<_>>(),
expected_names,
"unexpected files in binary output dir"
);
assert_eq!(
bin_files, direct_files,
"binary shard files must be byte-identical to direct runner output"
);
// Determinism across repeat runs.
let repeat = run_bin(&bin_args(&fx, &bin_out_repeat, "1750000000123456", &[]));
assert!(repeat.status.success());
assert_eq!(
bin_files,
read_dir_files(&bin_out_repeat),
"repeat runs must be byte-identical"
);
assert_eq!(
strip_timing_line(&stdout),
strip_timing_line(&String::from_utf8_lossy(&repeat.stdout)),
);
// Decode all ILP rows across shards and verify row count + financial invariants.
let mut rows: Vec<IlpRow> = bin_files
.values()
.flat_map(|bytes| decode_rows(bytes))
.collect();
assert_eq!(
rows.len(),
direct_report.rows_written,
"decoded ILP row count must equal reported rows_written"
);
rows.sort_by_key(|r| (r.listing_id, r.ts));
for row in &rows {
assert_eq!(row.table, TABLE_BARS_1M);
assert_eq!(row.source, BARS_1M_SOURCE_QM);
assert_eq!(row.known_at, known_at_micros);
}
// NVDA pre-split row: raw OHLCV bit-identical (adjusted* fields ignored), embedded 0x0a intact.
let nvda_pre = &rows[0];
assert_eq!(nvda_pre.listing_id, 1001);
assert_eq!(nvda_pre.ts, et_ts_millis(2024, 6, 7, 15, 59) * 1_000);
assert_eq!(nvda_pre.open.to_bits(), 100.0_f64.to_bits());
assert_eq!(nvda_pre.high.to_bits(), 101.0_f64.to_bits());
assert_eq!(nvda_pre.low.to_bits(), 99.5_f64.to_bits());
assert_eq!(nvda_pre.close.to_bits(), close_with_lf_byte.to_bits());
assert_eq!(nvda_pre.volume.to_bits(), 412_390.0_f64.to_bits());
// NVDA post-split row (adj_scale 1.0): raw OHLCV bit-identical, no un-adjustment applied.
let nvda_post = &rows[1];
assert_eq!(nvda_post.listing_id, 1001);
assert_eq!(nvda_post.ts, et_ts_millis(2024, 6, 10, 15, 59) * 1_000);
assert_eq!(nvda_post.open.to_bits(), 121.50_f64.to_bits());
assert_eq!(nvda_post.high.to_bits(), 122.00_f64.to_bits());
assert_eq!(nvda_post.low.to_bits(), 121.20_f64.to_bits());
assert_eq!(nvda_post.close.to_bits(), 121.79_f64.to_bits());
assert_eq!(nvda_post.volume.to_bits(), 350_000.0_f64.to_bits());
// NEXM:CA row: raw OHLC bit-identical, -0.0 sharevolume normalized to +0.0.
let nexm = &rows[2];
assert_eq!(nexm.listing_id, 1002);
assert_eq!(nexm.ts, et_ts_millis(2025, 6, 18, 15, 59) * 1_000);
assert_eq!(nexm.open.to_bits(), 1.21_f64.to_bits());
assert_eq!(nexm.high.to_bits(), 1.22_f64.to_bits());
assert_eq!(nexm.low.to_bits(), 1.20_f64.to_bits());
assert_eq!(nexm.close.to_bits(), 1.215_f64.to_bits());
assert_eq!(nexm.volume.to_bits(), 0.0_f64.to_bits());
}
#[test]
fn curate_qm_bars_1m_binary_missing_input_exits_nonzero_single_line_stderr_and_clean_out() {
let tmp = TempDir::new("missing-input");
let (fx, _) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE);
let missing_intraday = tmp.path().join("does-not-exist.bson");
let missing_mapping = tmp.path().join("does-not-exist.tsv");
for (tag, intraday_path, mapping_path) in [
("intraday", &missing_intraday, &fx.mapping),
("mapping", &fx.intraday, &missing_mapping),
] {
let out_dir = tmp.path().join(format!("out-empty-{tag}"));
fs::create_dir_all(&out_dir).expect("create empty out dir");
let output = run_bin(&[
"curate-qm-bars-1m",
"--qm-intraday",
intraday_path.to_str().unwrap(),
"--provider-mapping",
mapping_path.to_str().unwrap(),
"--out",
out_dir.to_str().unwrap(),
"--shards",
"2",
"--known-at-micros",
"1750000000000000",
]);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success(),
"expected non-zero exit when {tag} file is missing"
);
assert!(
stdout.is_empty(),
"expected no success report on stdout for missing {tag}, got:\n{stdout}"
);
let lines: Vec<&str> = stderr.lines().collect();
assert_eq!(
lines.len(),
1,
"expected strictly single-line stderr (no usage block) for missing {tag}, got:\n{stderr}"
);
assert!(
lines[0].starts_with("error:"),
"expected 'error:' prefix on stderr for missing {tag}, got: {}",
lines[0]
);
assert!(
shard_and_staging_files(&out_dir).is_empty(),
"expected no shard or staging files in output dir for missing {tag}, found: {:?}",
shard_and_staging_files(&out_dir)
);
}
}
#[test]
fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards() {
let tmp = TempDir::new("overwrite-coexist");
let (fx, _) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE);
let out = tmp.path().join("out");
fs::create_dir_all(&out).expect("create out dir");
// Pre-populate an EOD bars_1m shard in the same directory; QM run must not collide with it.
let eod_sentinel = b"sentinel-eod-bars-1m-shard\n".to_vec();
fs::write(out.join("bars_1m.shard-00.ilp"), &eod_sentinel).expect("write eod sentinel");
let first = run_bin(&bin_args(&fx, &out, "1750000000000000", &[]));
assert!(
first.status.success(),
"QM run should coexist with bars_1m.shard-00.ilp; stderr:\n{}",
String::from_utf8_lossy(&first.stderr)
);
let before = read_dir_files(&out);
assert_eq!(
before.get("bars_1m.shard-00.ilp"),
Some(&eod_sentinel),
"co-located EOD shard must remain untouched"
);
assert!(before.contains_key("bars_1m_qm.shard-00.ilp"));
assert!(before.contains_key("bars_1m_qm.shard-01.ilp"));
// Second run with different known_at must refuse to overwrite existing bars_1m_qm shards.
let second = run_bin(&bin_args(&fx, &out, "1760000000000000", &[]));
assert!(
!second.status.success(),
"second run into populated --out must fail"
);
assert!(second.stdout.is_empty(), "no success report expected");
let stderr = String::from_utf8_lossy(&second.stderr);
assert_eq!(stderr.lines().count(), 1, "single-line stderr expected: {stderr}");
assert!(stderr.starts_with("error:"), "stderr: {stderr}");
assert_eq!(
read_dir_files(&out),
before,
"existing shards must be untouched and no staging files left"
);
}
#[test]
fn curate_qm_bars_1m_binary_supports_custom_mapping_source() {
let tmp = TempDir::new("custom-source");
let (fx, _) = write_qm_fixture(tmp.path(), "qm_alt");
let out = tmp.path().join("out");
let output = run_bin(&bin_args(
&fx,
&out,
"1750000000000000",
&["--mapping-source=qm_alt"],
));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "stderr:\n{stderr}");
assert!(stderr.is_empty());
let rows: Vec<IlpRow> = read_dir_files(&out)
.values()
.flat_map(|bytes| decode_rows(bytes))
.collect();
assert_eq!(rows.len(), 3, "custom --mapping-source should map all 3 rows");
}
#[test]
fn curate_qm_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_nothing() {
let tmp = TempDir::new("parse-error");
let (fx, _) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE);
let out = tmp.path().join("out");
let secret = "--mongo-uri=mongodb://user:s3cr3t_pw@localhost:27017/stock";
let output = run_bin(&bin_args(&fx, &out, "1750000000000000", &[secret]));
assert!(!output.status.success());
assert!(output.stdout.is_empty());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("file mode only"), "stderr: {stderr}");
assert!(
stderr.contains("curate-qm-bars-1m --qm-intraday"),
"usage expected: {stderr}"
);
assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}");
assert!(!out.exists(), "parse failure must not create --out");
// Missing --known-at-micros: no clock fallback, nothing written.
let mut argv = bin_args(&fx, &out, "1", &[]);
argv.truncate(argv.len() - 2);
let output = run_bin(&argv);
assert!(!output.status.success());
assert!(String::from_utf8_lossy(&output.stderr)
.contains("missing required flag '--known-at-micros'"));
assert!(!out.exists());
}
#[test]
fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped() {
let tmp = TempDir::new("pit-mapping");
// "REUSE" maps to listing 101 through 2024-06-10 and to listing 202 from 2024-06-11;
// "GHOST" has no mapping row and must be dropped (never assigned a listing).
let mapping = tmp.path().join("provider_mapping.tsv");
fs::write(
&mapping,
"qm\tREUSE\t2024-06-01\t2024-06-10\t101\n\
qm\tREUSE\t2024-06-11\t\t202\n",
)
.expect("write provider_mapping.tsv");
let intraday = tmp.path().join("qmIntraday.bson");
let ts_old = et_ts_millis(2024, 6, 10, 10, 30);
let ts_new = et_ts_millis(2024, 6, 11, 10, 30);
fs::write(
&intraday,
concat_docs(&[
make_qm_intraday_doc("REUSE", ts_old, 50.0, 51.0, 49.0, 50.5, 1_000.0),
make_qm_intraday_doc("REUSE", ts_new, 60.0, 61.0, 59.0, 60.5, 2_000.0),
make_qm_intraday_doc("GHOST", ts_new, 1.0, 1.0, 1.0, 1.0, 10.0),
]),
)
.expect("write qmIntraday.bson");
let fx = Fixture { intraday, mapping };
let out = tmp.path().join("out");
let output = run_bin(&bin_args(&fx, &out, "1718236800000000", &[]));
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "stderr:\n{stderr}");
assert!(stderr.is_empty(), "stderr:\n{stderr}");
assert!(
stdout.contains("dropped_unmapped=1"),
"expected one unmapped row reported:\n{stdout}"
);
assert!(stdout.contains("rows_written=2"), "stdout:\n{stdout}");
let mut rows: Vec<IlpRow> = read_dir_files(&out)
.values()
.flat_map(|bytes| decode_rows(bytes))
.collect();
rows.sort_by_key(|r| r.ts);
assert_eq!(rows.len(), 2);
assert_eq!((rows[0].listing_id, rows[0].ts), (101, ts_old * 1_000));
assert_eq!((rows[1].listing_id, rows[1].ts), (202, ts_new * 1_000));
assert_eq!(rows[1].open.to_bits(), 60.0_f64.to_bits());
assert!(rows.iter().all(|r| r.known_at == 1_718_236_800_000_000));
// Reported per-shard counts must sum to the rows actually written in the shard files.
let per_shard_line = stdout
.lines()
.find(|l| l.contains("per_shard_rows="))
.expect("per_shard_rows in report");
let per_shard_sum: usize = per_shard_line
.split("per_shard_rows=")
.nth(1)
.unwrap()
.trim()
.split(',')
.map(|kv| kv.split_once('=').unwrap().1.parse::<usize>().unwrap())
.sum();
assert_eq!(per_shard_sum, rows.len());
}