stock-bot/design/m2-gap-audit.md

128 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Milestone M2 Gap Audit Report (T-203)
**Verdict:** **OPEN — M2 is not ready for closure.** Core M2 libraries (`curate-macro`, `send-ilp`, MCP server/adapters with Vault-fenced `query_data`, `fundamentalsAsOf`, QuestDB `10.2.0` primitives, and TS Feature Library) are present in the checked-out worktree and pass local sandbox-safe checks, but six concrete code/wiring gaps remain (including the missing desktop MCP entry point, unwired equity `1m` QuestDB consumer routing, and a `ceo_post` vs `post` event-kind mismatch). Authoritative `master` revision verification and all host-only `quant` / desktop / full-check closure gates remain **PENDING**.
> **Scope & Provenance Notes:**
> - Milestone and contract documents live under `design/` (`design/MILESTONES.md`, `design/DATA-CONTRACTS.md`, `design/PLATFORM-PLAN.md`), not `docs/`.
> - **Revision status:** Worktree `.git` metadata lives outside the sandbox boundary, so the exact base `master` SHA and `studio/auto-*` branches could not be inspected inside the sandbox. All local checks below ran against the checked-out worktree on branch `feat/m2-gap-audit` (`/home/boki/.studio/worktrees/stock-bot/slot-1`); authoritative `master` verification remains **PENDING** until the host confirms the `master` SHA.
> - Per settled director decision, **T-127** (M1 equity eligibility / Vault file isolation) stays deferred in the backlog and does not block M2.
> - Project CI is off; no CI workflows were planned, added, or modified.
---
## 1. Verification History & Worktree Gate Results
### 1.1 Earlier Planning-Phase Setup Failures (Recorded in Approved Plan)
During the initial read-only planning pass (unprovisioned environment before worktree dependencies and writable Cargo target were available), all four requested local gates and supplemental tests failed during setup:
| Gate / Suite | Command | Exit Code | Planning-Phase Outcome |
| --- | --- | --- | --- |
| Typecheck | `bun run typecheck` | `2` | **FAIL** — `TS2688` missing `bun-types` |
| Contracts | `bun run test:contracts` | `2` | **FAIL** — `TS2688` missing `bun-types` |
| Lint | `bun run lint:check` | `127` | **FAIL** — `eslint: command not found` |
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `101` | **FAIL** — `Read-only file system (os error 30)` creating Cargo target path |
| Supplemental M2 `bun test` | copilot server, stdio, snapshot exporter, DuckDB store, ILP writer | `1` | **FAIL** — missing `zod` and `@stock-bot/logger` during import setup |
### 1.2 Provisioned Worktree Sandbox Runs (`feat/m2-gap-audit`, `master` SHA Unconfirmed Locally)
Executed in the provisioned worktree `/home/boki/.studio/worktrees/stock-bot/slot-1` (branch `feat/m2-gap-audit`, Linux sandbox, network disabled, `.git` metadata outside sandbox):
| Gate / Suite | Command | Exit Code | Worktree Result |
| --- | --- | --- | --- |
| Typecheck | `bun run typecheck` | `0` | **PASS** (0 errors) |
| Contracts | `bun run test:contracts` | `0` | **PASS** (0 errors) |
| Lint | `bun run lint:check` | `0` | **PASS** (0 errors, 0 warnings) |
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PASS** (`1,548` passed, `0` failed, `4` ignored across `57` suites) |
| MCP `query_data` Vault Fence | `bun test libs/research/test/mcp-query-data.test.ts` | `0` | **PASS** (`13` pass, `0` fail) |
| Real-DuckDB M2 Fixtures | `bun test libs/data/duckdb/test/` | `0` | **PASS** (`25` pass, `0` fail across `4` files; includes Exit 2 restatement fixture & `openResearchCopilotStore`) |
| Research + QuestDB + Copilot Executor | `bun test libs/research/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** (`999` pass, `0` fail across `59` files) |
| Exit 3 Split-Boundary Fixture | `CARGO_BUILD_JOBS=2 cargo test -p curate-etl --offline split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` | `0` | **PASS** (`1` passed, `0` failed) |
| Utils | `bun run test:utils` | `0` | **PASS** (`32` pass, `0` fail across `3` files) |
| Calculations | `bun run test:calculations` | `0` | **PASS** (`144` pass, `0` fail across `12` files) |
- **Prior Studio unsandboxed runs (review branch `feat/m2-gap-audit`):** Studio `build` (`#1589`) and `test` (`#1590`) passed on the review branch; these cover the review branch only and do not substitute for host confirmation of the audited `master` SHA.
- **`master` verification status:** **PENDING** host confirmation of the exact `master` SHA and a host run of `CARGO_BUILD_JOBS=2 bun run check` (see Section 4.1).
---
## 2. Verified on `master` *(Source & Worktree Checks; Host `master` SHA Confirmation Pending)*
- **PRESENT · MCP Copilot Libraries, Vault-Fenced `query_data` & Snapshot Exporter.**
- `libs/research/src/mcp/copilot-server.ts` exposes all six M2 tools (`search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`).
- `createQueryDataTool` (`libs/research/src/mcp/tools/query-data.ts`) enforces strict Vault fencing: its Zod schema omits `scope` and `vault_evaluation_only` (`.strict()` rejects them with zero store calls), calls `fenceVaultQueryBounds` before any `store.universe` or `store.bars` call (clamping `to`/`asOf` strictly below `vaultCutoffTs` and rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError`), always passes `scope: 'vault_fenced'`, and applies defense-in-depth row filtering dropping any row where `row.ts >= vaultCutoffTs || row.knownAt >= vaultCutoffTs` (lines 203–210).
- Boundary cases in `libs/research/test/mcp-query-data.test.ts` — rejecting `scope`/`vault_evaluation_only`/unknown keys (L303), rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError` (L342), clamping straddling `to`/`asOf` below cutoff (L359), dropping leaky post-cutoff `ts`/`knownAt` rows (L386), clamping universe date via `min(to, asOf)` (L508), and DuckDB microsecond-bound + `adj_factors` snapshot checks (L576) — **PASS** in the worktree (`13` pass, `0` fail; host `master` SHA confirmation pending).
- `libs/research/src/mcp/adapters/postgres-copilot.ts` (`createPostgresResearchCopilotServer`) wires the read-only Studio library reader, PostgreSQL findings/caveats, trial lookup, and exchange calendars.
- `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`, T-184) and `openResearchCopilotExecutor` (`libs/data/postgres/src/research-copilot-executor.ts`, T-189/T-200) are exported and pass worktree unit tests.
- `exportNotebookSnapshot` (`libs/research/src/notebook-snapshot.ts`) and its Node/Bun adapters (`libs/research/src/notebook-snapshot-node.ts`) implement the `marimo check` → static HTML export sequence.
- **PRESENT · `tools/curate-etl` CLI Subcommands.**
- `tools/curate-etl/src/cli.rs` and `tools/curate-etl/src/main.rs` wire `curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`, `curate-bars-1m`, `curate-fx-1m`, `curate-posts`, `curate-fundamentals`, `curate-macro`, and `send-ilp`.
- `curate-macro` (T-194/T-202) connects `run_curate_macro` to `curate_and_write_macro`; `send-ilp` (T-190) connects `run_send_ilp` to shard discovery and one TCP connection per shard. Both pass offline native tests in the worktree.
- **PRESENT · Exit 2 (PIT Restatement) & Exit 3 (Split-Boundary) Fixtures.**
- `tools/curate-etl/src/fundamentals.rs` builds deduplicated 2D PIT snapshots and 4-quarter TTM with venue lag provenance.
- `libs/data/duckdb/test/duckdb-market-data-store.test.ts` passes the real-DuckDB `fundamentalsAsOf` restatement fixture in the worktree proving a restated Q1 (`known_at > Q2`) never overwrites Q2.
- `tools/curate-etl/src/run_curate_bars_1m_tests.rs` passes `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` in the worktree with the `0.5%` threshold and negative controls.
- **PRESENT · QuestDB `10.2.0` Primitives & TS Feature Library.**
- `docker-compose.yml`, `docker-compose.dev.yml`, and `docker-compose.prod.yml` pin `questdb/questdb:10.2.0`.
- `libs/data/questdb/src/{schema,client,query-builder,ilp-v2-writer}.ts` provide monthly WAL DDL (`M2_INTRADAY_SCHEMAS`, `getM2IntradayDDL`), parameterized PGWire (`QuestDBClient.query`), `LATEST ON`, and the ILP v2 binary batch writer.
- `libs/research/src/feature-library.ts` implements `registerSignal`, `runFeatureBatch`, and Zstd Parquet writing for versioned DuckDB SQL features.
---
## 3. Remaining M2 Code Gaps
1. **FAIL · Desktop MCP Entry Point & Exit 1 Wiring**
- T-196 target `scripts/research-copilot-mcp.ts` and root `package.json` script `mcp:research-copilot` are absent.
- `runResearchCopilotStdioHost` (`libs/research/src/mcp/host/stdio-host.ts`) still requires caller-injected store/executor factories rather than a runnable default entrypoint.
- `apps/stock/web-api/src/` has no MCP/SSE route.
- Impact: Desktop Claude Code cannot yet launch the copilot end-to-end to satisfy M2 Exit Criterion 1.
2. **FAIL · `ceoPosts` Event-Kind & Output-Root Interoperability**
- `tools/curate-etl/src/parquet_posts.rs` emits `EVENT_KIND_POST = "post"`, whereas `libs/research/src/market-data-store.ts` (`EventKind`), `libs/research/src/market-data-store-duckdb.ts` (`EVENT_KINDS`), `libs/research/src/mcp/tools/event-study.ts`, and `python/stockbot/data.py` (`EventKind`) all expect `"ceo_post"`.
- `tools/curate-etl/src/run_curate_posts.rs` writes `<out_dir>/events/year=YYYY/part.parquet` and fails closed (`RunCuratePostsError::EventsDatasetExists`) if `<out_dir>/events` already has `year=*` partitions from `curate-events`, while the copilot store takes a single curated root.
- Impact: Published `ceoPosts` cannot be queried alongside filings and earnings through the DuckDB store or MCP `event_study` as shipped.
3. **PARTIAL · Fundamentals & Macro Contract Gaps**
- `build_fundamentals_rows` (`tools/curate-etl/src/fundamentals.rs`) links filings using listing/fiscal-class plus report-date or filing-window heuristics because sampled filings lack statement period, whereas `design/DATA-CONTRACTS.md` specifies a direct period-end join.
- `run_curate_fundamentals` (`tools/curate-etl/src/run_curate_fundamentals.rs`) takes one caller-prepared financials BSON dump and requires `listing_venues.tsv`, which `exportCurateInputs` (`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts`) does not emit. No physical `fundamentals_bitemporal` writer or `eodFinancialsOLD` backfill path exists.
- `createDuckDbMarketDataStore().macroAsOf` (`libs/research/src/market-data-store-duckdb.ts:2294`) still rejects with `MarketDataStoreNotImplementedError`, so curated `teData` Parquet (`macro/part.parquet`) has no DuckDB reader.
4. **PARTIAL · Intraday Operating Path**
- `run_curate_qm_bars_1m` (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`) is implemented as a library function but has no binary subcommand dispatch in `tools/curate-etl/src/{cli,main}.rs`.
- `curate-bars-1m` and `curate-fx-1m` operate in file-mode BSON only (no `--from-mongo` streaming).
- `tools/curate-etl/src/bars_1m.rs` applies fixed Eastern session tags (venue/date overrides exist in close validation, not curation), and loaders stamp caller-supplied `--known-at-micros` whose historical availability semantics must be defined before as-of studies.
5. **FAIL / PARTIAL · QuestDB Startup Wiring & Intraday Read Path (Equity `1m` + FX `1m`)**
- **Unwired equity `1m` consumer path:** No application entry point constructs `createRoutedMarketDataStore` (`libs/research/src/market-data-store-routed.ts`) with `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`). The documented copilot factory `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`) opens DuckDB alone (`openDuckDbMarketDataStore`), which rejects `timeframe: '1m'` queries with `MarketDataStoreNotImplementedError` before reaching QuestDB.
- **Unwired FX `1m` route:** Even when `createRoutedMarketDataStore` is constructed, `fx()` delegates to the daily store rather than QuestDB `fx_1m`.
- **Startup DDL & legacy writer:** `getM2IntradayDDL` (`libs/data/questdb/src/schema.ts:139`) is opt-in with no checked-in startup caller applying it, and `QuestDBClient` (`libs/data/questdb/src/client.ts:232`) still instantiates legacy `QuestDBInfluxWriter` (`libs/data/questdb/src/influx-writer.ts`).
- **Schema wording drift:** `M2_INTRADAY_SCHEMAS.fx_1m` matches `design/DATA-CONTRACTS.md` (`DEDUP UPSERT KEYS(ts, pair)`), while `design/MILESTONES.md:96` wording can be read as `(ts, listing_id)` for both `bars_1m` and `fx_1m`.
6. **PARTIAL · Feature Library & Documentation Drift**
- `python/stockbot/__init__.py` and `python/stockbot/signals.py` do not expose `register_signal(...)` (only TS `libs/research/src/feature-library.ts` has `registerSignal`).
- `createDuckDbMarketDataStore().crossSection` (`libs/research/src/market-data-store-duckdb.ts:2283`) still rejects with `MarketDataStoreNotImplementedError`.
- `tools/curate-etl/README.md` still describes landed `curate-fundamentals` and `curate-macro` CLI wiring as deferred/follow-up in older stage sections (e.g., lines 1697, 1744, 1752, 1836, 1859).
- `AGENTS.md` and `studio.config.json` still reference `docs/` paths instead of `design/`.
- `design/MILESTONES.md:97` labels the Feature Library `D04` reopened, whereas `design/PLATFORM-PLAN.md` assigns the `register_signal` promotion bridge to `D11`.
---
## 4. Manual Host-Only Closure Gates
These checks cannot run inside the sandbox and must be executed on the host / `quant` before closing M2:
1. **Host Git Revision, Unmerged Branches & Full Check Gate**
- Record the exact audited `master` SHA and inspect `studio/auto-*` branches for any unmerged M2 commits (in particular T-196 desktop MCP wiring).
- Run `CARGO_BUILD_JOBS=2 bun run check` outside the sandbox on the confirmed `master` revision (covering `build`, `audit:secrets`, worktree-git tooling tests, and `stock_bot_safety*` PostgreSQL suites via `/home/boki/.studio/test-env/stock-bot.env`).
- Never mutate QA MongoDB (`localhost:27017/stock`) or QA PostgreSQL (`localhost:5432/trading_bot`).
2. **Desktop Claude Code End-to-End Verification (Exit 1)**
- After runnable MCP entry-point wiring lands, connect desktop Claude Code against the read-only Studio library (`~/repos/studio/catalog/quant/library/library.yml`) and isolated PostgreSQL.
- Exercise all six MCP tools: run a PIT fundamentals + alt-data signal study and an event study, verify actual `marimo check`-clean static HTML export, and retrieve the filed finding with its trial and artifact references.
3. **Live `quant` QuestDB `10.2.0` Preflight, Load & Latency Verification (Exit 3)**
- **Host & schema precheck:** Verify on `quant`: QuestDB `10.2.0` image, `vm.max_map_count >= 1048576`, container `ulimits.nofile = 1048576`, memory limits, and pre-created `PARTITION BY MONTH` WAL tables with documented dedup keys (`(ts, listing_id)` for `bars_1m`, `(ts, pair)` for `fx_1m`).
- **Small live preflight per shard type (before bulk load):** Because `tools/curate-etl/src/cli.rs:175` documents that ILP v2 binary double encoding over TCP on QuestDB `10.2.0` is still unverified live, send one small sample shard for each shard type (`bars_1m`, `bars_1m_qm`, `fx_1m`) via `send-ilp` first. Confirm committed row counts, decoded OHLCV/FX numeric values and timestamps, and healthy WAL state (`wal_tables()`) through PGWire before starting the bulk load.
- **Full bulk load & reconciliation:** Run `send-ilp` for `bars_1m`, `bars_1m_qm`, and `fx_1m`; reconcile source counts vs. QuestDB PGWire row counts and WAL state (TCP `send-ilp` success confirms socket delivery only, not committed rows), and verify overlapping EOD/QM bar dedup and repeat-load idempotency.
- **Split-boundary verification:** Compare `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split-boundary `bars_1m` session closes against independently sourced raw `bars_1d` closes (`<= 0.5%`).
- **Read latency benchmark & explicit scope:** Benchmark a pinned 1-year single-listing `1m` read (`adjustment: 'raw'`) at **`< 250 ms` warm / `< 1 s` cold** using the real PGWire-backed reader path: `QuestDBClient.query(sql, params)` (`libs/data/questdb/src/client.ts`) injected as `QuestDbQueryExecutor` into `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`), optionally composed via `createRoutedMarketDataStore({ daily, intraday })`. Record listing ID, date range, row count, elapsed times, and cache conditions. **Scope note:** Until equity `1m` routing is wired into `openResearchCopilotStore` and the desktop MCP entrypoint (Section 3, item 5), this benchmark measures the **standalone PGWire-backed reader path**, not a running copilot application; re-verify through the running application once consumer wiring lands.