This commit is contained in:
Boki 2026-11-26 22:23:07 -05:00
parent c353ddbe01
commit ce9e2df67c
310 changed files with 2550 additions and 36861 deletions

237
docs/DATA-CONTRACTS.md Normal file
View file

@ -0,0 +1,237 @@
# Stock Bot — Data, Security Master & Storage Contracts
Authoritative specification for `data-pipeline`, PostgreSQL reference schemas, DuckDB/Parquet + QuestDB `10.2.0` curated tables, and `MarketDataStore`. Every rule below was verified against live QA MongoDB (`stock`, 31 collections) on 2026-11-26.
---
## 1. Empirical Provider Rules & Traps (QA MongoDB `stock`)
`data-pipeline` connects strictly read-only via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`). Never trust raw field names without applying the provider-specific transformations below:
| Collection (Docs) | Verified Empirical Behavior | Mandatory `data-pipeline` Rule |
| --- | --- | --- |
| `eodPrices` (`845.7M`) | `open/high/low/close` are **raw**, **but `volume` is retroactively split-adjusted** (`NVDA` pre-10:1 split `2024-06-07` has `close=1208.88`, `volume=412.39M` = $10\times$ raw; `X.TO` pre-5:1 split has $5\times$ raw volume). Indexes: `{date:1, eodSearchCode:1}` and `{eodSearchCode:1}` (no `{eodSearchCode:1, date:1}`). | Divide historical `volume` by cumulative post-bar split factor so `close * raw_volume` equals true dollar volume; cross-check against `qmPrices.sharevolume`. Query cross-sectional slices by `date` first when scanning MongoDB. |
| `qmPrices` (`51.5M`) | `unadjustedopen..unadjustedclose` and `sharevolume` are **genuinely raw** (both price and share count). Index: `{qmSearchCode:1, date:1}`. | Use as primary raw-volume truth and cross-check partner for `eodPrices`. |
| `eodIntraday1M` (`3.40B`) | **OHLCV is ALREADY retroactively split-adjusted** (`NEXM.V` pre-1:20 reverse split on `2025-06-18` reports `close=24.29` instead of raw `~1.21`). Covers US deeply back to Dec 2003; sparse/empty on many TSX tickers (`SHOP.TO` has `0` rows). | Un-adjust pre-split OHLCV using cumulative split factors before writing raw `bars_1m` (or never re-apply `adj_factors` on top without un-adjusting first!). Verify `1m` session close vs raw `bars_1d.close`. |
| `qmIntraday` (`173.3M`) | Stores **both** raw (`open..close`, `sharevolume`) and adjusted (`adjustedopen..adjustedclose`, `avolume`). Covers TSX/CA (`SHOP:CA`, `X:CA`) from ~May 2024 onward. | Primary `1m` intraday source for Canadian listings where `eodIntraday1M` is empty, and split-calibration truth for overlapping symbols. |
| `eodSymbols` (`317.8k`) | `103.8k` rows have composite `eodExchange="US"`, of which **`44,970` (`43.3%`) have `Exchange="NMFQS"` (mutual funds)**, `18,114` `PINK`, `15,858` `NASDAQ`, `9,879` `NYSE`. `52,745` US + `3,136` CA rows have `delisted=true`. EOD retroactively renames changed tickers (`META.US` holds 2012–2022 Facebook; `FB.US` is now a 2025 ProShares ETF) and overwrote pre-bankruptcy `GM.US` (`starts 2010-11-18`) and `HTZ.US` (`starts 2021-07-01`). | Resolve US MIC from `eodSymbols.Exchange` (not `eodExchange="US"`); exclude `NMFQS` from equity universes; never assume `Code.US` is a single historical company without checking bar spans and `qmFilings`. |
| `ibSymbols` (`18,402`) | Fields use **`exchangeId`** and **`description`** (which legacy `provider-symbol.ts` ignored). `100%` ISIN/CUSIP/`conid`, **but `exchangeId` is an execution/ATS venue, NOT primary listing MIC**: CA has `AEQLIT=2,506` (`65%`) vs `TSE=514`; US has `OTCLNKECN=6,627`, `ARCAEDGE=1,067`, `BEX=777`, `DRCTEDGE=682`, `IEX=509` vs **`NYSE=370` (`2.5%`) and `NASDAQ=241` (`1.7%`)**! Contains placeholder/checksum-bad ISINs (`CATSETEST001`, `CA00149WBAD4`, `CA8131391062` for `SCU.UN`). | **Never block `ibSymbols` on MIC.** Validate ISIN Luhn check digit (derive `US`/`CA` + CUSIP + check digit when ISIN checksum fails on a valid 9-char CUSIP), match globally to `instrument`, and attach `conid` to `listing` by `(instrument_id, currency)`. |
| `qmSymbols` (`47,243`) | `0%` ISIN/CUSIP; `15,790` US + `3,626` CA rows have `active=false`. Contains duplicate `(symbol, exchange)` pairs on CSE (`VOY:CNX` active + `VOY:CC` inactive). | Disambiguate via `active` flag, `qmSearchCode`, and observed `[first_bar_date, last_bar_date]` overlap. |
| `ceoSymbols` (`12,589`), `ceoPosts` (`14.78M`), `ceoShorts` (`692.9k`) | 100% Canadian (`CNQ=4,583`, `TSX=4,127`, `CDX=3,292`, `AQL=587`). `ceoSymbols.symbol` embeds `.TO`/`.V` suffixes. `ceoPosts` has `1.8%` edited posts (`edited != null` mutates `spiel`) and `bot="1"` (`@thenewswire`). `ceoShorts.timestamp` is the 15th / month-end **report period date**, NOT CIRO dissemination date. | Map `TSX→XTSE`, `CDX→XTSX`, `CNQ→XCNQ`, `AQL→NEOE`; strip embedded `.TO`/`.V`; separate `bot="1"` posts and set text `known_at = COALESCE(edited, timestamp)`; set `ceoShorts` `known_at = timestamp + 4 Canadian business days (17:00 ET)`. |
| `qmFinancials` (`1.86M`), `qmFinancials-old` (`908k`) | Standardized `BalanceSheet`, `CashFlow`, `IncomeStatement`, `periodEndDate`, `reportDate` — **`0%` `filingDate` and `0` restatement versions** (overwritten in place). | Derive `known_at` by joining `(listing_id, periodEndDate)` to `qmFilings.timefiled`; where unlinked, add statutory deadline lag (`+45d Q / +90d FY` US & TSX; `+60d Q / +120d FY` TSXV/CSE) with `known_at_source = 'statutory_lag_estimate'`. |
| `eodFinancialsOLD` (`2.98M`), `eodFundamentalsOLD` (`106.6k`) | `eodFinancialsOLD` sets `filingDate == reportDate` on **`99.26%`** of rows. `eodFundamentalsOLD` has `filing_date: null`, unversioned current valuation ratios, and mislabels USD figures as `"CAD"` on NEO CDRs (`AAPL` CDR `$335B` assets). | **Quarantine `eodFundamentalsOLD` `Highlights`/`Valuation` from all backtests.** Use `eodFinancialsOLD` only for pre-QM historical backfill with mandatory statutory lag (ignoring its `filingDate`). |
| `qmFilings` (`30.52M`) | Has exact second-level `timefiled` (`"2025-01-31T06:01:27 EST"`) for both US EDGAR (`10-Q`, `10-K`, `8-K`, `4`, `144`) and **Canadian SEDAR+** (`Interim financial statements/report`, `Annual financial statements`, `MD&A`, `52-109`, `NI 43-101`, `45-106F1`). Metadata + external download URLs only (no parsed Form 4 share counts). | Primary `known_at` clock for `qmFinancials` and `qmEarnings`, plus standalone filing-arrival/form-type event stream. Convert `EST`/`EDT` strings cleanly using `America/New_York` rules. |
| `qmEarnings` (`444.9k`) | `66.94%` (`297,779`) have `announceTime="N/A"` (`80,481` `AMC`, `66,605` `BTO`); `consensusEps` is overwritten post-hoc. | Link to same-day `qmFilings` `8-K` / `News release` `timefiled`; if still unknown, set `known_at = reportDate 16:05 ET` (tradable `T+1` open). |
| `qmDividends` (`495.9k`), `qmSplits` (`18.8k`), `eodSymbolChange` (`230`) | `qmDividends`: `82.3%` have `declared < date`, bogus `usdFxRate: 1` on CAD rows. `qmSplits`: `30.1%` have `declared`, `258` have `splitratio == 1`. `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; never rely on `eodSymbolChange` for multi-year ticker history. |
| `teData` (`14.8k`), `teMarketData` (`435`), `CAD.FOREX` | `teData` has `{d, v}` final-revised values only (no release dates/vintages). `CAD.FOREX` (`eodPrices` `12,109` 1d, `eodIntraday1M` `5.20M` 1m) + `teMarketData.USDCAD` (`2,865` 1d through Apr 2026) already provide complete USD/CAD history. | Lag `teData` (`+1d` central-bank rates, `+35d` monthly CPI/NFP, `+65d/+90d` GDP) for coarse regime filters only. Curate `CAD.FOREX` + `teMarketData.USDCAD` directly into `fx_1d` and `fx_1m`. |
---
## 2. Security Master Schema (PostgreSQL)
Applied via `@stock-bot/postgres` (`master` migration track; no `\c` meta-commands):
```sql
CREATE TABLE IF NOT EXISTS exchange (
mic VARCHAR(10) PRIMARY KEY, -- ISO 10383 (e.g. XNYS, XNAS, XTSE, XTSX, XCNQ, NEOE, OTCM)
operating_mic VARCHAR(10) NOT NULL,
name TEXT NOT NULL,
country_iso CHAR(2) NOT NULL,
currency CHAR(3) NOT NULL,
timezone TEXT NOT NULL, -- e.g. 'America/New_York', 'America/Toronto'
calendar_code VARCHAR(16) NOT NULL,
board_lot_policy VARCHAR(16) NOT NULL DEFAULT 'us_100', -- 'us_100' | 'tsx_tiered' | 'fx'
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS exchange_source_map (
source VARCHAR(16) NOT NULL, -- 'eod' | 'qm' | 'ib' | 'ceo'
source_code VARCHAR(32) NOT NULL,
role VARCHAR(20) NOT NULL, -- 'primary_venue' | 'composite' | 'ats_routing' | 'forex' | 'excluded_fund'
mic VARCHAR(10) REFERENCES exchange(mic),
country_iso CHAR(2),
method VARCHAR(32) NOT NULL,
reviewed_by TEXT,
PRIMARY KEY (source, source_code)
);
CREATE TABLE IF NOT EXISTS instrument (
instrument_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
primary_isin CHAR(12) UNIQUE,
primary_cusip CHAR(9),
canonical_name TEXT NOT NULL,
security_type VARCHAR(16) NOT NULL, -- 'common'|'preferred'|'unit'|'warrant'|'right'|'etf'|'cdr'|'fx'
issuer_country CHAR(2),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS instrument_identifier_history (
instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id),
id_type VARCHAR(8) NOT NULL, -- 'ISIN' | 'CUSIP'
id_value VARCHAR(16) NOT NULL,
valid_from DATE,
valid_to DATE,
source VARCHAR(16) NOT NULL,
PRIMARY KEY (id_type, id_value, valid_from)
);
CREATE TABLE IF NOT EXISTS listing (
listing_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id),
mic VARCHAR(10) NOT NULL REFERENCES exchange(mic),
ticker_root VARCHAR(24) NOT NULL,
class_suffix VARCHAR(12) NOT NULL DEFAULT '',
currency CHAR(3) NOT NULL,
ib_conid BIGINT,
ib_primary_exchange VARCHAR(16), -- e.g. 'NYSE', 'NASDAQ', 'TSE', 'VENTURE'
listed_from DATE,
listed_to DATE,
delist_reason VARCHAR(24), -- 'active'|'merger_cash'|'moved_to_otc'|'bankruptcy_cancelled'|'unknown_ involuntary'
terminal_return NUMERIC(10, 6), -- e.g. -0.300000 or -1.000000 when no post-delist OTC bar exists
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS corporate_action_continuity (
from_listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
to_listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
effective_date DATE NOT NULL,
kind VARCHAR(24) NOT NULL, -- 'otc_delist_transfer' | 'venue_uplisting' | 'reorg_continuation'
PRIMARY KEY (from_listing_id, effective_date)
);
CREATE TABLE IF NOT EXISTS listing_symbol_history (
listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
ticker VARCHAR(32) NOT NULL,
valid_from DATE NOT NULL,
valid_to DATE,
source VARCHAR(16) NOT NULL,
PRIMARY KEY (listing_id, ticker, valid_from)
);
CREATE TABLE IF NOT EXISTS provider_mapping (
source VARCHAR(16) NOT NULL,
source_id VARCHAR(64) NOT NULL, -- eodSearchCode, qmSearchCode, ib conid/id, ceoId
valid_from DATE NOT NULL DEFAULT '1900-01-01',
valid_to DATE,
listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
method VARCHAR(24) NOT NULL, -- 'tier1_isin'|'tier2_cusip'|'tier3_ticker_span'|'tier4_name'|'override'
confidence NUMERIC(4, 3) NOT NULL,
price_corr NUMERIC(5, 4),
PRIMARY KEY (source, source_id, valid_from)
);
```
Plus `resolution_conflict`, `override` (keyed by `(source, source_id, valid_from)` and applied last with precedence `1.000`), and `golden_field_audit`.
---
## 3. Curated Storage Schemas
### A. DuckDB + Hive Parquet (`/mnt/data/stockbot/curated/`)
All Parquet files use `ZSTD` compression, integer `listing_id` (`INT32`), UTC `TIMESTAMPTZ` (`ts`, `known_at`), and explicit `known_at_source`:
- **`bars_1d/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, session_date DATE, open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume DOUBLE, vwap DOUBLE, currency VARCHAR, source VARCHAR, known_at TIMESTAMPTZ)` — strictly raw OHLC and **un-adjusted** share `volume`, sorted by `(listing_id, session_date)`.
- **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`.
- **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`.
- **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, <standardized statement columns...>)`.
- **`fundamentals_pit/year=YYYY/part.parquet`**: Wide pre-resolved point-in-time snapshots keyed by `(listing_id INT32, effective_known_at TIMESTAMPTZ)` where each row computes:
$$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$
forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2.
- **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`.
- **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`.
- **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`.
- **`fx_1d/part.parquet`**: `(pair VARCHAR, session_date DATE, ts TIMESTAMPTZ, open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, source VARCHAR, known_at TIMESTAMPTZ)`.
- **`features/<feature_name>/v<version>/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, value DOUBLE)`.
### B. QuestDB `10.2.0` (Intraday & Live Streaming)
Image pinned to `questdb/questdb:10.2.0`. `listing_id` is stored as decimal string inside `SYMBOL CAPACITY 65536 NOCACHE` and converted to `number` (`INT32`) at the `MarketDataStore` adapter boundary:
```sql
CREATE TABLE IF NOT EXISTS bars_1m (
listing_id SYMBOL CAPACITY 65536 NOCACHE,
open DOUBLE,
high DOUBLE,
low DOUBLE,
close DOUBLE,
volume DOUBLE,
vwap DOUBLE,
session SYMBOL CAPACITY 8 CACHE, -- 'PRE' | 'RTH' | 'POST'
source SYMBOL CAPACITY 8 CACHE, -- 'eod_unadj' | 'qm_raw' | 'ib_live'
known_at TIMESTAMP,
ts TIMESTAMP
) TIMESTAMP(ts) PARTITION BY DAY WAL
DEDUP UPSERT KEYS(ts, listing_id);
CREATE TABLE IF NOT EXISTS fx_1m (
pair SYMBOL CAPACITY 32 CACHE, -- 'USD.CAD'
open DOUBLE,
high DOUBLE,
low DOUBLE,
close DOUBLE,
source SYMBOL CAPACITY 8 CACHE,
ts TIMESTAMP
) TIMESTAMP(ts) PARTITION BY MONTH WAL
DEDUP UPSERT KEYS(ts, pair);
CREATE TABLE IF NOT EXISTS bar_revisions (
listing_id SYMBOL CAPACITY 65536 NOCACHE,
timeframe SYMBOL CAPACITY 8 CACHE,
bar_ts TIMESTAMP,
prev_close DOUBLE,
new_close DOUBLE,
prev_volume DOUBLE,
new_volume DOUBLE,
revised_at TIMESTAMP
) TIMESTAMP(revised_at) PARTITION BY MONTH WAL;
```
---
## 4. `MarketDataStore` Contract
```ts
export type DataScope = 'vault_fenced' | 'vault_evaluation_only';
export interface MarketDataStore {
bars(q: {
listingIds: number[];
timeframe: '1m' | '5m' | '1h' | '1d';
from: string;
to: string;
adjustment: 'raw' | 'split' | 'total';
asOf?: string;
scope?: DataScope; // defaults to 'vault_fenced'; 'vault_evaluation_only' requires human operator Vault token
}): AsyncIterable<BarBatch>;
crossSection(q: {
features: string[]; // versioned refs, e.g. 'rsi_14@v1'
date: string;
universe: UniverseRef;
asOf?: string;
}): Promise<Table>;
fundamentalsAsOf(q: {
listingIds: number[];
fields: string[];
asOf: string;
allowEstimatedLag?: boolean; // default true for daily/swing, false for intraday event triggers
}): Promise<Table>;
events(q: {
kinds: EventKind[];
listingIds?: number[];
from: string;
to: string;
asOf?: string;
}): Promise<Table>;
shortsAsOf(q: { listingIds: number[]; from: string; to: string; asOf?: string }): Promise<Table>;
macroAsOf(q: { countries: string[]; indicators: string[]; from: string; to: string; asOf?: string }): Promise<Table>;
fx(q: { pair: 'USD.CAD'; timeframe: '1m' | '1d'; from: string; to: string }): Promise<Table>;
universe(q: { ref: UniverseRef; date: string }): Promise<number[]>; // survivorship-free active listings on date
}
```
**Hard adapter invariant:** When `scope !== 'vault_evaluation_only'`, the adapter clamps `to` and `asOf` to `< VAULT_CUTOFF_TS` (rejecting requests with `from >= VAULT_CUTOFF_TS` with `VaultHoldoutFenceError`).

164
docs/MILESTONES.md Normal file
View file

@ -0,0 +1,164 @@
# Stock Bot — Execution Milestones (`M0` → `M5`)
Actionable build tracker for turning Stock Bot into the AI algo research & IB live trading platform defined in [PLATFORM-PLAN.md](PLATFORM-PLAN.md).
**Sequencing rule:** Build **Vertical Slice 1 (`M0` + `M1`)** before touching multi-asset Rust internals or greenfield UI dashboards. That puts you and desktop Claude Code onto real survivorship-clean US+CA daily, filing, and short-interest signal research by Week 3.
---
## Explicit Scope Cuts & Deferrals
- **Cut:** Dual-backend QuestDB ↔ DuckDB parity harness (storage is split cleanly by workload from Day 1: DuckDB+Parquet for daily/PIT/features; QuestDB `10.2.0` for `1m` intraday/hot bars).
- **Cut:** `eodFundamentalsOLD` scrape-time valuation snapshots in backtests (look-ahead + corrupted CDR currencies).
- **Cut:** Macro release/surprise event studies on `teData` (no release timestamps or initial vintages exist in raw data; `teData` is restricted to lagged regime tags).
- **Cut:** `ttFutures` (corrupted dates and separate contract-roll/margin domain; revisit post-`M5`).
- **Defer to `M4`:** React Merge Review UI (use generated CSV/Markdown conflict reports + SQL `override` seed files in `M1`), greenfield `Home`/`Markets` pages, and custom Knowledge Base CRUD (mount `~/repos/studio/catalog/quant/library/library.yml` read-only via MCP).
- **Defer to post-`M5`:** Multi-host distributed research worker pool (`quant` has 24 threads + 125 GiB RAM + 3.6 TiB NVMe on one box) and Form 4 XML / SEDI insider dollar-size parsing.
---
## M0 — Safety, Migrations & Gate Lock *(Days 1–3)*
**Goal:** Every repo gate passes, dev/QA database isolation is airtight at both client and server layers, secrets and holdout export leaks are closed, and schema migrations work across `data-pipeline` and `web-api`.
### Checklist
- [ ] **Fix failing baseline gates:**
- Update `scripts/test/workspace.test.ts:85` for `docker-compose.dev.yml` default in `scripts/docker.sh`.
- Fix all 65 ESLint issues (`59` `curly` + `2` non-null warnings in `apps/stock/data-pipeline/scripts/phase1-inventory.ts`; `4` `curly` errors in `apps/stock/config/src/env-safety.ts`, `libs/core/di/src/container/builder.ts`, `libs/data/mongodb/src/client.ts`).
- Delete the 6 stray root files (`tetest.ts`, `test-queue.ts`, `proxy-playwrite.ts`, `test-rust-strategies.js`, `test-typescript-strategy.js`, `test-e2e-backtest.sh`).
- [ ] **Fix PostgreSQL init & shared migration runner:**
- Strip hardcoded `CREATE DATABASE trading_bot` and `\c trading_bot;` from `database/postgres/init/01-init-database.sql` through `05-add-visible-column.sql` so `docker-compose.dev.yml` (`trading_bot_dev` on `5433`) and `docker-compose.prod.yml` initialize master tables in `$POSTGRES_DB`.
- Extract `runMigrations` from `apps/stock/web-api/src/migrations/migration-runner.ts` into `@stock-bot/postgres` (`libs/data/postgres`) with `master` and `research` migration tracks + `bun run db:migrate`.
- [ ] **Close `MongoDBClient` `readOnly` bypass & `env-safety.ts` gaps:**
- Block or read-only-proxy `getDatabase()`, `getDb()`, `database`, `getCollection()`, and `collection()` in `libs/data/mongodb/src/client.ts` when `readOnly: true`.
- Delete legacy MongoDB-writing `apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts` (and its route hook in `web-api`).
- Change `apps/stock/config/src/env-safety.ts:86-94` from `logger.warn` to `throw new Error` when `dataPipeline` targets port `27017` without `readOnly: true` or with `trading_admin`, and check `port === 27017` even when URI omits `/stock`.
- Default `QUEUE_ENABLE_SCHEDULED_JOBS=false` outside explicit ingestion deployments so starting `data-ingestion` never triggers background crawls unintentionally.
- [ ] **Purge hardcoded credentials & close `sb-research.*` holdout leak:**
- Rotate and remove the hardcoded Webshare proxy URL in `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` (read from env only) and extend `scripts/audit-secrets.ts` to catch `http(s)://user:pass@` literals; also fix `fetch-symbols.action.ts:108` (`ib_symbols` → `ibSymbols`).
- Remove `GET /api/v2/datasets/canonical/:hash/export` from `sb-research.*` permissions in `apps/stock/web-api/src/services/research-agents.service.ts:51` and scope agent `GET` routes to granted projects/templates.
### Exit Criteria
1. `CARGO_BUILD_JOBS=2 bun run check` passes all 11 gates (`0` errors, `0` warnings).
2. Fresh `trading_bot_dev` container (`5433`) contains both master (`02`–`05`) and research (`06`–`33`) tables, verified by automated test.
3. Integration test proves `data-pipeline` throws on both `mongoClient.insertOne()` and `mongoClient.getDatabase().collection('x').insertOne()`, and `studio_stock_bot_read` rejects server-side writes.
4. Security test proves `sb-research.*` receives `403` on dataset `/export` and ungranted project `GET`s.
---
## M1 — Vertical Slice 1: Security Master + Honest Daily/Event Signal Lab *(Weeks 1–3)*
**Goal:** Resolve US + Canadian equities into permanent `listing_id`s, curate honest survivorship-aware daily bars + corporate actions + FX + filings/earnings/Canadian shorts into Parquet + DuckDB, enforce the 6-month Vault and `trial_ledger`, and start testing real signals in Python/marimo.
### Checklist
- [ ] **Step 1 — Security Master (`Postgres` + `apps/stock/data-pipeline`):**
- Add DDL migration for `exchange`, `exchange_source_map`, `instrument`, `instrument_identifier_history`, `listing`, `listing_symbol_history`, `corporate_action_continuity`, `provider_mapping`, `resolution_conflict`, `override`, `golden_field_audit` (see [DATA-CONTRACTS.md](DATA-CONTRACTS.md)).
- Implement Pass 1 (ISO 10383 MIC seed + ~320 source exchange mappings; mark EOD `US` composite, EOD `NMFQS` excluded mutual funds, IB `AEQLIT`/`IEX`/`ARCAEDGE`/`OTCLNKECN`/etc. `ats_routing`, CEO `TSX/CDX/CNQ/AQL` → `XTSE/XTSX/XCNQ/NEOE`) and review once via committed seed SQL.
- Implement Pass 2 normalization (fix `provider-symbol.ts` for IB `exchangeId`/`description`; ticker root/suffix parser; ISIN Luhn validator + CUSIP→ISIN derivation; precompute `[first_bar_date, last_bar_date]` per `(source, source_id)`).
- Implement Pass 3 two-stage matching (Stage A: global ISIN/CUSIP → `instrument`; Stage B: EOD/QM venue → `listing`, IB `conid` attached at `(instrument_id, currency)`, temporal bar-span overlap required on Tier 3/4 ticker matches) + Pass 6 OTC delisting chains (`SIVB` → `SIVBQ`).
- Implement Pass 4 batch 25-date cross-sectional price cross-check (`{ date: { $in: sampleDates } }`) and export US+CA match & conflict report + `override` seed file.
- [ ] **Step 2 Core — Daily, Corporate Actions, FX & Events (`Parquet + DuckDB`):**
- Curate `bars_1d` (un-adjusting `eodPrices.volume` via `qmSplits` and cross-checking `qmPrices.sharevolume`).
- Curate `corporate_actions` & `adj_factors` (`qmSplits` excluding `1:1` no-ops, `qmDividends` ignoring bogus `usdFxRate: 1`, plus OTC continuation & `-30%`/`-100%` Shumway terminal delisting events).
- Curate `fx_1d` (`CAD.FOREX` 1971–2025 + `teMarketData.USDCAD` through 2026).
- Curate `events` (`qmFilings` UTC-converted `timefiled` + form groups; `qmEarnings` linked to `qmFilings` or lagged to `16:05 ET` when `announceTime == 'N/A'`) and `shorts` (`ceoShorts` with `+4` Canadian business-day `known_at` lag).
- [ ] **`MarketDataStore` + Rolling 6-Month Vault + `trial_ledger`:**
- Implement `MarketDataStore` (TS) and `stockbot.data` (Python) over DuckDB + Parquet with mandatory `known_at <= asOf` and `ts < VAULT_CUTOFF_TS` (`max_ingested_ts - 6 months`) enforcement.
- Add PostgreSQL `trial_ledger` and `vault_evaluations` tables (protected by `reject_research_evidence_mutation()`) + canonical DSR ($\hat{N}$ effective trials) in `@stock-bot/calculations` (see [VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)).
- [ ] **Signal Analyzer + `marimo` Workspace:**
- Implement `analyze_signal` and `event_study` (IC, rank-IC, quantile spreads, turnover, pre/post-2023 recency split, Newey-West $t$-stat, automatic `trial_ledger` write).
- Stand up `marimo edit ./research/notebooks --watch` (`127.0.0.1:2718`) with marimo agent rules (`CLAUDE.md`) and `marimo check --format=json` pre-commit/CI check.
### Exit Criteria
1. US+CA match report committed: `100%` of exchange codes mapped; $\ge 95\%$ of US/CA equities resolved; `FB` (2012–2022) and `FB` (2025 ETF) have distinct `listing_id`s; `SIVB` chains to `SIVBQ`; `NVDA` pre-split `close * raw_volume` matches `qmPrices` within `1%`.
2. 20y US+CA daily scan + 1 signal IC/quantile/turnover/recency/DSR evaluation finishes in **`< 5 s`** on `quant` without reading any Vault row.
3. End-to-end test runs a Canadian `ceoShorts` / `qmFilings` signal study in `stockbot` Python SDK, logs its return vector to `trial_ledger`, and computes $\hat{N}$-deflated Sharpe.
---
## M2 — MCP Copilot, Intraday QuestDB `10.2.0` & PIT Fundamentals *(Weeks 4–5)*
**Goal:** Connect desktop Claude Code via MCP, curate 2D point-in-time fundamentals (`qmFinancials × qmFilings`) and split-unadjusted `1m` intraday bars (`QuestDB 10.2.0`), and launch the versioned batch Feature Library.
### Checklist
- [ ] **MCP Server (`web-api` / standalone stdio+SSE wrapper):**
- Expose `search_symbols`, `query_data` (vault-fenced), `analyze_signal`, `event_study`, `file_finding`, `read_knowledge` (serving `~/repos/studio/catalog/quant/library/library.yml` + Postgres `findings`/`provider_caveats`).
- [ ] **PIT Fundamentals & CEO Posts (`Parquet + DuckDB`):**
- Join `qmFinancials` (+ `qmFinancials-old`) to `qmFilings.timefiled` (`10-Q`, `10-K`, `40-F`, SEDAR `Interim/Annual financial statements`), applying `+45d/+90d` (US/TSX) and `+60d/+120d` (TSXV/CSE) statutory lags where unlinked (`known_at_source = 'statutory_lag_estimate'`).
- Materialize 2D `(period_end, known_at)` deduplicated wide snapshots + TTM features (`fundamentals_pit`).
- Curate `ceoPosts` (`14.8M`) separating `bot == "1"` newswires from retail posts and guarding `edited != null` text timestamps; curate lagged `teData` regime series.
- [ ] **Intraday Curation (`QuestDB 10.2.0`):**
- Pin `questdb/questdb:10.2.0` in `docker-compose*.yml`; replace legacy `libs/data/questdb` (`LATEST BY` → `LATEST ON`, parameterized PG queries, ILP batch writer).
- Load split-unadjusted `eodIntraday1M` (US 2003–2025), raw `qmIntraday` (CA/US 2024–2025), and `CAD.FOREX` `1m` (`5.2M` bars) into `bars_1m` and `fx_1m` (`listing_id SYMBOL CAPACITY 65536 NOCACHE`, `DEDUP UPSERT KEYS(ts, listing_id)`).
- [ ] **Versioned Feature Library (`D04` reopened):**
- Build declarative SQL/Polars batch runner writing versioned `(listing_id, ts, known_at, value)` columns + `register_signal(...)` SDK entrypoint.
### Exit Criteria
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.
2. Restatement fixture test proves a restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`.
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**.
---
## M3 — Portfolio Backtest v2: Columnar Screener + Multi-Asset Rust Engine *(Weeks 6–9)*
**Goal:** Turn surviving signals into multi-asset long/short US+CA (+ FX) strategies with exact 8-decimal Rust accounting, zero Python→TS indicator translation, full CPCV/DSR/PBO validation, and the human 6-month Vault gate.
### Checklist
- [ ] **Tier 1 Columnar Screener:**
- Vectorized Polars/DuckDB portfolio sweep (`signal × universe × rebalance × cost`), writing full $M_{T \times N}$ return matrices to `trial_ledger` and computing CSCV PBO ($S = 16$).
- [ ] **Tier 2 Rust `financial/` Multi-Asset Upgrades (`apps/stock/engine/src/financial/*`):**
- **Atomic timestamp-slice marks (`F06`):** Update all marks at timestamp `t` before checking `RiskAccount` daily-loss/drawdown latches.
- **Simultaneous `Target` sell-netting:** Credit haircut-adjusted pending `Sell` proceeds toward same-barrier `Buy` reservations in `MatchingAccount::submit`.
- **Feature side-channel & Arrow loader:** Pass precomputed `features` into `Replay` decision barriers and `StrategyContext`; load bars/features from Parquet/Arrow paths instead of Postgres `JSONB` snapshots; remove duplicate `serde_json::Value` parse in `api/canonical.rs`; lift single-series TS gates in `native-worker.ts` and `candidate-sandbox.ts`.
- **Long/short, multi-currency Margin & corporate actions:** Signed positions/targets + borrow fee accrual; `BTreeMap<Currency, Posting>` (`USD`/`CAD` cash & negative margin-loan interest + `FXCONV` sweeps + tradable FX pairs); ex-date splits, cash dividends, TSX/TSXV `100/500/1000` board-lot rounding, and OTC/Shumway delisting liquidations.
- [ ] **Validation Suite & Engine Consolidation:**
- Add Purged Walk-Forward & CPCV (`purge = horizon + warmup`, `embargo = max(5d, 0.01 * T)`), parameter stability surface, capacity (ADV participation), and US/CA factor exposure (`MKT`, `SMB`, `HML`, `MOM`).
- Implement one-shot human **Vault Holdout Gate** (`Validated → Paper`, capped at $\le 10$ evaluations/year in `vault_evaluations`).
- Retire legacy `f64` `BacktestEngine`, legacy TS `SimulationExecution`, and dead `apps/stock/analytics` metric scripts.
### Exit Criteria
1. Rust unit + differential fixtures pass for: atomic hedged mark neutrality, 100%-invested `Sell A + Buy B` target rotation, split + dividend 8-decimal conservation, USD/CAD margin interest, TSX board-lot sizing, and `SIVB` delisting liquidation.
2. 20y US+CA cross-sectional long/short daily backtest (`~5,000+` listings) finishes in **`< 30 s`** on `quant`.
3. A real `M2` signal promoted via `register_signal` runs through `Tier 1 Screen → Tier 2 Rust Engine → CPCV/DSR/PBO/Recency → Human 6m Vault Gate` with zero indicator code duplicated in TypeScript.
---
## M4 — Autonomous Agent Campaigns, Studio Bridge & App Evolution *(Weeks 10–12)*
**Goal:** Run bounded overnight research campaigns safely on `quant`, connect the Studio Quant hypothesis loop, and surface everything cleanly in `web-app`.
### Checklist
- [ ] **Campaign Runner & SQL Budgets:**
- Add `campaigns` table and PostgreSQL `BEFORE INSERT` triggers enforcing cumulative per-campaign and daily trial, bar-evaluation, and wall-clock budgets.
- Package containerized campaign runner (`--network` restricted to Research Kernel API/MCP only; zero DB port or host filesystem access) implementing `Scout`, `Data Analyst`, `Signal Researcher`, `Strategy Builder`, and `Skeptic` workflows + ntfy/Discord notifications.
- [ ] **Studio Bridge:**
- Webhook/API endpoint accepting Studio Quant hypotheses → creating bounded Stock Bot campaigns → posting structured `verdict + DSR + PBO + static HTML link` receipts back to Studio.
- [ ] **Incremental `web-app` Evolution:**
- Wire `/research/agents` into `Sidebar.tsx` and unify `src/components/charts/Chart.tsx` + `SymbolChart.tsx`.
- Ship `Lab` (Signal Analyzer, Event Study, sandboxed `<iframe sandbox="allow-scripts" srcDoc={...}>` HTML viewer + on-demand `marimo run` launcher), `Agents` (live campaigns, budgets, findings/dead-ends feed), `Strategies` (lifecycle + Vault gate), and `Data` (coverage, quality monitors, conflict queue), followed by lightweight `Home` and `Markets` views.
### Exit Criteria
1. Overnight containerized campaign launched from a Studio Quant idea completes unattended on `quant`, stays strictly inside SQL trial budgets, passes `Skeptic` audit checks, and renders static-HTML-backed findings in the `Agents` feed.
2. Attempting to exceed campaign trial/compute caps or access Vault dates from inside the agent container fails closed (`403` / SQL trigger error).
---
## M5 — Paper at Scale → Live Interactive Brokers Margin (`9900K`) *(Weeks 13–16)*
**Goal:** Harden paper execution for long-running multi-asset portfolios, connect headless IB Gateway on the isolated `9900K` server, validate live vs. backtest drift in IB Paper, and go live on small capital.
### Checklist
- [ ] **`paper-host` Hardening (`apps/stock/engine/src/api/paper.rs` & `orchestrator/src/paper/*`):**
- Replace $O(N)$ double genesis receipt replay in `stage_financial_transaction` with periodic compacted state snapshots + bounded tail journal; expose `MatchingReset` over NAPI; run non-builtin paper strategy code inside the `A02` sandbox; lift single-deployment / single-series limits.
- [ ] **IB Gateway & Market Data / OMS Bridge (`9900K`):**
- Deploy headless `IB Gateway` + `IBC` on `9900K` (handling nightly ~21:00 ET resets and `1100 → 1102` re-subscriptions).
- Build `ib-bridge` aggregating `reqRealTimeBars(5s, TRADES)` + L1 `reqMktData` quotes ($\le 80$ active lines) into post-grace closed bars; pin `(conid, currency, exchange="SMART", primaryExchange)` from `listing`; route cash sweeps via `FXCONV` and FX alpha trades via `IDEALPRO`; implement idempotent client order IDs, partial fills, TSX `15:40 ET` / US `15:50 ET` auction cutoffs, and continuous position/cash reconciliation.
- [ ] **Risk, Kill Switches & Dual Drift Monitor:**
- Global + per-strategy exposure, daily-loss, drawdown, and order-rate kill switches + `Trading` UI controls.
- Implement **Execution Drift** (live IB fills vs. Rust replay on *recorded IB bars/quotes*) and **Feed Basis Drift** (Rust replay on *recorded IB bars* vs. next-day *curated EOD/QM bars*), with automatic demotion proposals when outside bounds.
### Exit Criteria
1. `paper-host` processes `100,000` sequential quotes with flat **`< 5 ms` p99** latency.
2. Strategy runs $\ge 30$ trading days and $\ge 50$ trades on IB Paper across US (`USD`) + TSX (`CAD`) listings, surviving nightly IB Gateway resets with `0` unrecovered reconciliation mismatches and Execution Drift **`<= 15 bps/trade`**.
3. Small-capital live deployment passes pre-flight kill-switch, partial-fill, `FXCONV`, and reconciliation drills with explicit operator approval.

376
docs/PLATFORM-PLAN.md Normal file
View file

@ -0,0 +1,376 @@
# Stock Bot — AI Algo Research Platform Plan
As of 2026-11-26 (revised post-audit). Owner: Boki.
Stock Bot becomes a personal **edge factory**: ideas go in, AI agents test them at scale on honest point-in-time data, you explore alongside them, and survivors move through paper trading to live trading on Interactive Brokers — then get monitored until their edge decays.
Companion specs:
- **[MILESTONES.md](MILESTONES.md)** — executable milestone checklist (`M0` → `M5`), scope cuts, and exit criteria.
- **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** — raw provider quirks, security-master DDL, `known_at` rules, and Parquet/QuestDB schemas.
- **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** — canonical metrics, trial ledger ($\hat{N}$ DSR & PBO), 6-month Vault, recency gate, and IB/TSX execution rules.
---
## Contents
1. [Vision and principles](#1-vision-and-principles)
2. [Where the project stands](#2-where-the-project-stands)
3. [Decisions log](#3-decisions-log)
4. [System architecture](#4-system-architecture)
5. [Data architecture and storage](#5-data-architecture-and-storage)
6. [Step 1 — Cross-source merge (security master)](#6-step-1--cross-source-merge-security-master)
7. [Step 2 — Processing the remaining datasets](#7-step-2--processing-the-remaining-datasets)
8. [Feature library](#8-feature-library)
9. [Backtesting](#9-backtesting)
10. [Orchestration](#10-orchestration)
11. [Research and analytics playground](#11-research-and-analytics-playground)
12. [Agent layer](#12-agent-layer)
13. [Execution: paper to live on IB](#13-execution-paper-to-live-on-ib)
14. [The app](#14-the-app)
15. [Strategy lifecycle](#15-strategy-lifecycle)
16. [Roadmap](#16-roadmap)
---
## 1. Vision and principles
The real product is **trustworthy evidence produced fast**. Most retail algo work fails because results look good and are not real. The edge comes from:
- **Rigor at scale** — agents can run thousands of tests; the platform makes sure the statistics account for that and penalize pre-LLM regime decay.
- **Data few others combine** — 14.8M CEO.ca posts, 30.5M US/Canadian filings with second-level timestamps, 693k CIRO short records, fundamentals, dividends, splits, earnings, 54 years of USD/CAD (`5.2M` 1m bars), and `3.4B` 1m bars across US and Canadian markets.
- **Capacity-constrained niches** — Canadian small/mid-caps (`TSX`/`TSXV`/`CSE`), cross-border US/CA interlisted pairs, and filing/short/retail-flow events where institutional AI pods cannot deploy size.
- **Research speed** — "is there something here?" answered in seconds over Parquet + DuckDB, before writing a line of strategy code.
- **Execution quality** — one Rust financial kernel for portfolio backtest, paper, and live IB execution, paired with dual drift monitoring.
Ideas come from two places: you, and the Quant profile in Studio (`~/repos/studio`). Agents test them. You research alongside them. Everything that can give an edge is in scope: intraday, swing/daily, cross-sectional equity portfolios, FX, and event/alt-data strategies.
### Design principles
1. **Point-in-time everything — with honest provenance.** Every query answers "as known at time T": universe membership, prices, fundamentals, events. Where raw vendors omit true availability timestamps, the pipeline applies conservative statutory/publication lags and tags `known_at_source` (`filing_timestamp` vs `statutory_lag_estimate`) so strategies never unknowingly trade estimated timestamps at intraday precision.
2. **Single source of truth per calculation.**
- **Rust (`apps/stock/engine/src/financial`)** owns all accounting, cash/margin, corporate actions, fills, risk, and replay.
- **`@stock-bot/calculations`** owns canonical return/drawdown/Sharpe/DSR/PBO statistics served by the Research Kernel API.
- **Batch feature jobs** compute versioned features once; Python notebooks, the Tier 1 screener, and Tier 2 TypeScript/Rust strategies all consume the exact same materialized feature values.
3. **Signal-first, not strategy-first.** Research starts with "does this signal predict anything?" Strategies are built only on signals that survived cost, regime, and recency checks.
4. **Every trial counts.** An immutable trial ledger records every signal analysis, screen, and backtest with its return/IC vector. Significance is adjusted for effective independent trials $\hat{N}$ (Deflated Sharpe Ratio) and Combinatorial Symmetric Cross-Validation (PBO), backed by a rolling **6-month Air-Gapped Vault** and a **Post-2023 Recency Gate**.
5. **Agents and you use the same tools.** One Research Kernel API, one MCP surface, one Python SDK. Autonomous campaign agents run in network-isolated containers with no host shell or direct DB port access.
6. **Rigor lives in the engine, not the UX.** Keep receipts, fencing, and provenance underneath. Make the surface fast and playful.
7. **Raw stays raw.** MongoDB is the provider landing zone. Only `data-pipeline` reads it via `MONGODB_READ_URI` (`studio_stock_bot_read`).
8. **Stable identity.** Everything downstream keys on permanent integer `listing_id` (or ISO country / currency pair), never on mutable tickers.
---
## 2. Where the project stands
The October engineering backlog closed at **113 done / 5 deferred (`D04`, `P03`, `P05`, `P06`, `CL21`) / 4 merged = 122 retained tasks**, delivering:
- the canonical fixed-decimal Rust financial kernel (`Ledger`, `RiskAccount`, `MatchingAccount`, `Replay`);
- canonical single-asset research with 3-phase chronological validation, walk-forward, and cost sensitivity;
- an isolated Linux Docker + seccomp + Rust PID1 guardian sandbox for agent-written TypeScript (`A02`);
- scoped `sb-research.*` agent credentials (`A01`) and a typed `ResearchClient`;
- a 1/2/4-slot worker pool and human-reviewed paper deployments;
- full `quant` server deployment (`12900K`, 24 threads, 125 GiB RAM, 4 TB WD Black SN850X NVMe at `/mnt/data/stockbot`).
### Baseline gates & Phase 0 findings (2026-11-26)
9 of 11 repository gates pass on the current working tree; audit uncovered specific Phase 0 items that must land before Phase A:
- **Failing gates:** `test:tooling` (`178 pass, 1 fail` — `scripts/test/workspace.test.ts:85` expects `docker-compose.yml` after `scripts/docker.sh` switched default to `dev`) and `lint:check` (`63 curly errors + 2 warnings = 65`: `61` in `phase1-inventory.ts`, `4` in WIP files).
- **Dev PostgreSQL init bug:** `database/postgres/init/01`–`05` hardcode `\c trading_bot;`, leaving `trading_bot_dev` (`5433`) with zero master/pipeline tables on fresh startup.
- **Read-only MongoDB bypass:** `MongoDBClient.getDatabase()`/`collection()` (`libs/data/mongodb/src/client.ts`) expose unwrapped driver objects bypassing `mongoReadOnly`, used by legacy `sync-ib-exchanges.operations.ts`; `env-safety.ts` warns instead of throwing when `dataPipeline` uses `trading_admin`.
- **Credential & holdout leaks:** `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` contains a hardcoded proxy URL credential; `research-agents.service.ts:51` allows `sb-research.*` tokens to call `/api/v2/datasets/canonical/:hash/export` (leaking holdout bars) and lacks cumulative lifetime/campaign trial caps; `data-ingestion` runs scheduled crawls on boot unless `QUEUE_ENABLE_SCHEDULED_JOBS=false`.
- **Stray root files to remove:** `tetest.ts`, `test-queue.ts`, `proxy-playwrite.ts`, `test-rust-strategies.js`, `test-typescript-strategy.js`, `test-e2e-backtest.sh`.
### Raw data inventory (QA MongoDB `stock` — 31 collections)
| Provider | Collections (documents) | Key Audit Notes |
| --- | --- | --- |
| **EOD** | `eodSymbols` 318k, `eodExchanges` 76, `eodPrices` 846M, `eodIntraday1M` 3.40B, `eodIntraday5M` 1.08B, `eodIntraday1H` 110M, `eodSymbolChange` 230, `eodFundamentalsOLD` 107k, `eodFinancialsOLD` 2.98M | `eodPrices` has raw OHLC + **split-adjusted `volume`**; `eodIntraday1M` (US back to 2003) has **split-adjusted OHLC**; `CAD.FOREX` has `12.1k` 1d + `5.2M` 1m USD/CAD bars; `eodSymbolChange` only covers Aug 2024–Jul 2025 US; `eodFinancialsOLD` sets `filingDate == reportDate` on 99.3% of rows. |
| **QM** | `qmSymbols` 47k, `qmExchanges` 25, `qmPrices` 51.5M, `qmIntraday` 173M, `qmFinancials` 1.86M, `qmFinancials-old` 908k, `qmFilings` 30.5M, `qmEarnings` 445k, `qmDividends` 496k, `qmSplits` 18.8k | `qmPrices` has raw OHLC + **raw `sharevolume`**; `qmIntraday` covers TSX/CA 1m (from May 2024) with both raw & adjusted columns; `qmFilings` holds US EDGAR + **Canadian SEDAR+** `timefiled` to the second (no parsed Form 4 share counts); `qmFinancials` has `0%` `filingDate` and `0` restatements (rescued via `qmFilings` join). |
| **IB** | `ibSymbols` 18.4k, `ibExchanges` 214 | `100%` ISIN, `99.98%` CUSIP, `100%` `conid`; `exchangeId` records execution/ATS venues (`AEQLIT`, `ARCAEDGE`, `IEX`, `OTCLNKECN`), **not** primary listing MICs (`NYSE`=370, `NASDAQ`=241, `TSE`=514). |
| **CEO** | `ceoSymbols` 12.6k, `ceoExchanges` 4, `ceoPosts` 14.8M, `ceoShorts` 693k | 100% Canadian (`TSX`, `CDX`, `CNQ`, `AQL`); `ceoShorts` back to Apr 2017 (stamps 15th/month-end report dates, requiring `+4bd` CIRO publication lag); `ceoPosts` has 1.8% edited posts (`edited != null`) and `@thenewswire` bot accounts. |
| **TE** | `teCountries` 198, `teIndicators` 163, `teData` 14.8k, `teMarketData` 435, `teUrls` 2.4M | `teData` stores `{d, v}` final-revised series only (no release dates or vintages → lagged regime use only); `teMarketData` includes `USDCAD` daily bars through Apr 2026. |
| **TT** | `ttFutures` 1.46M | Individual historical contracts with corrupted date strings (`"NaN-at-e\""`, `"2001-/0-2/"`) → deferred out of scope. |
---
## 3. Decisions log
| # | Decision | Status |
| --- | --- | --- |
| **D1** | **Storage split:** Curate daily bars, corporate actions, PIT fundamentals/events/shorts/macro, FX, and versioned features directly into **Hive Parquet + DuckDB** behind `MarketDataStore`. Reserve **QuestDB `10.2.0`** (`SYMBOL CAPACITY 65536 NOCACHE`) for `1m`/`5m`/`1h` intraday and hot live/paper bars. No dual-backend parity harness. | Settled (2026-11-26) |
| **D2** | **Copilot:** Desktop first — Claude Code / Claude Desktop connected through an MCP server. Autonomous campaign agents run in network-isolated containers with MCP-only access. | Settled (2026-11-26) |
| **D3** | **Markets:** Multi-market, with US + Canada (and USD/CAD + G10 spot FX) as priority; `ttFutures` out of scope. | Settled (2026-11-26) |
| **D4** | **Web app:** Evolve incrementally alongside backend phases; no rewrite. | Settled (2026-11-26) |
| **D5** | **First step:** Cross-source entity resolution in `data-pipeline` (two-stage: global ISIN/CUSIP → `instrument`, EOD/QM venue → `listing`, IB `conid` attached at `(instrument_id, currency)`). | Settled (2026-11-26) |
| **D6** | **End state:** Paper → live on **Interactive Brokers Margin account** (`USD` + `CAD` cash/margin sub-ledgers, `FXCONV` sweeps, `IDEALPRO` when trading FX alpha, $\le 80$ active intraday streaming symbols on isolated `9900K` host). | Settled (2026-11-26) |
| **D7** | **Strategy scope:** Intraday, swing/daily, cross-sectional long/short equity portfolios, FX, and event/alt-data strategies (excluding macro-release surprises and insider dollar-volume in v1). | Settled (2026-11-26) |
| **D8** | **Research playground:** Market intelligence, exploration lab, strategy tearsheets, and agent lab feed — delivered incrementally starting with Signal Lab + MCP. | Settled (2026-11-26) |
| **D9** | **marimo** confirmed for Python labs: `marimo edit --watch --mcp` on separate loopback origin (`127.0.0.1:2718`), zero-RAM `marimo export html` snapshots in the Agent Feed, `_`-prefixed local variables, and mandatory `marimo check` AST/DAG gating. | Confirmed (2026-11-26) |
| **D10** | **Holdout & recency defense:** Rolling **6-month Air-Gapped Vault** (`today - 6m`, unreadable by `MarketDataStore`/MCP/marimo during research, unlocked once at human `Validated → Paper` gate; no toggle switch in v1) + mandatory **Post-2023 Recency Gate**. | Settled (2026-11-26) |
| **D11** | **Python → TypeScript bridge:** Signals promote via **materialized batch feature jobs** (`register_signal` → versioned `features` column read by Rust `Replay` + `StrategyContext`), eliminating manual Python-to-TypeScript indicator rewrites. | Settled (2026-11-26) |
| **D12** | **Knowledge base:** Mount Studio's 83-card `catalog/quant/library/library.yml` read-only for methodology/literature; store only empirical Stock Bot `findings`, `dead_ends`, and `provider_caveats` in PostgreSQL. | Settled (2026-11-26) |
---
## 4. System architecture
```text
┌────────────────────────────────────────────┐
Ideas: you + Studio ───▶ │ AGENTS (desktop copilot, Studio, campaigns)│
└───────────────┬────────────────────────────┘
│ MCP tools / HTTP API / Python SDK
┌──────────────────────────────────────────▼─────────────────────────────────────────┐
│ RESEARCH KERNEL (one API) │
│ query data (vault-fenced) · analyze signal · event study · screen · backtest · │
│ tearsheet · findings · campaigns · trial ledger · vault promotion gate │
└───────┬───────────────────┬──────────────────────┬───────────────────┬─────────────┘
│ │ │ │
┌───────▼───────┐ ┌────────▼────────┐ ┌─────────▼────────┐ ┌───────▼─────────┐
│ DATA │ │ BACKTEST │ │ ORCHESTRATION │ │ EXECUTION │
│ MarketDataStore│ │ columnar screen │ │ campaigns, │ │ paper host → │
│ • DuckDB/Parq │ │ + Rust engine │ │ budgets, local │ │ IB Gateway (9900K│
│ • QuestDB 10.2│ │ + CPCV/DSR/PBO │ │ worker pool │ │ OMS, dual drift)│
└───────▲───────┘ └─────────────────┘ └──────────────────┘ └─────────────────┘
│
┌───────┴──────────────────────────────────────────────┐
│ PIPELINE (data-pipeline): raw → merged → curated → │
│ batch features; security master in PostgreSQL │
└───────▲──────────────────────────────────────────────┘
│ read-only (MONGODB_READ_URI: studio_stock_bot_read)
┌───────┴───────────────┐ ┌──────────────────────────────────────────┐
│ MongoDB raw landing │◀───────│ data-ingestion (providers: EOD, QM, IB, │
│ (QA, never written │ │ CEO, TE) │
│ from dev/tests) │ └──────────────────────────────────────────┘
└───────────────────────┘
APP (web-app): Lab (+ marimo) · Agents · Strategies · Data · Trading · Markets · Home
```
| Layer | Owns | Language |
| --- | --- | --- |
| `data-ingestion` | Provider crawlers → raw MongoDB (scheduled jobs disabled outside dedicated ingester) | TypeScript |
| `data-pipeline` | Entity resolution, split/volume un-adjustment, PIT curation, batch features → Postgres + Parquet + QuestDB | TypeScript + Python/DuckDB batch |
| Research kernel | Single API + MCP server enforcing vault cutoff, budgets, trial ledger, and canonical metrics | TypeScript (`web-api` / `orchestrator` / `@stock-bot/calculations`) |
| Engine | Authoritative accounting, multi-currency margin ledger, corporate actions, fills, risk, replay | Rust (`apps/stock/engine/src/financial`) |
| Python SDK + marimo | Exploration, Signal Analyzer, Event Study, Tier 1 columnar screener, feature batch definitions | Python (`polars`, `duckdb`, `marimo`) |
| `web-app` | Incremental UI over Research Kernel state | TypeScript / React |
---
## 5. Data architecture and storage
Full schemas and SQL contracts live in **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)**.
### Layers
| Layer | Store | Contents | Who writes | Who reads |
| --- | --- | --- | --- | --- |
| Raw | MongoDB (`stock`) | Provider documents as fetched | `data-ingestion` | `data-pipeline` only (`studio_stock_bot_read`) |
| Reference | PostgreSQL | Exchanges, instruments, identifier history, listings, symbol history, provider mappings, corporate-action continuations, conflicts, overrides | `data-pipeline` | Everything |
| Curated (Daily & PIT) | **Parquet + DuckDB** | `bars_1d`, `adj_factors`, `corporate_actions`, bitemporal `fundamentals` + wide PIT/TTM snapshots, `events`, `shorts`, `macro`, `fx_1d` | `data-pipeline` | `MarketDataStore` |
| Curated (Intraday & Hot) | **QuestDB `10.2.0`** | `bars_1m` (`5m`/`1h` via `SAMPLE BY` or materialized), `fx_1m`, recorded live/paper IB bars & quotes, sparse `bar_revisions` | `data-pipeline`, IB bridge | `MarketDataStore` |
| Features | **Parquet + DuckDB** (1d) / **QuestDB** (intraday) | Versioned precomputed feature series (`(listing_id, ts, known_at, value)`) | Feature jobs | `MarketDataStore`, Screener, Rust `Replay` |
| Research & Vault state | PostgreSQL | Projects, campaigns, `trial_ledger` (with return vectors), findings, strategies, runs, `vault_evaluations` | Research kernel | App, MCP, SDK |
### Access rules & performance targets
1. **One access contract (`MarketDataStore` in TS, `stockbot.data` in Python).** Every non-vault call enforces `ts < VAULT_CUTOFF_TS` and `known_at <= asOf` inside the adapter. No raw-SQL escape hatch is exposed to agents; human localhost sessions may query read-only pre-vault DuckDB views.
2. **Storage hygiene.**
- `MarketDataStore` and Parquet expose `listing_id` as `INT32`; inside QuestDB `10.2.0`, `listing_id` is stored as `SYMBOL CAPACITY 65536 NOCACHE` so `LATEST ON` backward partition scans and `ASOF JOIN` fast paths work without JVM heap bloat.
- Sealed `>90d` QuestDB `bars_1m` partitions may be compressed in-place (`ALTER TABLE bars_1m CONVERT PARTITION TO PARQUET`) if NVMe capacity requires it; recent partitions remain native mmap.
3. **Measured storage targets on `quant` (`12900K`, SN850X NVMe):**
- **W1:** 20y US+CA daily universe (~15k active+delisted listings, ~45M bars) + 1 signal IC/quantile scan: **`< 3 s` warm / `< 8 s` cold**.
- **W2:** 1 listing, 1y of `1m` bars (~100k–200k rows) from QuestDB: **`< 250 ms` warm / `< 1 s` cold**.
- **W3:** 4 concurrent campaign workers: **p95 slowdown `< 35%`**, zero OOM or lease expiries.
- **W4:** 1 date cross-section (~8k alive listings × 20 features): **`< 100 ms`**.
---
## 6. Step 1 — Cross-source merge (security master)
Exact DDL and edge-case rules are specified in **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)**.
### Target model (PostgreSQL)
- `exchange`: `mic` (ISO 10383 PK), `operating_mic`, `name`, `country_iso`, `currency`, `timezone`, `calendar_code`, `is_composite_or_ats`.
- `exchange_source_map`: `(source, source_code)` → `mic` (or explicit non-primary role: `'composite' | 'ats_routing' | 'forex' | 'excluded_fund'`), `reviewed_by`.
- `instrument`: `instrument_id` (`INT4` identity), `primary_isin`, `primary_cusip`, `canonical_name`, `security_type` (`common`, `preferred`, `unit`, `warrant`, `right`, `etf`, `cdr`, `fx`), `issuer_country`.
- `instrument_identifier_history`: `(instrument_id, id_type, id_value, valid_from, valid_to, source)` — preserves continuity across TSXV share consolidations and corporate redomiciliations (`LIN`).
- `listing`: permanent `listing_id` (`INT4` identity), `instrument_id`, `mic`, `ticker_root`, `class_suffix`, `currency`, `ib_conid`, `listed_from`, `listed_to`, `delist_reason`.
- `listing_symbol_history`: `(listing_id, ticker, valid_from, valid_to, source)`.
- `corporate_action_continuity`: `(from_listing_id, to_listing_id, effective_date, kind)` — links primary-venue delistings (`SIVB` on `XNAS`) to same-ISIN OTC continuations (`SIVBQ` on `OTCM`) so bankruptcy losses are never truncated at halt price.
- `provider_mapping`: `(source, source_id, valid_from)` → `listing_id`, `valid_to`, `method`, `confidence`.
- `resolution_conflict`, `override` (always wins on re-runs), and `golden_field_audit`.
### Six-pass resolution pipeline
1. **Pass 1 — Exchanges (~320 rows):** Seed ISO 10383 MICs; map EOD (`76`), IB (`214`), QM (`25`), and CEO (`4: TSX→XTSE, CDX→XTSX, CNQ→XCNQ, AQL→NEOE`). Explicitly tag EOD `US` as composite (resolved via per-symbol `eodSymbols.Exchange`), exclude EOD `NMFQS` (`44,970` mutual funds) from equity universes, and mark IB ATS/smart codes (`AEQLIT`, `ARCAEDGE`, `BEX`, `DRCTEDGE`, `EDGEA`, `IEX`, `MEMX`, `OTCLNKECN`, `PSX`, `IBEOS`) as **`ats_routing`** rather than primary listing MICs.
2. **Pass 2 — Normalization & Observed Spans:** Parse root + suffix (`AAA-P`/`AAA.P`, `AACT U`/`AACT.U`, `SCU.UN`, strip CEO `.TO`/`.V`), Luhn-validate ISINs (rejecting `CATSETEST001`, `CA00149WBAD4`, checksum-corrupted `CA8131391062` while recovering valid CUSIP `813139106` → `CA8131391064`), fix `provider-symbol.ts` to read IB `exchangeId`/`description`, and precompute `[first_bar_date, last_bar_date]` per `(source, source_id)`.
3. **Pass 3 — Two-Stage Matching (Instrument first, Listing second):**
- **Stage A (`instrument`):** Match globally by Luhn-valid ISIN and US/CA CUSIP-derived ISIN (`IB ↔ EOD`). Interlisted US/CA shares (`SHOP` on `XTSE` CAD and `XNYS` USD) share one `instrument_id` and get two `listing_id`s.
- **Stage B (`listing` & non-ISIN sources):** Assign primary `listing.mic` from EOD `Exchange` + QM `exchange`; attach IB `conid` at `(instrument_id, currency)` (resolving the 83% TSX-on-`AEQLIT` and >90% NYSE/Nasdaq-on-ATS `ibSymbols` problem). Match QM and CEO by `(normalized_ticker, mic, currency)` **requiring overlapping `[first_bar_date, last_bar_date]` spans** so reused tickers (`FB` 2012–2022 Meta vs `FB` 2025 ProShares ETF; CSE `CNX`/`CC` duplicates) never collide.
4. **Pass 4 — Fast Cross-Sectional Price Cross-Check:** Extract 25 stratified trading dates via `{ date: { $in: sampleDates } }` (hitting `eodPrices`'s `{date: 1, eodSearchCode: 1}` index sequentially in seconds rather than scanning 846M docs per pair) or run in DuckDB post-extract; verify price ratio ($\approx 1.0$ or $\approx \text{USD/CAD}$) and return correlation.
5. **Pass 5 — Conflict Export & Overrides:** Write unresolved conflicts to `resolution_conflict`; review initial US+CA conflicts via generated markdown/CSV + SQL `override` seed file in Milestone 1 (deferring the React review UI until ongoing delta runs warrant it).
6. **Pass 6 — Golden Record & OTC Delisting Chains:** Populate golden fields (`IB` → `EOD` for ISIN/CUSIP/`conid`/currency; `EOD` → `QM` for name/sector/listing span) and link same-ISIN `XNAS`/`XNYS` → `OTCM` delisting continuations.
---
## 7. Step 2 — Processing the remaining datasets
| Dataset | Raw sources | Curation & PIT (`known_at`) Rules | Store |
| --- | --- | --- | --- |
| **Daily bars** | `eodPrices`, `qmPrices` | Raw OHLC; **un-adjust `eodPrices.volume`** using cumulative `qmSplits` factors (cross-checked against raw `qmPrices.sharevolume`); `known_at` = session close | Parquet (`bars_1d`) |
| **Intraday bars** | `eodIntraday1M` (US 2003–2025), `qmIntraday` (CA/US 2024–2025) | **Un-adjust `eodIntraday1M` OHLCV** for post-bar splits (cross-checked against `qmIntraday` raw & `bars_1d`); enforce venue session calendars | QuestDB `10.2.0` (`bars_1m`) |
| **Corporate actions** | `qmSplits`, `qmDividends`, `eodPrices`/`qmPrices` spans | Drop `splitratio == 1` no-ops; ignore bogus `qmDividends.usdFxRate: 1`; link same-ISIN OTC delistings (`SIVB`→`SIVBQ`) + apply Shumway terminal delisting returns (`-30%` involuntary unlinked delist, `-100%` cancelled `-Q`/Pink) | Parquet (`corporate_actions`, `adj_factors`) |
| **Fundamentals** | `qmFinancials`, `qmFinancials-old` + `qmFilings` (`eodFinancialsOLD` pre-QM fallback only; **`eodFundamentalsOLD` snapshots quarantined**) | Join `(listing_id, periodEndDate)` to earliest matching `10-Q`/`10-K`/`40-F`/SEDAR `Interim/Annual financial statements` `timefiled` in `qmFilings`. Fallback: statutory lag (`+45d Q / +90d FY` US & TSX; **`+60d Q / +120d FY` TSXV/CSE**) tagged `known_at_source = 'statutory_lag_estimate'`. Materialize 2D `(period_end, known_at)` deduplicated wide PIT + TTM snapshots. | Parquet (`fundamentals_pit`) |
| **Earnings** | `qmEarnings` + `qmFilings` | Resolve `"announceTime": "N/A"` (`66.9%` of rows) via `qmFilings` `8-K` / `News release` `timefiled`; otherwise lag to `reportDate 16:05 ET` (tradable `T+1` open) | Parquet (`events`) |
| **Filings** | `qmFilings` (`30.5M`) | Parse `timefiled` (`EST`/`EDT` → UTC); expose form-type & filing-arrival events (Form 4 / 144 / 8-K / NI 43-101 / 45-106F1 counts; insider share/dollar parsing deferred) | Parquet (`events`) |
| **CEO posts** | `ceoPosts` (`14.8M`) via `ceoSymbols` | Separate `bot == "1"` (`@thenewswire`) from retail posts; if `edited != null` (`1.8%`), guard text features with `known_at = edited` | Parquet (`events`) |
| **Shorts** | `ceoShorts` (`693k`, CA 2017–2025) | Stamp `known_at = report_timestamp + 4 Canadian business days (17:00 ET)` to match CIRO dissemination lag | Parquet (`shorts`) |
| **Macro** | `teCountries`, `teIndicators`, `teData` | Lagged publication cutoffs (`+1d` policy rates, `+35d` monthly CPI/NFP, `+65d/+90d` GDP); **regime filters only** (final-revised values, no release event studies) | Parquet (`macro`) |
| **FX** | `eodPrices`/`eodIntraday1M` (`CAD.FOREX`, `CADUSD.FOREX`) + `teMarketData` (`USDCAD`) | Curate existing 1971–2026 daily + `5.2M` `1m` USD/CAD series immediately; add IB `USD.CAD` live feed in Milestone 5 | Parquet (`fx_1d`) + QuestDB (`fx_1m`) |
---
## 8. Feature library
Features are defined once as **versioned DuckDB SQL or Python/Polars batch jobs** (`features/<family>/<name>_v<k>`), materialized to Parquet/QuestDB with `(listing_id, ts, known_at, value: f64)`, and registered with warm-up length, inputs, `known_at` rule, and unit tests:
- **Technical:** multi-horizon log/simple returns, realized vol, Wilder RSI (`flatValue = 50.0` standardized), ATR, MA distance, overnight/intraday gaps, dollar-volume z-score (on un-adjusted volume!), VWAP distance, opening range.
- **Cross-sectional:** universe/sector-neutralized ranks and winsorized z-scores per date.
- **Fundamental (PIT):** E/P, B/P, FCF yield, ROE, gross/operating margins, Sloan accruals, YoY asset/revenue growth, net-debt/EBITDA — computed strictly from 2D-deduplicated TTM snapshots.
- **Event & Canadian alt-data:** days since/until earnings, filing-burst flags (`45-106F1` financings, `NI 43-101`, Form 4/144 clusters), CEO.ca retail vs newswire post velocity, CIRO short-interest % of float & semi-monthly $\Delta$ days-to-cover.
- **Cross-border & FX:** interlisted TSX vs NYSE CAD-adjusted basis (`CAD.FOREX` 1m/1d) and lead-lag spreads.
- **Regime:** market breadth, realized-vol state, sector dispersion, lagged central-bank/CPI/PMI state.
**Promotion bridge (D11):** Calling `register_signal(...)` from Python/marimo registers a versioned batch feature job. Rust `Replay` and TypeScript `StrategyContext` receive a read-only `features: Record<string, number | null>` map at each decision barrier — so zero indicator or statistical math is ever rewritten in zero-import TypeScript.
---
## 9. Backtesting
Mathematical formulas and ledger schemas are specified in **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)**.
### Tier 1 — Fast columnar screener (Polars / DuckDB)
- Evaluates hundreds to thousands of `feature × horizon × universe × rebalance` variants in seconds over precomputed Parquet columns, applying linear spread + commission + borrow-rate turnover haircuts.
- Net-new columnar screener (distinct from deferred backlog task `P06`, which remains closed; `D04` shared features and `P03` worker dataset caching are reopened instead).
- Finds candidates only; **never** certifies a strategy. Logs the complete synchronous return matrix $M_{T \times N}$ to `trial_ledger` in one atomic batch.
### Tier 2 — Authoritative Rust portfolio engine (`apps/stock/engine/src/financial`)
Extends the existing 8-decimal Rust kernel (retiring legacy `f64` `BacktestEngine` and TypeScript `SimulationExecution` upon cutover):
- **Atomic timestamp-slice marking (`F06` fix):** Apply all instrument marks at timestamp `t` before evaluating `RiskAccount` portfolio drawdown/daily-loss latches so hedged long/short moves never trigger false intermediate halts.
- **Simultaneous target rebalancing:** Credit haircut-adjusted pending `Sell` proceeds against same-barrier `Buy` reservations in `MatchingAccount::submit` so fully invested cross-sectional rotations execute cleanly in one barrier.
- **Feature side-channel & Arrow loading:** Load market bars + precomputed `features` directly from Parquet/Arrow into Rust (eliminating PostgreSQL's 1 GB `JSONB` snapshot ceiling and removing double `serde_json::Value` parsing in `api/canonical.rs`), triggering JS/sandbox callbacks **only on declared rebalance barriers**.
- **Long/short, multi-currency margin & corporate actions:** Signed quantities/targets, short borrow fee accrual, `BTreeMap<Currency, Posting>` (`USD` + `CAD` cash/margin balances with IB benchmark+spread interest on negative balances, plus tradable FX pairs), ex-date split share adjustments, cash dividend postings, TSX/TSXV board-lot sizing (`100`/`500`/`1,000` shares), and OTC/Shumway delisting liquidations.
### Validation suite, Trial Ledger & 6-Month Vault
- **Trial ledger (`trial_ledger` in PostgreSQL):** Groups trials deterministically by `(universe_market, horizon_bucket)` (`{US, CA, US_CA, FX} × {intraday, swing_1_10d, position_10d_plus}`) and stores each variant's out-of-warmup daily return/IC vector (`FLOAT4[]`) to compute Bailey & López de Prado **effective independent trials $\hat{N}$**, non-normal **Deflated Sharpe Ratio (DSR $\ge 0.95$)**, and **PBO ($\le 0.20$)** via CSCV ($S = 16$).
- **Purged Walk-Forward & CPCV:** Replaces `labelHorizonMs = 0` with mandatory `purge = horizon + warmup` and `embargo = max(5d, 0.01 * T)`.
- **Post-2023 Recency Gate:** Post-2023 IC and Sharpe must be positive and $\ge 50\%$ of pre-2023 levels so decayed pre-LLM anomalies fail automatically.
- **Rolling 6-Month Air-Gapped Vault (`D10`):** Most recent 6 months (~126 trading days) fenced off from all research/MCP/marimo reads; evaluated **once** when **you** promote a `Validated` strategy toward `Paper` ($\le 10$ vault evaluations/year recorded in immutable `vault_evaluations`).
---
## 10. Orchestration
- **Single-host research & campaign execution on `quant` (`12900K`):** With 24 threads, 125 GiB RAM, and 3.6 TiB NVMe on `quant`, all databases, DuckDB/QuestDB stores, and 4–8 worker-pool slots run locally on `quant` — avoiding distributed multi-host worker complexity until 24 cores saturate.
- **Campaigns with hard SQL budgets:** `campaign → experiments → trials`, with cumulative trial, bar-evaluation, and wall-clock caps enforced by PostgreSQL `BEFORE INSERT` triggers (closing today's concurrent-only `active_trials` gap).
- **Shared dataset/feature memory (`P03`):** Trials in a campaign share memory-mapped Parquet/Arrow columns on `quant`.
- **Notifications:** Desktop/phone alerts (ntfy or Discord) when campaigns complete, vault candidates surface, or data monitors trip.
---
## 11. Research and analytics playground
1. **Exploration Lab (built first):**
- **Signal Analyzer:** IC, rank-IC, decay across `1d/5d/20d`, quantile spreads, turnover, breakeven cost, and breakdowns by regime, sector, market-cap tier, country (`US` vs `CA`), and pre/post-2023.
- **Event Study:** Pre/post abnormal return fans around filings (`NI 43-101`, `45-106F1`, Form 4/8-K), earnings, CIRO short spikes, and CEO.ca bursts.
- **marimo Labs (`D9`):**
- `marimo edit ./research/notebooks --watch --mcp` runs on a **dedicated loopback origin (`127.0.0.1:2718`)** with token auth so iframe scripts never share `web-app`'s `SameSite=Strict` `stock_bot_session` cookie.
- Agent findings attach **static HTML exports (`marimo export html`)** rendered in `<iframe sandbox="allow-scripts" srcDoc={...}>` (zero idle Python RAM); interactive `marimo run --session-ttl 300` launches on-demand only.
- Agent notebook writes must pass `marimo check --format=json` (`0` errors) and use `_`-prefixed cell-local variables for heavy Polars frames.
2. **Tearsheets:** Equity, underwater drawdown, rolling Sharpe, trade-to-bar drill-down (over unified `lightweight-charts`), exposures, capacity, full validation suite (`DSR`, `PBO`, `CPCV`, recency), and live dual drift.
3. **Agent Lab Feed:** Findings + dead ends linked to immutable trial counts, $\hat{N}$-adjusted DSR, and static HTML notebook snapshots, with one-click `Approve / Reject / Dig deeper / Promote to Paper (run 6m Vault)`.
4. **Market Intelligence (`Markets` & `Home`):** Built incrementally in Phase 4 once core research and portfolio backtesting are live.
---
## 12. Agent layer
- **Roles:** `Scout` (Studio/notes → testable hypothesis + economic rationale), `Data Analyst` (coverage & `known_at_source` check), `Signal Researcher` (IC / event studies), `Strategy Builder` (`register_signal` → Tier 1 screen → Tier 2 Rust backtest), `Skeptic` (audits look-ahead, split/volume artifacts, liquidity/board-lots, post-2023 decay, multiple testing), `Portfolio Manager` (marginal Sharpe & correlation vs existing book), `Monitor` (paper/live drift & decay).
- **Knowledge base (`D12`):** MCP mounts Studio's 83-card `~/repos/studio/catalog/quant/library/library.yml` read-only for statistical/methodological cards, while PostgreSQL stores Stock Bot's empirical `findings`, `dead_ends`, and `provider_caveats`.
- **Security & isolation:**
- Desktop Claude Code connects via MCP (`D2`) for interactive copilot work.
- Autonomous campaign agents run in **network-isolated containers** reaching **only** the Research Kernel MCP/HTTP endpoint (`sb-research.*` tokens with `/export` revoked, `GET` routes project-scoped, and SQL cumulative trial caps).
- **Studio bridge:** Studio Quant ideas (`hypothesis`) trigger bounded Stock Bot campaigns via API and receive structured `verdict + DSR + tearsheet/HTML link` receipts back.
---
## 13. Execution: paper to live on IB
Deployed on the dedicated, isolated **`9900K` host** (`docs/servers.md`) in Milestone 5:
- **Paper runtime fixes (prerequisite):** Compact `simulation_accounts` state (periodic snapshot + tail receipts, eliminating today's $O(N)$ double genesis replay in `apps/stock/engine/src/api/paper.rs`), expose `MatchingReset` over NAPI, and execute non-builtin strategy code inside the `A02` sandbox rather than importing raw JS into the privileged `paper-host` process.
- **IB Gateway & Market Data Bridge:** Headless `IB Gateway` supervised by `IBC` (handling nightly ~21:00 ET resets and `1100→1102` stream re-subscriptions). Aggregates `reqRealTimeBars(5s, TRADES)` + L1 `reqMktData` quotes into session-aligned bars emitted **after bar-close + 2s grace**, budgeted to $\le 80$ concurrent symbols within IBKR's standard 100-line cap.
- **Contract & Canadian market-structure rules:**
- Pin `(conid, symbol, currency, exchange="SMART", primaryExchange)` from `listing` so interlisted US/CA tickers (`SHOP`, `RY`, `TD`) never route across borders.
- Enforce TSX/TSXV price-tiered board lots (`100` sh $\ge \$1.00$, `500` sh $\$0.10\text{–}\$0.995$, `1,000` sh $< \$0.10$) and auction cutoffs (`15:40 ET` TSX MOC vs `15:50 ET` NYSE/Nasdaq MOC).
- **IBKR Margin `USD` / `CAD` & FX policy:**
- Track separate `USD` and `CAD` cash/margin sub-ledgers in Rust `Ledger`, accruing daily IBKR benchmark+spread interest on negative currency balances.
- Route cash-funding conversions to **`exchange="FXCONV"`** (`$2` min, updates cash without creating virtual FX positions); route intentional FX alpha trades to **`exchange="IDEALPRO"`**.
- **OMS, Risk & Dual Drift Monitoring:**
- Idempotent client order IDs, partial-fill state machine, continuous broker-vs-ledger position/cash reconciliation, per-strategy + global daily-loss/drawdown/order-rate kill switches.
- **Dual Drift Monitor:** separates **(1) Execution Drift** (live IB fills vs Rust replay on *recorded live IB bars/quotes*) from **(2) Feed Basis Drift** (Rust replay on *recorded IB bars* vs next-day *curated EOD/QM bars*).
---
## 14. The app
Evolves incrementally (`D4`) from today's `29.6k`-line React codebase (`apps/stock/web-app/src/features/*`):
- **Immediate cleanup:** Wire existing `ResearchAgentsPage.tsx` (`/research/agents`) into `Sidebar.tsx` and consolidate the two separate `lightweight-charts` wrappers (`src/components/charts/Chart.tsx` and `src/features/charts/components/SymbolChart.tsx`).
- **Target navigation (delivered with each milestone):**
- **Lab** (Signal Analyzer, Event Study, static-HTML + live marimo link)
- **Strategies** (lifecycle stages, tearsheets, CPCV/DSR/PBO + 6m Vault gate)
- **Agents** (campaigns, budgets, findings/dead-ends feed, `sb-research.*` tokens)
- **Data** (`exchanges`/`symbols`/`pipeline` + coverage map, quality monitors, conflict queue)
- **Trading** (`paper` + IB live positions, USD/CAD cash & margin, Dual Drift, kill switches)
- **Markets** & **Home** (greenfield — note `src/features/dashboard` is currently empty and deferred until Milestone 4).
---
## 15. Strategy lifecycle
```text
Idea ─▶ Hypothesis ─▶ Signal ─▶ Candidate ─▶ Validated ──[You: 6m Vault]──▶ Paper ─▶ Live ─▶ Retired
```
| Stage | Quantitative Gate to Enter | Who Approves |
| --- | --- | --- |
| **Hypothesis** | Economic rationale, target universe/horizon, `known_at_source` verified clean | Agent (`Scout` + `Data Analyst`) |
| **Signal** | $|\overline{\text{Rank IC}}| \ge 0.015$ ($t \ge 3.0$ Newey-West) or event abnormal return $\ge +35\text{ bps}$ ($t \ge 3.0$); **Post-2023 Recency Gate** ($\ge 50\%$ of pre-2023 IC & $> 0$) | Agent, logged to `trial_ledger` |
| **Candidate** | Tier 1 screen net Sharpe $\ge 1.0$ at $1.5\times$ costs; turnover within $2\%$ ADV | Agent |
| **Validated** | Tier 2 Rust engine + Purged Walk-Forward/CPCV: **DSR $\ge 0.95$** (cluster $\hat{N}$), **PBO $\le 0.20$**, net Sharpe $> 0$ at $2.0\times$ costs + `Skeptic` sign-off | Agent proposes to Lab Feed |
| **Paper** | One-shot **6-month Vault Holdout** Sharpe $> 0.5$ & within $1.5\sigma$ of CPCV + **manual code/evidence review** | **You** |
| **Live** | $\ge 30$ paper trading days & $\ge 50$ trades; Execution Drift $\le 15\text{ bps/trade}$; `0` unrecovered reconciliation breaks | **You** (small → scaled) |
| **Retired** | Rolling decay or drift beyond bounds, or manual halt | `Monitor` proposes, **You** confirm |
---
## 16. Roadmap
Detailed checklists, file targets, and exit criteria live in **[MILESTONES.md](MILESTONES.md)**:
| Milestone | Delivers | Target Window |
| --- | --- | --- |
| **M0 — Safety & Gate Lock** | All 11 gates green, dev PG `\c` bug fixed, `@stock-bot/postgres` migrations, `MongoDBClient` `readOnly` leak closed, proxy secret purged, `sb-research.*` `/export` blocked | Days 1–3 |
| **M1 — Vertical Slice 1 (Security Master + Daily/Event Signal Lab)** | US+CA security master (Passes 1–6 via SQL/CSV overrides), curated `bars_1d` + `corporate_actions` + `fx_1d` + `qmFilings`/`qmEarnings`/`ceoShorts` in DuckDB+Parquet, 6m Vault fence, `trial_ledger` + DSR, Python `stockbot` SDK + `marimo` Signal Analyzer | Weeks 1–3 |
| **M2 — MCP Copilot, Intraday QuestDB & PIT Fundamentals** | MCP server + Studio library mount, `qmFinancials × qmFilings` 2D PIT fundamentals, `QuestDB 10.2.0` `bars_1m` + `fx_1m` (split-unadjusted), versioned batch Feature Library | Weeks 4–5 |
| **M3 — Portfolio Backtest v2 (Screener + Multi-Asset Rust)** | Tier 1 columnar screener, Tier 2 Rust multi-asset upgrades (atomic marks, target sell-netting, `features` channel, long/short margin, USD/CAD, corporate actions, OTC delistings, Arrow load), CPCV + PBO + Vault promotion gate | Weeks 6–9 |
| **M4 — Autonomous Campaigns, Studio Bridge & Lab UI** | Containerized campaign runner with SQL cumulative budgets, agent roles + `Skeptic`, Studio webhook bridge, unified `web-app` Lab/Agents/Data/Markets/Home screens | Weeks 10–12 |
| **M5 — Compacted Paper → Live IB Margin (`9900K`)** | `paper.rs` state compaction + sandboxed paper candidates, headless `IB Gateway + IBC` bridge on `9900K`, OMS + TSX board-lots + `FXCONV`, continuous reconciliation, Dual Drift Monitor, small-capital live | Weeks 13–16 |

44
docs/README.md Normal file
View file

@ -0,0 +1,44 @@
# Stock Bot — Documentation Map
Start here. Every document below has a single responsibility; historical sprint logs and superseded design notes have been retired.
---
## 1. Platform Direction & Execution Plan
| Document | Owns | When to Read |
| --- | --- | --- |
| **[PLATFORM-PLAN.md](PLATFORM-PLAN.md)** | Target system architecture, settled decisions (`D1`–`D12`), layer boundaries, agent roles, and IB execution model | Before making architectural changes or starting a new milestone |
| **[MILESTONES.md](MILESTONES.md)** | Active checklist (`M0` → `M5`), task order, explicit scope cuts, target file paths, and falsifiable exit criteria | Day-to-day execution for you, Claude Code, and Studio agents |
| **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** | Raw MongoDB provider quirks, PostgreSQL security-master DDL, split/volume un-adjustment rules, `known_at` derivation, DuckDB/Parquet & QuestDB `10.2.0` schemas, and `MarketDataStore` API | Before touching `data-pipeline`, `data-ingestion`, SQL migrations, or `MarketDataStore` |
| **[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 |
---
## 2. Current Connected Runtime & Code Tour
These documents describe **what is already implemented and running in code today**:
| Document | Owns |
| --- | --- |
| **[guide/README.md](guide/README.md)** | High-level tour of the current canonical single-asset research workbench |
| **[guide/system-map.md](guide/system-map.md)** | Applications, shared libraries, queues, and process boundaries |
| **[guide/backtest-walkthrough.md](guide/backtest-walkthrough.md)** | End-to-end trace of a canonical backtest from HTTP admission to Rust replay and result persistence |
| **[guide/strategy-development.md](guide/strategy-development.md)** | Current `StrategyProgram` callback contract and isolated candidate packaging |
| **[guide/code-reading.md](guide/code-reading.md)** | Function-level call paths across `web-api`, `orchestrator`, and `engine` |
| **[backtest-datasets.md](backtest-datasets.md)** | Current v2 retained dataset snapshot preparation, hashing, and local export |
| **[data-pipeline/phase1-investigation.md](data-pipeline/phase1-investigation.md)** | Measured 31-collection QA MongoDB inventory, identifier coverage, and cross-provider tricky cases |
| **[cleanup-audit.md](cleanup-audit.md)** | Separation between reviewed `@stock-bot/calculations` core and preserved `/legacy` functions |
---
## 3. Enduring Architecture Decisions & Gates
| Document | Owns |
| --- | --- |
| **[development/QUALITY-GATES.md](development/QUALITY-GATES.md)** | Build, typecheck, contract, lint, native Rust, disposable PostgreSQL/Redis, and E2E verification gates |
| **[development/architecture/overview.md](development/architecture/overview.md)** | Core invariants of the Rust financial kernel and durable worker supervision |
| **[development/architecture/research-product.md](development/architecture/research-product.md)** | Retained provenance, idempotency, agent grants (`A01`), candidate isolation (`A02`), and paper custody (`A04`) |
| **[development/architecture/benchmarks.md](development/architecture/benchmarks.md)** | Reproducible dataset and replay benchmark methodology |
| **[development/architecture/decisions/](development/architecture/decisions/)** | Approved ADRs `001`–`008` (ownership, 8-decimal postings, availability timing, NAPI pull boundary, durable cutover, AI boundary, performance) |

View file

@ -0,0 +1,103 @@
# Stock Bot — Validation, Trial Ledger & Execution Rigor
Canonical mathematical and operational rules for `@stock-bot/calculations`, `@stock-bot/research`, the PostgreSQL `trial_ledger`, the 6-month Vault Holdout, and IBKR Margin / TSX execution.
---
## 1. Canonical Metric Conventions (`@stock-bot/calculations`)
No Python script, UI component, or legacy simulator may define its own Sharpe, Sortino, volatility, or drawdown formula. All layers read metrics computed by `@stock-bot/calculations`:
- **Return series:** Daily (or session-level) mark-to-market net portfolio total returns $r_t = \frac{E_t - E_{t-1}}{E_{t-1}}$ in the account's base currency, starting from `initialCapital` (so first-period losses are never skipped).
- **Annualization factor ($A$):** `252` trading sessions/year for equity strategies (`252 * 390` only when reporting un-aggregated 1m bar statistics; tearsheets always aggregate intraday equity to daily session closes before computing Sharpe/DSR/PBO so intraday and daily strategies compare on the same `252`/yr scale).
- **Volatility:** Sample standard deviation ($N - 1$ degrees of freedom), annualized via $\hat{\sigma}_{\text{ann}} = \hat{\sigma}_d \sqrt{252}$.
- **Sharpe Ratio ($\widehat{SR}$):** Arithmetic excess return over risk-free rate $r_f$ per period:
$$\widehat{SR}_{\text{ann}} = \frac{\bar{r}_d - r_{f,d}}{\hat{\sigma}_d}\sqrt{252}$$
- **Sortino Ratio:** Downside root-mean-square over **all** $T$ observations (`target = r_{f,d}`), never standard deviation of negative-only observations:
$$\widehat{\text{Sortino}}_{\text{ann}} = \frac{(\bar{r}_d - r_{f,d}) \cdot 252}{\sqrt{\frac{252}{T}\sum_{t=1}^{T} \min(0, r_t - r_{f,d})^2}}$$
- **RSI convention:** Wilder smoothing (`1/period`), with flat-price (`avg_gain == 0 && avg_loss == 0`) standardized to **`50.0`** across Rust, TypeScript, and batch feature jobs.
---
## 2. Trial Ledger & Multiple-Testing Math (`DSR` & `PBO`)
### A. PostgreSQL `trial_ledger` Schema (Append-Only)
Protected against `UPDATE`/`DELETE`/`TRUNCATE` by `reject_research_evidence_mutation()`:
```sql
CREATE TABLE IF NOT EXISTS trial_ledger (
trial_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
principal_id TEXT NOT NULL, -- 'operator' | 'agent:<uuid>'
campaign_id UUID,
stage VARCHAR(16) NOT NULL, -- 'signal_ic' | 'event_study' | 'screen' | 'engine_backtest'
universe_market VARCHAR(12) NOT NULL, -- 'US_EQ' | 'CA_EQ' | 'US_CA_EQ' | 'FX'
horizon_bucket VARCHAR(16) NOT NULL, -- 'intraday' | 'swing_1_10d' | 'position_10d_plus'
hypothesis_id UUID,
expression_hash CHAR(64) NOT NULL, -- SHA-256 of canonical signal/strategy + params + universe + window
sample_start DATE NOT NULL,
sample_end DATE NOT NULL, -- must be < VAULT_CUTOFF_DATE
n_obs INTEGER NOT NULL,
sharpe_unann DOUBLE PRECISION NOT NULL,
skewness DOUBLE PRECISION NOT NULL,
kurtosis DOUBLE PRECISION NOT NULL, -- Pearson kurtosis (normal = 3.0)
daily_series REAL[] NOT NULL -- daily net return or daily cross-sectional IC vector (~5k floats = 20 KB)
);
```
### B. Relatedness Cluster & Effective Independent Trials ($\hat{N}$)
- **Deterministic cluster key:** `(universe_market, horizon_bucket)`. Agents cannot reset `N = 1` by inventing a new strategy `family` name.
- **Multi-horizon / breakdown accounting:** A single `analyze_signal` call evaluating 3 horizons (`1d`, `5d`, `20d`) records **3 rows** in `trial_ledger`.
- **Effective independent trials ($\hat{N}$, Bailey & López de Prado):** Given $K$ trials in the cluster with overlapping daily series correlation matrix $P$:
$$\bar{\rho} = \frac{2}{K(K - 1)}\sum_{1 \le i < j \le K} \rho_{ij}, \qquad \hat{N} = \max\!\big(1,\; 1 + (K - 1)(1 - \max(0, \bar{\rho}))\big)$$
Sweeping `SMA(20)` and `SMA(21)` ($\rho \approx 0.97$) adds $\approx 0.03$ effective trials; testing 100 orthogonal signals ($\bar{\rho} \approx 0$) yields $\hat{N} \approx 100$.
### C. Non-Normal Deflated Sharpe Ratio (`DSR`)
Using unannualized per-day $\widehat{SR}$ over $T$ daily observations, skewness $\hat{\gamma}_3$, Pearson kurtosis $\hat{\gamma}_4$, and cross-sectional variance $\hat{\sigma}_{\{SR\}}^2 = \text{Var}(\{\widehat{SR}_k\}_{k=1}^K)$ across the cluster:
$$SR_0 = \hat{\sigma}_{\{SR\}} \left[ (1 - \gamma)\Phi^{-1}\!\left(1 - \frac{1}{\hat{N}}\right) + \gamma\,\Phi^{-1}\!\left(1 - \frac{1}{\hat{N} e}\right) \right], \quad \gamma \approx 0.57721566$$
$$\widehat{\text{SE}}(\widehat{SR}) = \sqrt{\frac{1 - \hat{\gamma}_3 \widehat{SR} + \frac{\hat{\gamma}_4 - 1}{4}\widehat{SR}^2}{T - 1}}, \qquad \text{DSR} = \Phi\!\left(\frac{\widehat{SR} - SR_0}{\widehat{\text{SE}}(\widehat{SR})}\right)$$
**Gate:** Candidate → Validated requires **`DSR >= 0.95`**.
### D. Probability of Backtest Overfitting (`PBO` via CSCV)
Computed on any synchronous screen/experiment return matrix $M \in \mathbb{R}^{T \times N}$ ($N \ge 4$):
1. Partition $T$ into $S = 16$ contiguous equal sub-periods (respecting `purge` at boundaries).
2. For all $\binom{16}{8} = 12,870$ splits into in-sample $J$ and out-of-sample $\bar{J}$: find $n^* = \arg\max_n SR_n(J)$, compute the relative OOS rank $\omega \in (0, 1)$ of $n^*$ within $\{SR_n(\bar{J})\}$, and set $\lambda = \ln\!\frac{\omega}{1 - \omega}$.
3. $\text{PBO} = \Pr(\lambda < 0)$ across all $12,870$ splits.
**Gate:** Candidate → Validated requires **`PBO <= 0.20`**.
---
## 3. Purging, Embargo, Recency & the 6-Month Vault
1. **Purged Walk-Forward & CPCV:** Every train/test boundary enforces:
- `purge_bars = prediction_horizon_bars + feature_warmup_bars` (eliminating `labelHorizonMs = 0` overlap leakage).
- `embargo_days = max(5, ceil(0.01 * total_trading_days))` after each test fold before resuming training.
2. **Post-2023 Recency Gate:** Every candidate must report pre-2023 (`< 2023-01-01`) vs. post-2023 (`2023-01-01 .. VAULT_CUTOFF_DATE`) performance. Post-2023 rank-IC and post-cost Sharpe must both be **strictly positive** and **$\ge 50\%$** of pre-2023 levels.
3. **Rolling 6-Month Air-Gapped Vault (`VAULT_CUTOFF_DATE`):**
- Set to `max_curated_date - 6 calendar months` (~126 trading days).
- Physically fenced in `MarketDataStore` (`scope = 'vault_fenced'`), with `/export` disabled for `sb-research.*` tokens and campaign containers blocked from DB ports.
- **One-shot human burn:** Triggered only on operator `Validated → Paper` action (`<= 10` evaluations/year enforced by an append-only `vault_evaluations` table). Requires Vault post-cost Sharpe $> 0.5$ and within $1.5\sigma$ of CPCV fold distribution.
---
## 4. IBKR Margin, USD/CAD, TSX Microstructure & Dual Drift Rules
1. **Multi-currency IBKR Margin accounting (`USD` + `CAD`):**
- Rust `Ledger` holds `cash: BTreeMap<Currency, Posting>` (signed `Decimal`, scale 8).
- Buying a `USD` asset without `USD` cash creates a negative `USD` balance accruing daily IBKR tier benchmark + spread interest (no implicit free FX conversion).
- Automated cash sweeps emit `secType="CASH"`, `symbol="USD"`, `currency="CAD"`, **`exchange="FXCONV"`** (`$2.00` USD min fee, `0.2` bps) — never `IDEALPRO`, unless a strategy explicitly opens a tracked FX alpha position.
2. **Contract & Canadian board-lot rules:**
- Every IB `Contract` specifies `conid`, `currency`, `exchange="SMART"`, and `primaryExchange` (`NYSE`, `NASDAQ`, `TSE`, `VENTURE`, etc.).
- Position sizing on `XTSE` / `XTSX` (`board_lot_policy = 'tsx_tiered'`) rounds target orders to **Standard Trading Units** (`100` shares if mark $\ge \$1.00$ CAD; `500` shares if $\$0.10\text{–}\$0.995$; `1,000` shares if $< \$0.10$) unless odd-lot execution + wider spread penalty is explicitly enabled.
- Auction orders enforce hard venue cutoffs (`15:40 ET` TSX `MOC`; `15:50 ET` NYSE/Nasdaq `MOC`/`LOC`).
3. **Dual Live Drift Monitor:**
- **Check 1 — Engine/Execution Drift:** Compare live IB fills & cash against a Rust replay run on the **exact recorded live IB bars & L1 quotes** (gate: $|\Delta\text{fill}| \le 15\text{ bps/trade}$, daily tracking error $\le 50\text{ bps}$ annualized).
- **Check 2 — Feed Basis Drift:** Next morning after EOD/QM ingestion, compare Rust replay on **recorded IB bars** vs. Rust replay on **curated EOD/QM bars** for the same session to detect SIP vs. IB `SMART` volume/auction divergence before blaming execution.

View file

@ -1,106 +0,0 @@
I'll search for specific information about Timothy Masters' recommendations on permutation tests for trading and newer alternatives in 2025.Based on my research, here's a comprehensive overview of **Timothy Masters' recommendations and newer alternatives for permutation and randomization tests in trading (2025)**:
## Timothy Masters' Permutation Test Recommendations
Timothy Masters, in his book "Permutation and Randomization Tests for Trading System Development," advocates for several key permutation tests:
### 1. **Core Permutation Methods**
The book covers: Testing for overfitting at the earliest possible stage, Evaluating the luckiness-versus-skill of a fully developed system before deploying it, Testing the effectiveness and reliability of a trading system factory, Removing selection bias when screening a large number of indicators
### 2. **Monte Carlo Permutation Test**
The Monte Carlo permutation test of Timothy Masters involves simulating multiple iterations of the strategy using randomly permuted versions of historical data. The process:
- Transforms absolute prices into log-returns for better statistical properties
- Creates 500 or 1000 permuted versions resulting in worse performance for >>90% if the strategy picks up a real "signal"
### 3. **Key Applications**
One usage of the Monte Carlo Permutation test allows us to discover the degree of data overfitting, without using the out-of-sample data
- Tests whether trading performance beats 99% of what could be expected by luck
- Preserves the single-usage principle of out-of-sample data
- If our trading system beats 99% of what can be expected by good luck, we can conclude that our indicator, trading system or trading system development method is actually worthwhile
### 4. **Selection Bias Testing**
On March 30, 2020, I released a third edition of the book which includes an important new section that introduces an alternative permutation test for selection bias that is substantially superior to the traditional test
## Newer Alternatives and Advances in 2025
### 1. **System Parameter Permutation (SPP) and Randomization (SPR)**
System Parameter Randomization (SPR) is introduced as a close cousin of SPP to address computational limitations and provide a better alternative
**Advantages over Masters' approach:**
- The idea behind System Parameter Permutation is that we must test ALL the possible parameter combinations and only from the data of all optimization runs we can make some assumptions about the realistic strategy performance
- Computes median values for all performance statistics (Net profit, Drawdown, Sharpe ratio, etc.)
- More computationally feasible for complex trading systems
### 2. **Advanced Bootstrap Methods**
**Block Bootstrap Variants:**
Advanced block bootstrap methods are specifically tailored for dependent time series data, including stationary bootstrap, circular bootstrap, and tapered block bootstrap
- **Stationary Bootstrap**: Uses random block lengths from geometric distribution
- **Circular Bootstrap**: Attempts to solve edge effects by wrapping the series
- **Tapered Block Bootstrap**: Offers smoother transitions at block boundaries
### 3. **White's Reality Check and Hansen's SPA Test**
White's Reality Check bootstrap methodology evaluates simple technical trading rules while quantifying the data-snooping bias
**Superior Predictive Ability (SPA) Test:**
- The stepwise SPA test is more powerful than the stepwise Reality Check test of Romano and Wolf
- Addresses data snooping bias more effectively
- Can identify predictive models without potential bias
### 4. **Conformal Prediction for Trading**
This is one of the most promising newer alternatives:
**Key Features:**
- Distribution-free nature - unlike Bayesian approaches and other statistical methods that require specific assumptions about the data distribution, conformal prediction makes no such assumptions
- Provides valid prediction intervals with guaranteed coverage
- The EnbPI (Ensemble batch Prediction Intervals) method removes the data exchangeability requirement and can thus be applied in time series forecasting
**Applications in Trading:**
- Uncertainty quantification for price predictions
- Risk-adjusted position sizing based on prediction intervals
- Model confidence assessment without distributional assumptions
### 5. **Synthetic Data Generation Methods**
Deep generative models produce synthetic time-series data, enhancing the amount of data available for training predictive models
**Benefits for Trading Strategy Validation:**
- Creates realistic market scenarios while preserving statistical properties
- Synthetic data obtained this way replicates the distribution properties of real historical data, leads to better performance, and enables thorough validation of predictive models
- Addresses data scarcity issues in certain market conditions
- In the finance sector, synthetic data is used for fraud detection, risk assessment, and algorithmic trading
### 6. **Hybrid Approaches**
**Combining Multiple Methods:**
The variance test takes the historical trades and creates a probable distribution to resample, selecting random trades from this distribution until it reaches the backtest's total trade count
**Modern Robustness Tests:**
- Noise testing, Vs Shifted, Variance testing or Monte Carlo Permutation test multiple price paths
- Address limitations of traditional walk-forward analysis
- Four-step approach: in-sample excellence, Monte Carlo permutation testing, walk-forward testing, and walk-forward Monte Carlo testing
## Key Advantages of Newer Methods
1. **Computational Efficiency**: Modern methods like SPR and conformal prediction are more computationally efficient than exhaustive permutation testing
2. **Better Coverage**: CopulaCPTS produces significantly sharper and more calibrated uncertainty estimates than state-of-the-art baselines
3. **No Distributional Assumptions**: Conformal prediction and synthetic data methods work without assuming specific data distributions
4. **Adaptive Capabilities**: Methods like EnbPI update intervals as new data arrives, maintaining adaptiveness
5. **Multi-Path Testing**: Unlike single-path methods, newer approaches test multiple possible market scenarios simultaneously
## Recommendations for 2025
For modern trading system development, consider:
1. **Start with Masters' Monte Carlo Permutation** for basic validation
2. **Implement SPP/SPR** for parameter robustness testing
3. **Use Conformal Prediction** for uncertainty quantification and risk management
4. **Apply Synthetic Data Generation** for stress testing under various market conditions
5. **Combine multiple methods** for comprehensive validation
The field has evolved significantly, with newer methods offering better computational efficiency, fewer assumptions, and more robust validation while maintaining the core principles that Masters established.

View file

@ -6,7 +6,7 @@ Command `bun apps/stock/data-pipeline/scripts/phase1-inventory.ts > /tmp/p1.json
## a. Source inventory
The `stock` database contained **31 collections**. Source names start with lowercase provider prefixes followed by a camelCase entity name (`qm*`, `eod*`, `ib*`, `ceo*`, `te*`, `tt*`). No `XX_`-prefixed, TradingView, or Webshare collection was present. This describes persisted data. The ingestion code and [source notes](../../docs/data-sources.md) also cover providers with no collection in this snapshot.
The `stock` database contained **31 collections**. Source names start with lowercase provider prefixes followed by a camelCase entity name (`qm*`, `eod*`, `ib*`, `ceo*`, `te*`, `tt*`). No `XX_`-prefixed, TradingView, or Webshare collection was present. This describes persisted data; see [DATA-CONTRACTS.md](../DATA-CONTRACTS.md) for the canonical 31-collection contracts and adjustment rules.
The exact count column comes from `countDocuments({})` for collections whose estimate was below one million. A dash means the estimate was used. The inventory sampled top-level keys from up to 200 documents per collection. Large time-series and event collections had metadata and key samples only.

View file

@ -1,50 +0,0 @@
# Core Data
### EOD (Good Price Good Api)
- Pricing: https://eodhd.com/pricing
- API Docs: https://eodhd.com/financial-apis/
### Twelve Data (Promicing $80-230/month)
- Pricing: https://twelvedata.com/pricing
- API Docs: https://twelvedata.com/docs
### Tiingo ($30/month looks good)
- Pricing: https://www.tiingo.com/about/pricing
- API Docs: https://api.tiingo.com/
### Alpha Vantage (Kinda ok) (4M6P2HUGJGI73UWG)
- Pricing: https://www.alphavantage.co/premium/
- API Docs: https://www.alphavantage.co/documentation/
### Yahoo Finance API
- Unofficial Python library: https://github.com/ranaroussi/yfinance
- Alternative: https://github.com/lukaszbanasiak/yahoo-finance
### Finnhub (Expensive $40-200/month)
- Pricing: https://finnhub.io/pricing
- API Docs: https://finnhub.io/docs/api
### Polygon.io (Good pricing for 5 years - 20+ is 200 but unlimited calls and good data)
- Pricing: https://polygon.io/pricing
- API Docs: https://polygon.io/docs/stocks/getting-started
### FMP ($50/month Lots of data and good api calls)
- Pricing: https://site.financialmodelingprep.com/developer/docs/pricing
- API Docs: https://financialmodelingprep.com/developer/docs
### Marketdata.App
- Pricing: https://www.marketdata.app/
### ThetaData
- https://www.thetadata.net/subscribe
## Additional Resources
- **Marketstack**: https://marketstack.com/
- **Alpaca**: https://alpaca.markets/ - Future hopefully or US connection
- **MacroMicro**: https://en.macromicro.me/
- **Norgate**: https://norgatedata.com/stockmarketpackages.php#castocks
- **FINRA**: https://www.finra.org
https://otce.finra.org/otce/EquityShortInterest/staticArchives?startDate=2014-01-01&endDate=2024-11-03&dateDisplay=November%203,%202018
https://www.finra.org/finra-data/browse-catalog/equity-short-interest/files
https://www.cboe.com/us/equities/market_statistics/short_interest/?year=2025&month=06&mkt=bzx
- **MORNINGSTAR**: https://finra-markets.morningstar.com/MarketData/EquityOptions/detail.jsp?query=14:0P0001BUHA PRICES/SHORT INTEREST

View file

@ -1,92 +0,0 @@
# Cleanup and maintainability plan
Current acceptance: all 13 cleanup stories received independent review; the resulting cache/configuration corrections and check evidence are recorded in [real-data-research.md](real-data-research.md). Earlier review-pending statements below describe the historical execution state.
Baseline: `fbf2eb9e`, inspected October 26, 2026. This extends the existing development backlog. The original 45 scheduled tasks remain complete; these 13 cleanup stories are new work. The owner subsequently authorized implementation and validated commits; progress and checks are recorded in [cleanup-execution.md](cleanup-execution.md). All 13 stories are implemented and validated. They remain in `review` until an independent reviewer signs off; no additional agents have been launched.
[manifest.json](backlog/manifest.json) remains the scheduling source of truth. It records task states, prerequisites, priorities and write locks. This page explains the execution contract and recommended order; it is not a second status tracker. Current evidence is appended to [findings.md](backlog/findings.md#cleanup-audit-2026-10-26).
## Objective
Reduce the maintenance cost of the existing TypeScript research platform while preserving the canonical Rust financial core, immutable research inputs and results, candidate isolation, durable execution and reviewed calculations. This prepares stable interfaces for the agreed editor/Codex/research-tool direction without implementing MCP, notebooks or a new AI workflow yet.
## Story index
| Story | Outcome | Priority | Size | Implementation prerequisites |
| --- | --- | --- | --- | --- |
| [CL01](backlog/tasks/CL01.md) | Replace permissive DI tests with production-path assertions | P1 | M | None |
| [CL02](backlog/tasks/CL02.md) | Normalize connection settings and honor service-disable switches | P1 | M | CL01 |
| [CL03](backlog/tasks/CL03.md) | Roll back failed shared-service startup and clear timers | P1 | M | None |
| [CL04](backlog/tasks/CL04.md) | Repair commands and provide one consistent research startup path | P1 | S | None |
| [CL05](backlog/tasks/CL05.md) | Extract shared dataset/report logic behind one research package | P2 | M | Completed D01, F08, R05 |
| [CL06](backlog/tasks/CL06.md) | Share dataset response schemas and eligibility checks | P2 | M | CL05 |
| [CL07](backlog/tasks/CL07.md) | Share experiment/validation HTTP transport plumbing | P2 | M | None |
| [CL08](backlog/tasks/CL08.md) | Split backtest application-service responsibilities | P2 | M | CL05 |
| [CL09](backlog/tasks/CL09.md) | Separate strategy metadata, versions and publication UI | P2 | M | None |
| [CL10](backlog/tasks/CL10.md) | Separate experiment modes and submission state | P2 | M | None |
| [CL11](backlog/tasks/CL11.md) | Separate template, run-monitoring and submission lifetimes | P2 | M | None |
| [CL12](backlog/tasks/CL12.md) | Remove unreachable execution seams while preserving compatibility | P2 | M | CL08 |
| [CL13](backlog/tasks/CL13.md) | Hide placeholder navigation while preserving useful routes | P2 | S | None |
Each story contains a user outcome, verified repository evidence, intended behavior, affected paths, exclusions, ownership, acceptance criteria, mandatory verification and regression risks. Proposed new test/module names are labelled as proposed rather than claimed existing capabilities.
## Dependency and integration order
```mermaid
flowchart LR
CL01[CL01: trustworthy DI tests] --> CL02[CL02: configuration]
CL03[CL03: startup rollback]
CL04[CL04: developer commands]
BASE[Completed D01 / F08 / R05] --> CL05[CL05: shared domain boundary]
CL05 --> CL06[CL06: dataset response schemas]
CL05 --> CL08[CL08: backtest application modules]
CL08 --> CL12[CL12: retired execution seams]
CL07[CL07: HTTP transport]
CL09[CL09: strategy UI]
CL10[CL10: experiment UI]
CL11[CL11: backtest UI state]
CL13[CL13: navigation]
```
Edges are code prerequisites. File locks are additional scheduling constraints: CL02 and CL03 both touch the DI builder and must not run together, even though neither needs the other's behavior. CL04 owns root scripts; CL05 uses the existing workspace glob and must coordinate any unexpectedly required root-script edits. CL07 starts with experiment clients, leaving the backtest API client to CL06.
Recommended progression:
1. Establish the DI test baseline, repair shared startup, and remove broken development commands.
2. Complete CL02 once CL01 is accepted and CL03 releases the DI builder lock. Begin the CL05 domain extraction independently.
3. Follow CL05 with CL06 and CL08; keep their actual imports/contracts coordinated. CL07 can proceed independently against unchanged client contracts.
4. Refactor one frontend workflow at a time, then simplify CL12's confirmed-unreachable execution branches. CL13 is an independent small cleanup when navigation is otherwise idle.
This is a preferred sequence, not an artificial dependency chain. Unrelated frontend work can proceed sooner when ownership and review capacity are available.
## First execution wave
**CL01, CL03 and CL04** are the first independent assignments. The owner has authorized implementation and validated commits. The earlier completion authorization remains historical evidence for the completed original backlog.
| Story | Why first | Writable ownership | Completion evidence |
| --- | --- | --- | --- |
| CL01 | Prevents false passing configuration tests before normalization | DI builder tests only | Valid fixtures use production normalization; arbitrary exceptions fail; focused tests pass without stores |
| CL03 | Fixes reproduced partial-startup resource retention | DI lifecycle, builder startup and dedicated lifecycle tests | Partial failure/timeout cleans up, late work retains cleanup ownership, and timers do not leak |
| CL04 | Removes broken commands and inconsistent startup | Root scripts, Docker helper, workspace tests and startup docs | Existing command targets, exact three-role research dev plan, consistent store set and failure propagation |
These three assignments have disjoint authored paths. For a solo maintainer, start at most two implementers concurrently and retain capacity for independent review; rotate the third task into the next free slot. Test-process module mocks, native build outputs and database fixtures must remain isolated. This plan does not launch agents.
## Execution contract
- Read the task, current manifest, approved relevant architecture decisions and [QUALITY-GATES.md](QUALITY-GATES.md). Scope is the selected story, not permission to implement neighboring cleanup.
- `ready` means code prerequisites are satisfied. The current top-level `execution_authorized` is true following the owner’s explicit cleanup implementation request. Scope remains these stories; conditional performance/product tasks are excluded.
- Use one focused branch/worktree per implementation when multiple agents are used. Claim exact files and write locks in the manifest before edits. An unexpected overlap requires coordination before changing the shared file.
- Preserve Rust financial semantics, strategy targets/state, exact financial output, command idempotency, receipt recovery, run/outbox atomicity, leases, paper recovery and original reproduction inputs.
- Preserve historical result readers, retained source/build artifacts, reviewed calculation APIs and useful legacy research. No broad dead-code deletion or native-export removal follows from this plan.
- Keep the existing .env files. Do not rotate, print or remove credentials. No development trading database is a test fixture.
- Run the story's focused tests and type checks. The integrator runs `bun run check` on the combined batch and the relevant disposable PostgreSQL/browser suites when the affected boundary requires them. Report skipped/unavailable checks honestly; do not add benchmarks to a cleanup story.
- Rebuild changed workspaces/worker artifacts in the assigned checkout before tests that consume built packages. Native/economic fixtures must not be rebaselined to conceal changed behavior.
- Review failure behavior and compatibility independently before marking a task done. Record exact commands/results and accepted commit references in the manifest. User authorization controls commits, pushes, PRs and any subsequent implementation.
## Scope deliberately left for later
The six original conditional tasks remain deferred with their existing triggers. This cleanup does not resume performance profiling, shared feature caches, result paging, a Rust strategy DSL or additional optimization.
The AI-assisted data-exploration/MCP/notebook workflow needs its own product stories after its tools and interfaces are agreed. CL05/CL06/CL07 make those clients easier to add; they do not implement or approve them. Research-page redesign, browser IDEs, fitted-model/forward-label validation, new financial policies and multi-asset/live activation are outside this cleanup epic.
The existing financial core and failure-oriented regression suites are preservation targets. Large financial modules are not split merely to reduce line counts.

View file

@ -1,302 +0,0 @@
# First development wave: four independent assignments
**First wave completed and committed on 2026-10-22.** The owner authorized implementation with “make a commit and start,” then authorized the implementation and handoff commits with “do all comits.” The assignments and execution record below are retained for traceability. Subsequent wave authorization is tracked in the canonical manifest and ROADMAP; this historical record does not grant it.
Choose **C01, C03, C04, W01**. They have no code/ADR prerequisites beyond global execution approval and no shared authored source files. Recommend three implementers plus one coordinator/read-only reviewer; start C01/C03/W01 and rotate C04 into the first free slot. If runtime cleanup is more urgent than the interim funding fix, start C04 before C03. This is capacity management, not a dependency.
## Common execution contract
Each prompt below incorporates this contract:
- Read repository instructions, the task file, relevant ADRs and `docs/development/QUALITY-GATES.md`. Scope is the task, not permission to implement neighboring tasks.
- Planner claims the ID/write locks in the canonical manifest; implementation agents do not edit scheduling metadata. Use one branch/worktree per task from the recorded integration base.
- Inspect existing changes before editing. Preserve user work. Use only assigned writable files; additional required edits must be reported to the coordinator before expanding scope.
- Keep native builds, dependency symlinks and disposable test resources worktree-local. Verify workspace imports resolve into your worktree, not the original checkout. Do not share mutable addon/target output between concurrent agents.
- Before tests that import native code, build the addon from the assigned worktree if absent/stale, record its resolved path/hash, and do not count a pre-existing binary as validation. Generated native binaries/declarations are not authored changes.
- Do not alter shared financial contracts, schemas, root scripts, shared fixtures or another task's files. W01 alone may add a minimal frontend test dev dependency if necessary and must explain it.
- Run exact listed checks. Report baseline failures, unavailable dependencies and skipped checks honestly; do not install/provision resources beyond execution authorization. No tests against the development trading account/database.
- Supply focused diff, numerical expectations, test commands/results, risks and handoff notes. Independent review plus tests on the integrated change are required before “done.” Do not commit or create a PR without explicit approval.
## Ownership and integration
| Task | Writable implementation scope | Dedicated tests | Dependencies / later impact |
| --- | --- | --- | --- |
| C01 | Legacy Rust backtest engine/results | Inline Rust; optional native-terminal-equity.test.ts | No prerequisite; arithmetic fixture retained during later financial migration |
| C03 | TS execution model/SimulationExecution | fee-funding.test.ts | No prerequisite; closes a current fee hole without deciding the new account model |
| C04 | ModeManager | mode-lifecycle.test.ts | No prerequisite; unlocks C06 fail-closed composition |
| W01 | Backtest detail/control/API hook and shared websocket hook | backtest-run-controls.test.tsx | No prerequisite; unlocks W02 then W04 web release |
Each has disjoint authored files. C01/C03 may both run account tests, but against their own fixtures/resources. Do not parallelize W02 with W01 or C06 with C04. Shared financial contracts F01 onward have one coordinated owner, unlike these isolated legacy fixes.
## C01 — Native terminal valuation
Role: Rust financial-correctness engineer. [Task](backlog/tasks/C01.md). Priority P0.
### Exact Codex implementation prompt
```text
Implement only C01 under the Common execution contract in
docs/development/FIRST-WAVE.md. Read backlog/tasks/C01.md and the relevant quality gates.
Inspect the current native terminal liquidation and result projection. Preserve current
sizing, matching, liquidation thresholds, order policy and fee policy. After terminal
closing fills, recompute final account equity and replace the existing terminal-time
curve sample; do not append a duplicate timestamp or charge closing costs twice.
Add a deterministic internal fixture that buys exactly one share at4 from cash10,
with1% entry and exit fees and zero slippage. Liquidation at4 must leave cash,
final equity and finalValue at9.92, with total fees0.08. Do not derive fixture quantity
from production sizing. Add no-position, zero-fee, multiple-symbol and terminal
timestamp-uniqueness cases. Positions eligible for liquidation in these fixtures
must be flat. Preserve the existing micro-position liquidation threshold; if a
residual remains under that existing policy, its marked value still belongs in equity.
Writable files:
- apps/stock/engine/src/backtest/engine.rs
- apps/stock/engine/src/backtest/simple_results.rs
- inline Rust tests in those modules
- optionally test/integration/native-terminal-equity.test.ts, only if the existing
public API can exercise the same fixture without a testing-only exported API.
Read existing result-mapping/backtest-ledger integration tests but do not edit them
independently. Do not implement next-open matching, the new ledger, new ownership,
new risk policies or other backlog tasks.
Run the C01 commands below, building this worktree's addon before native integration
tests. Report exact results, fixture arithmetic and any existing limitations.
Do not commit, push or create a PR without explicit approval.
```
### Tests
Run from the assigned repository root:
```sh
cargo test -p engine --lib --offline
bun run --cwd apps/stock/engine build:debug
bun test test/integration/backtest-result-mapping.test.ts test/integration/backtest-ledger.test.ts
```
If the optional public-surface test is added, also run:
```sh
bun test test/integration/native-terminal-equity.test.ts
```
Definition of done: 9.92/0.08 fixture passes; closing fills counted once; curve/report reconcile; one terminal timestamp; no-position and multi-symbol behavior covered; existing adapters pass against the current worktree addon; no other economic policy changed.
## C03 — Fee-inclusive legacy funding check
Role: TS trading infrastructure/financial correctness. [Task](backlog/tasks/C03.md). Priority P0.
### Exact Codex implementation prompt
```text
Implement only C03 under the Common execution contract in
docs/development/FIRST-WAVE.md. Read backlog/tasks/C03.md and ADR-002's explicit
legacy-versus-canonical distinction before editing.
Keep the current TypeScript gross-exposure capital model, short/reversal behavior
and reducing-order exemption. Correct only the missing unpaid fee liability in
its non-reducing capital check. Include the proposed remaining order plus other
pending remaining commitments, using each order's frozen commission policy.
At fill, exclude the current order from the "other pending" set. Fees already paid
are already reflected in equity: do not count them again. Reuse existing decimal
helpers and existing pending-order state; no new reservation schema or cash-only model.
Writable files:
- apps/stock/orchestrator/src/execution/model.ts
- apps/stock/orchestrator/src/execution/SimulationExecution.ts
- test/integration/fee-funding.test.ts (new).
Use test/fixtures/execution.ts and existing execution/recovery tests as read-only
context. If another file is genuinely required, report it before expanding scope.
Required deterministic cases, with other existing risk limits configured so they
do not mask this capital guard:
1. Cash10000, buy100@100,1% fees rejects without financial mutation.
2. Buy99@100 succeeds; total fee99; cash1.
3. With no fill liquidity, one pending buy50@100 has computed commitment5050;
another50 would require10100 total and rejects. Cancellation releases the
first commitment and allows a valid replacement.
4. Fill the99-share order as10 then89 shares; total fees99 and final cash1.
Duplicate order/market events cannot add fees again.
5. Changing runtime commission configuration cannot alter a stored order's policy.
6. Existing short/reversal and reducing-order behavior is unchanged.
Do not implement canonical Rust reservations, new financing semantics, migrations,
strategy changes or new account models. Do not claim this patch prevents every form
of legacy borrowing; short-cover insolvency is outside this narrow scope.
Run the C03 commands below and provide exact outcomes. Do not commit or create a
PR without explicit approval.
```
### Tests
```sh
bun test test/integration/fee-funding.test.ts test/integration/order-execution.test.ts test/integration/strategy-recovery.test.ts
bun run typecheck
bun run test:contracts
```
Before merge, the integration owner also runs `bun run test:postgres` using the repository's disposable safety-database/Redis configuration in QUALITY-GATES.md. This is an integration gate, not authorization to touch the developer's DB.
Definition of done: exact numerical cases above; existing shorts/reducing-order tests unchanged; partial/cancel/duplicate/frozen-policy cases pass; no new schema or alternative simulator; disposable transaction/recovery checks pass before integration is accepted.
## C04 — Recoverable partial initialization
Role: TS lifecycle/reliability engineer. [Task](backlog/tasks/C04.md). Priority P1.
### Exact Codex implementation prompt
```text
Implement only C04 under the Common execution contract in
docs/development/FIRST-WAVE.md. Read backlog/tasks/C04.md and the existing ModeManager
and mode-lifecycle tests.
Make initialization recoverable at the resource-lifecycle boundary. Validate before
side effects. Register cleanup for every stage that may partially acquire resources,
not only after it reports success. On failure stop admission/market feed first,
then attempt all applicable cleanup even if one cleanup throws. Preserve the
original initialization error. Clear failed readiness/config/engine state and allow
a later initialize call to succeed. Preserve the current successful ordering and
the live-disabled guard.
Writable files:
- apps/stock/orchestrator/src/core/ModeManager.ts
- test/integration/mode-lifecycle.test.ts.
Inject failures separately in execution initialization, storage initialization,
strategy restoration and market-feed initialization. Cover cleanup of the failing
stage as well as previously completed stages; cleanup exceptions; successful retry;
no modeChanged success event on failure; live rejection before side effects.
Do not redesign dependency injection, container composition, research isolation or
C06. Do not invent a native dispose API that does not exist. Keep the change focused
on real lifecycle resources and existing methods. Run the C04 commands below and
report outcomes and remaining limitations. Do not commit or create a PR without
explicit approval.
```
### Tests
```sh
bun test test/integration/mode-lifecycle.test.ts
bun run typecheck
bun run test:contracts
```
The existing fixture may load the native TradingEngine; build the assigned worktree addon if required without editing Rust source.
Definition of done: all four failure stages clean up acquired resources, feed cleanup precedes dependent teardown, one cleanup failure does not skip others or mask the original error, retry succeeds, success-path order/live-disabled behavior unchanged, no C06 composition changes.
## W01 — Reliable existing web run controls
Role: React asynchronous-state/test engineer. [Task](backlog/tasks/W01.md). Priority P1.
### Exact Codex implementation prompt
```text
Implement only W01 under the Common execution contract in
docs/development/FIRST-WAVE.md. Inspect existing run selection, cancellation,
polling/websocket behavior and native control limitations before editing.
Preserve the existing v2 APIs and persisted run state as authority. Wire cancel
into the detail controls. A202 acknowledgement is not terminal cancellation:
show requested state until persisted cancellation/completion/failure is read.
Use one nonoverlapping poll authority and selection-generation/abort guards so
late status, results, errors or finally handlers for A cannot replace selected B.
Clean subscriptions/timers on selection change and unmount. Websocket messages
invalidate/refetch authoritative state; do not create a second state store.
Fix the existing reconnect reference/cleanup bug or demonstrate a reliable polling
fallback, with tests covering the chosen recovery behavior.
Expose only supported shared execution controls. Hide/disable native-unsupported
server pause/resume/speed controls without implementing those features or a
capability registry. Preserve chart playback and legacy backend endpoints.
Distinguish loading, retriable error, cancelled/failed, successful zero-trade data,
and completed-but-missing result.
Writable files:
- apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx
- apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts
- apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx
- apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts
- apps/stock/web-app/src/hooks/useWebSocket.ts
- test/integration/backtest-run-controls.test.tsx (new)
- apps/stock/web-app/package.json and bun.lock only if one minimal DOM test
dev dependency is necessary; explain the choice first.
Read backend backtest-v2.service.ts, backtests-v2.routes.ts, websocket/run-updates.ts
and RustBacktestAdapter.ts as context only. Do not change backend source, economics,
provenance, database schemas, queues, strategy contracts or other screens.
Add focused tests with deferred requests, controlled timers and actual component/
hook interactions. Existing analytics-ui tests use server rendering; do not claim
they prove interactions. Reuse Bun/React; no second end-to-end framework. W04 owns
real browser E2E. Run the W01 commands below and report exact results and missing
coverage. Do not commit, push or create a PR without explicit approval.
```
### Context and tests
Read-only backend context:
- `apps/stock/web-api/src/services/backtest-v2.service.ts`
- `apps/stock/web-api/src/routes/backtests-v2.routes.ts`
- `apps/stock/web-api/src/websocket/run-updates.ts`
- `apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts`
```sh
bun test test/integration/backtest-run-controls.test.tsx test/integration/analytics-ui.test.tsx test/integration/backtest-result-mapping.test.ts test/integration/backtest-workflow.test.ts
bun run typecheck
bun run test:contracts
```
Definition of done:
- Deferred getRun(A) and getResults(A), including their error/finally paths, never overwrite B.
- At most one poll in flight per mounted selection; prior requests cannot publish after switch/unmount.
- Pending cancellation may be immediately terminal; active cancellation remains requested until persisted acknowledgement.
- Failure/cancellation never render as success; zero trades and unavailable result are different.
- Unsupported execution controls absent/disabled; chart playback preserved.
- Reconnect or polling recovers persisted status; interaction regressions pass.
- No browser-coverage claim without a browser run; W04 remains the release gate.
## Combined wave gate
Independent reviewer checks scope and exact fixtures, then the integrator runs relevant native, TS, contracts and disposable SQL checks on the combined branch. Run full `bun run check` once at integration, reporting unrelated baseline failures explicitly. No economic/provenance certification is implied by this wave; same-bar timing and canonical Rust ownership/risk remain subsequent work.
The planner records accepted evidence/commit references only when commit authority exists, updates dependencies once integrated, and then offers C02/P01/O01 plus C06 (after C04) and W02 (after W01). F01/D01 also require their ADR approvals.
## Execution record — 2026-10-22
Planning snapshot: `1148673`. C01/C03/C04/W01 were implemented in isolated worktrees, reviewed independently of their authors, integrated and validated together, then committed with owner approval. The canonical manifest records `done` and each implementation commit: C01 `74ba3b9`, C03 `a21a1b8`, C04 `3d26da0`, W01 `67f12b4`. No later task, push, PR or trading operation was started.
| Task | Verified behavior |
| --- | --- |
| C01 | Terminal liquidation costs enter the final equity mark exactly once. The one-share fixture ends at 9.92 with 0.08 fees; same-time curve samples are replaced. Existing micro-position policy is unchanged. |
| C03 | Legacy non-reducing funding checks include unpaid proposed and pending-order fees under frozen policies. The 100-share fixture rejects; 99 shares leave cash 1 after fees 99. Partial fills, cancellation and duplicates are covered. |
| C04 | Failed initialization cleans every attempted resource stage, preserves the original error and clears runtime state; cleanup failures do not prevent subsequent cleanup or retry. |
| W01 | Selection-owned polling rejects stale responses, cancellation waits for persisted state, reconnects recover, and failed/cancelled/missing results differ from successful zero-trade results. Unsupported execution controls are removed; chart playback remains intact. |
Integration verification (all passed; overlapping suites are not additive test counts):
| Command / gate | Result |
| --- | --- |
| `CARGO_BUILD_JOBS=2 bun run check` | All repository gates passed, including build, types, contracts, tooling, utilities, calculations, integration, native, lint and secret audit. |
| `CARGO_BUILD_JOBS=2 cargo test -p engine --lib --offline` | 37 passed, 0 failed. |
| Financial/lifecycle suite below | 66 passed, 0 failed, 389 assertions. |
| Exact W01 four-file command above | 68 passed, 0 failed, 406 assertions against the integrated checkout. |
| `bun run test:postgres` with disposable fixtures | 45 passed, 0 failed, 202 assertions; isolated `stock_bot_safety` database and Redis DB15, never the development trading database. |
| Scoped formatting/lint and `git diff --check` | Passed. |
Financial/lifecycle command:
```sh
bun test test/integration/fee-funding.test.ts test/integration/order-execution.test.ts test/integration/strategy-recovery.test.ts test/integration/mode-lifecycle.test.ts test/integration/native-terminal-equity.test.ts test/integration/backtest-result-mapping.test.ts test/integration/backtest-ledger.test.ts
```
The native addon was rebuilt from the integrated source; its path/hash are recorded in the manifest. Native subprocess builds/IPC and disposable database access required sandbox escalation. Existing Rust warnings and frontend build warnings remain; no unrelated cleanup was included. W01 adds pinned `happy-dom@21.0.4` for 18 React interaction tests under Bun, not a second test runner or a browser E2E claim.
Limits: this wave does not fix same-bar look-ahead execution, establish canonical Rust financial authority, change legacy short/reducing-order funding semantics, or satisfy W04's real-browser release gate. ADR-002/003/007 remain approval-gated. Worktrees are retained for handoff; temporary PostgreSQL/Redis fixture containers were removed. At this wave's completion C06/W02 became ready; their subsequent authorization/status is recorded in the canonical manifest.

View file

@ -1,80 +0,0 @@
# Independent skeptical backlog review
Reviewed against repository baseline `b7aeca4`, 2026-10-22. **Planning changes only.** Evidence below is code inspection, not a claim that tests/benchmarks ran. Verified = directly visible code/plan behavior; Likely = engineering consequence not benchmarked; Needs investigation = requires execution or product approval.
## Verdict
The direction is sound, but the original backlog made several optional optimizations prerequisites, sequenced financial ownership after the ledger, and left agents to resolve monetary/timing semantics. Those are more important than adding abstractions or increasing task count.
Keep the modular monolith, TypeScript authoring and current product/durability infrastructure. Establish one small Rust financial kernel with two adapters: resident research sessions and transactional paper transitions. Do not force statistical reports, orchestration or every indicator into Rust.
## Ranked findings and dispositions
| Severity / evidence | Problem | Revision and acceptance consequence |
| --- | --- | --- |
| Critical / Verified contract gap | Rounded average price was insufficient as authoritative cost basis; partial disposals could create residual money | ADR-002/F02 store remaining cost amount; partial proportional allocation, exact final residual. Fixture cost5/quantity3 must release5 exactly |
| Critical / Verified plan contradiction | F02 built aggregate positions before F03 introduced ownership | Merge F03 into F02. Owner books exist at first fill; A/B attribution and aggregate reconciliation are initial ledger tests |
| Critical / Verified boundary gap | Paper pure snapshot API could imply full serialization/cloning per research event | ADR-005 specifies one internal apply kernel. Resident research mutates private state directly; paper stages and persists within existing SQL transactions. Preserve ordered effects/checkpoints |
| Critical / Verified ambiguity | Arbitrary TS callback determinism was treated too broadly; barrier state/RNG/intent semantics were incomplete | ADR-004/F07/S01 use progress/decisionBatch/complete, same ledger revision for all callbacks, staged state and per-strategy RNG; exceptions fail the attempt; no target/order mixing in v1. Trace replay is not proof of arbitrary-code determinism |
| High / Verified scope conflict | C03 mixed a narrow fee bug with a new financing policy | Keep legacy nonreducing gross-capital model/reducing exemption; add unpaid remaining fees only. Canonical cash reservations belong to F04 |
| High / Verified dependency contradiction | F05 acceptance needed F06 replay, while F06 depended on F05 completion | Matcher tests complete F05; replay-dependent release assertions belong to F06. Release gates are separate from implementation prerequisites |
| High / Verified timing gaps | Multi-timeframe feeds could duplicate execution liquidity; DAY targets and account risk-session clock were ambiguous | ADR-003/F04–F06 require one execution series per instrument, feature-only additional frames, explicit DAY/target expiry and account calendar; next-open and persistent halt fixtures |
| High / Verified avoidable work | A new legacy research runtime would be replaced again after Rust cutover | Narrow C06 to fail-closed composition: shared paper accepts existing isolated native research only; standalone legacy TS research cannot initialize/activate paper. Preserve current busy guard |
| High / Verified artificial prerequisites | Shared cache, all builtins, resident dataset reuse and reporting blocked useful strategy/paper/batch work | Remove D04→S01, F08→S03, P03→P04; S02 ports one SMA first. Actual isolation and provenance gates remain |
| High / Verified repeated work | F06 introduced replay then P02 replaced its queue | Merge P02 into F06: sorted immutable event cursor once; deterministic ties and scaling evidence |
| High / Verified product sequencing | Workspace/catalog/picker completion blocked independent experiment/backend/AI work | Remove unrelated UI prerequisites. Keep W04 browser coverage as release gates; R06 offers summary projections, R09 only gates regime panels on S05 |
| High / Verified missing dependency | Validation artifacts/findings referenced R03 despite experiments no longer depending on research metadata | R08 persists immutable experiment-owned reports; R09 save/link-finding requires R03 only when enabled. Basic validation remains independent |
| Medium / Verified ambiguous evidence | Publishing, retrying and walk-forward semantics allowed inconsistent interpretations | R01 distinguishes idempotent publish from intentional revision; R06 retries use fenced attempts; R08 declares reset-segment capital/state and excludes warmup from performance |
| Medium / Verified excess infrastructure | Generic capabilities, metric-validation store, migrations framework and blanket bug toggles could grow from vague criteria | W01 uses existing APIs; R03 references retained metric paths; O01 locks existing migration transaction; no toggles restoring known defects |
| Medium / Likely optimization overreach | Universal caching/native analytics and arbitrary DSL speed thresholds increased work before measurement | F08 reuses reviewed TS statistics; five optional tasks stay conditional; P01 measures existing paths only |
| Needs investigation | Actual callback cost, resident-cache benefit, decimal throughput, platform bitwise feature reproducibility | Measure P01 then instrument F06/F07/S01/P04; no invented speedup/throughput claims |
## Repository anchors behind the decisions
- Terminal liquidation follows the last mark: [engine.rs:135](../../apps/stock/engine/src/backtest/engine.rs#L135); result reads the curve: [simple_results.rs:308](../../apps/stock/engine/src/backtest/simple_results.rs#L308). C01 remains a narrow current defect fix.
- Legacy financing checks gross exposure without unpaid fees: [model.ts:234](../../apps/stock/orchestrator/src/execution/model.ts#L234). Fill-time policy and existing TIF handling: [SimulationExecution.ts:92](../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L92), [line168](../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L168). C03 must not replace that entire model.
- Initialization readiness precedes a shutdown early return: [ModeManager.ts:33](../../apps/stock/orchestrator/src/core/ModeManager.ts#L33), [line157](../../apps/stock/orchestrator/src/core/ModeManager.ts#L157). C04 owns lifecycle, C06 owns composition.
- Shared TS research preparation changes ModeManager: [container.ts:101](../../apps/stock/orchestrator/src/container.ts#L101). The existing [NativeBacktestWorker](../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts) and [fenced dataset runner](../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190) are reusable.
- Historical events use repeated queue insertion: [backtest/mod.rs:138](../../apps/stock/engine/src/backtest/mod.rs#L138). Implement efficient traversal during replay replacement, not in a later task.
- Reviewed reporting math already exists: [return-statistics.ts:24](../../libs/calculations/src/analytics/return-statistics.ts#L24). Reuse it over authoritative ledger/session projections instead of rewriting statistics in Rust.
- Websocket close clears the reference before a reconnect equality check: [useWebSocket.ts:124](../../apps/stock/web-app/src/hooks/useWebSocket.ts#L124). Existing [detail controls](../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L379) and [durable submission](../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211) need focused repair, not replacement.
- Migration checking is outside the application transaction: [migration-runner.ts:59](../../apps/stock/web-api/src/migrations/migration-runner.ts#L59). O01 must acquire the lock and check/apply on the same client.
- Preserve transaction/recovery behavior: [StrategyRecovery.ts:151](../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151), [Postgres execution tests](../../test/postgres/order-execution.test.ts), [strategy recovery tests](../../test/postgres/strategy-recovery.test.ts).
## Scope accounting
| Disposition | IDs | Rationale |
| --- | --- | --- |
| Merge into financial contract | C05 → F01 | Economic fixture corpus and protocol evolve together; no separate expected-failure harness project |
| Merge into owner-aware ledger | F03 → F02 | Avoid migrating a ledger immediately after writing it |
| Merge into dataset v2 | D03 → D01 | Availability, coverage and eligibility are one schema migration |
| Merge into replay | P02 → F06 | Implement traversal once |
| Conditional after measurements | D04, P03, P05, P06 | Shared features, cross-trial reuse, large details, DSL respectively |
| Conditional after real operational need | O02 | Mandatory run/paper diagnostics already belong to W01/F07/S04 |
Result: **43 scheduled + 5 conditional work items**, with four merged traceability records. This does not promise a percentage reduction in engineering time: larger surviving tasks still contain the essential tests. Eliminated work is duplicated migration, needless porting, optional framework scope and artificial waiting.
## Financial/strategy boundary that agents must not reinterpret
1. Rust accepts validated intent envelopes, applies risk/matching/ledger transitions and emits owned effects.
2. TS chooses strategy logic and allocation preferences, not cash/P&L/fill calculations.
3. All due callbacks see one immutable account revision; admission order is stable and declared.
4. Strategy state and RNG are staged at barriers. A risk rejection is a committed decision outcome; a thrown callback is an attempt failure.
5. Paper SQL remains durability authority; Rust remains financial authority. Do not publish uncommitted staged effects.
6. One execution source per instrument; higher-timeframe observations are features, not extra liquidity.
7. Deterministic financial replay uses fixed inputs/decisions. Strategy recomputation additionally requires controlled APIs and pinned runtime/artifacts; same-process arbitrary JS is not a sandbox.
8. Statistical analytics can remain TS without being a competing simulator. Reports must consume canonical ledger/session values, never reconstruct a second account.
## Revised ordering
Critical path: F01 → F02 → F04 → F05 → F06 → F07 → S01 → S02 → R05 → R06. D01/P01 join replay, C02 joins NAPI, F08 and immutable retained artifacts join R05. S03 branches from S01/C06 without waiting for report/UI work. Parallel trials P04 need canonical sessions/experiments and measurement, not caches. AI A01/A02/A03 need bounded APIs/isolation/validation, not a browser IDE.
First wave: **C01, C03, C04, W01**. See [exact prompts and definitions of done](FIRST-WAVE.md). Use three implementation slots and a separate review/integration role. All four can be assigned independently; rotate the fourth to preserve review capacity.
## Remaining decisions and limitations
Approve monetary rounding/long-only scope, execution timing/terminal policy and AI trust model before dependent tasks. First-wave fixes do not settle those policies and do not make the legacy backtester suitable for performance claims.
No application tests or benchmarks were run for this review. Source inspection establishes the cited control-flow issues; numerical acceptance fixtures are specifications for implementation. The plan must be revalidated if source/contracts change before execution.
Planning validation passed: 75 planning files; 52 unique task IDs (43 scheduled, 5 conditional, 4 merged); 77 implementation edges with no cycle; no scheduled dependency on deferred/merged work; first-wave readiness; task/manifest dependency consistency; 749 relative link references and source line bounds; whitespace checks. Git changes remain confined to docs/development, HEAD remains b7aeca4, and execution_authorized remains false. Independent read-only core/product reviews found no remaining first-wave blocker; the product review's report-storage dependency gap was corrected as described above.

View file

@ -1,781 +0,0 @@
# Revised development roadmap
Current status — October 28, 2026: **113/113 selected tasks complete**, with five optional extensions deferred and four merged redirects in the [manifest](backlog/manifest.json). All 14 whole-application cleanup tasks (CL22–CL35) are committed and verified; see the [execution record](architecture-cleanup-execution.md). No selected task remains active or ready.
The cleanup establishes explicit shared API/orchestrator modules, a public strategy authoring contract, shared validated HTTP responses, one research-service composition point, isolated historical writers, container-owned ingestion initialization and correct queue draining. It preserves the authoritative Rust financial engine and durable execution behavior.
The [conditional review](conditional-review.md) records raw measurements, preserved invariants, verification and all seven dispositions. D04/P03/P05/P06/CL21 are not selected now: caching, residency, paging and DSL work need representative bottleneck evidence; replay extraction needs a concrete upcoming change. They remain unimplemented, not silently cancelled or counted as done. Performance is no longer paused. Research/paper readiness stays distinct, native execution is explicitly unverified until run start, and real paper/live activation and multi-asset financial-policy gates remain unchanged.
Counts and statuses above supersede historical milestones below.
## Cleanup implementation — October 26, 2026
The [cleanup plan](CLEANUP.md) adds 13 scoped stories under E10, grounded in the current code audit. The original completion record below remains historical evidence. Current task IDs, states, dependencies and locks are in the [manifest](backlog/manifest.json); the six conditional tasks remain deferred.
The owner authorized implementation and validated commits after planning. All 13 cleanup stories are implemented, validated and independently accepted; the review corrections are committed in `b4ac6460`. [Execution evidence](cleanup-execution.md) records exact checks and limitations. The historical first wave was CL01/CL03/CL04, followed by configuration, shared research code, backend and frontend cleanup.
**The original 45/45 scheduled tasks are complete.** The canonical Rust engine, TypeScript research/workbench, bounded worker pool, isolated candidates, AI evidence workflow and human-reviewed paper promotion are validated. Implementation commits: `bbf0dd4`, `26b9726`, `25b5cbf` (R07 measurement `ab08db8`). Six conditional tasks remain deferred; four merged IDs remain redirects. This is scheduled-backlog completion, not live-trading activation.
Authorization update: the owner requested “commit and continue with the rest of the tasks till 100%”. Commit `0c6aec4` records the validated stored-source slice. Complete scheduled R05/R07/S06/P04/A01–A04 with independent review. Required table/concurrency measurements resume; conditional optimizations remain evidence-driven. The default cutover supports canonical single-asset research; unsupported multi-asset policy and real paper/live activation remain gated.
## Strategy and review outcome
Use TypeScript for strategies, research and the web product; one Rust kernel owns money, risk, matching and replay. Preserve durable decisions/checkpoints, transactional execution, frozen datasets, reviewed calculations and failure-oriented tests.
The skeptical review established 43 scheduled tasks, 5 conditional tasks and 4 merged redirects. F09/P07/P08 added three IDs; the owner subsequently deferred P08. The original delivery plan retained **45 scheduled + 6 deferred/conditional + 4 merged = 55 IDs**; the cleanup extension adds 13 for a current total of **68 retained IDs**. See [review findings and dispositions](REVIEW.md), [complete index](backlog/README.md) and [canonical manifest](backlog/manifest.json).
The existing web workbench improves during engine migration. Legacy results remain labelled; fixing controls or terminal valuation does not make same-bar economics trustworthy. C06 blocks shared-runtime legacy research rather than building another soon-to-be-retired simulator runtime.
## Decisions to approve
| Decision | Direction | Approval |
| --- | --- | --- |
| [ADR-001](architecture/decisions/001-ownership.md) | TS product/strategy code; Rust financial authority; retain monolith and workers | User-mandated |
| [ADR-002](architecture/decisions/002-financial-policy.md) | Maintained checked decimal; 8-place half-up postings; authoritative remaining cost; owner books from day one; initial cash-funded long-only account | Approved by owner, 2026-10-22 |
| [ADR-003](architecture/decisions/003-time-and-datasets.md) | Availability/event phases; open-only next-interval matching; explicit zero-latency convention; mark-open terminal policy; account risk-session clock | Approved by owner, 2026-10-22 |
| [ADR-004](architecture/decisions/004-strategy-boundary.md) | NAPI pull sessions in existing workers; tagged decision barriers; IPC for untrusted code; no embedded JS | Approved by owner, 2026-10-22 |
| [ADR-005](architecture/decisions/005-durable-cutover.md) | One Rust transition kernel; resident research state; private staged paper state under existing SQL transactions | Approved by owner continuation, 2026-10-23; paper activation separately gated |
| [ADR-006](architecture/decisions/006-research-product.md) | Existing API/queue/database; immutable versions, provenance and evidence retention; no laboratory framework | Approved by owner continuation, 2026-10-23 |
| [ADR-007](architecture/decisions/007-ai-boundary.md) | Isolated untrusted code, research-only permissions/budgets; human-only paper promotion; live disabled | Implementation authorized by owner completion instruction, 2026-10-24; paper activation human-only |
| [ADR-008](architecture/decisions/008-performance.md) | Measure actual paths; cursor replay and bounded trials; caching/DSL only when measured | Scheduled measurements approved by owner completion instruction, 2026-10-24; conditional optimization gates unchanged |
Long-only is the approved first canonical model, not deletion of short history or a silent change to current paper accounts. Short/margin support still needs a separate approved borrowing policy and fixtures. C01/C03/C04/W01 preserve the legacy behavior described in their task scopes.
**Pre-default multi-asset risk decision:** F06 review confirms existing ordered mark transitions can latch an intermediate portfolio loss/drawdown halt even when simultaneous offsetting moves leave final equity unchanged. Additive F06/F07 work can proceed under the current deterministic policy, but R05 must not enable canonical multi-asset default research until the owner explicitly accepts the disclosed versioned approximation or approves a coordinated atomic-mark correction with fixtures. Determinism alone does not resolve this modeling issue.
## Milestones
| Milestone | Tasks | Exit criterion |
| --- | --- | --- |
| M0: safe interim behavior | C01/C02/C03/C04/C06; O01; P01 | Scoped terminal/funding/input fixes; failed init cleans up; shared-runtime research rejected; migration lock and honest baseline measurements |
| M1: usable current workbench | W01–W04 | Save, submit, cancel, inspect and reopen tested in browser; unsupported controls hidden; legacy economic limitations visible |
| M2: canonical Rust/TS research | F01/F02/F04–F09, D01, S01/S02; R01/R10/W03/C06 then R05; P07 measurements | Owner-aware finance, deterministic replay, compact results, one TS strategy and retained input provenance work through durable runs |
| M3: useful research product | R02/R03/R04/R11/R12 | Catalog/workspace/dataset selection and original reproduction; metadata/UI proceed alongside engine work |
| M4: batch research and validation | R06–R09, P04; S05 when ready | Bounded sweeps, summary comparisons, OOS/reset-segment walk-forward and measured worker scaling; regime panels only with S05 |
| M5: paper parity and AI research | S03/S04, A01–A04 | Recovery parity, operator readiness, isolated bounded AI experiments and evidence-linked human paper promotion |
| M6: remove duplicates / optional speed | S06; conditional D04/P03/P05/P06/O02 | Retire duplicate economics only after cutover proof; optional work requires demonstrated need |
Rows are outcomes, not a sequential waterfall. S03 does not wait for research UI or statistical reporting; basic experiments do not wait for regime models or feature caches.
## Critical path and parallel lanes
```mermaid
flowchart LR
F01[Contract + economic fixtures] --> F02[Owned ledger] --> F04[Risk + reservations] --> F05[Matcher]
F05 --> F06[Deterministic cursor replay]
D01[Availability-aware eligible datasets] --> F06
P01[Existing-path measurements] --> F06
F06 --> F07[Bounded NAPI sessions] --> S01[TS decisions] --> S02[One SMA]
F07 --> F09[Compact financial projections] --> F08
F07 --> P07[Representative replay profiling]
C02[Boundary integrity] --> F07
F06 --> F08[Canonical projections + reviewed TS statistics]
S02 --> R05[Durable canonical runs]
F08 --> R05
PRODUCT[Versions / retained artifacts / safe submission] --> R05
C06[Runtime containment] --> R05
R05 --> R06[Bounded experiments] --> P04[Measured parallel trials]
R06 --> R08[Chronological validation]
R06 --> A01[Research authorization] --> A02[Untrusted code isolation]
R08 --> A03[AI evidence loop]
A02 --> A03
S01 --> S03[Durable Rust paper adapter]
```
The full [dependency graph](backlog/dependencies.mmd) includes all code and decision gates. Solid task edges are implementation prerequisites. Dotted task edges are release/conditional gates, not blockers to integrating component work.
After approval, run one financial-core owner alongside one web/product owner and one data/benchmark/metadata owner. Serialize shared DTOs, migration registry, worker protocol and actual overlapping files. Core tasks F01/F02/F04/F05 must not be split among agents simultaneously.
## First wave: four independent assignments
Completed wave; the table records its original rationale. Exact prompts, paths, commands, commit references and verification results: [FIRST-WAVE.md](FIRST-WAVE.md).
| Task | Why now | Ownership / unlock |
| --- | --- | --- |
| [C01](backlog/tasks/C01.md) | Final native equity currently omits liquidation costs | Legacy Rust engine/results only; preserves a known arithmetic fixture for migration |
| [C03](backlog/tasks/C03.md) | Existing gross-capital guard ignores fee liability | TS execution model only; safer interim paper behavior without a new financing model |
| [C04](backlog/tasks/C04.md) | Partially initialized runtime can retain resources | ModeManager lifecycle only; unlocks C06 containment |
| [W01](backlog/tasks/W01.md) | Current user-facing cancellation/status can mislead | Frontend controls/hooks only; unlocks W02 and the tested workbench |
Recommend **3 simultaneous implementers**, reserving one slot for coordination/independent review. Start C01 + C03 + W01; rotate C04 into the first freed slot, or start C04 first if runtime containment is the immediate operational need. These four have no mutual code dependencies and disjoint writable files. Four concurrent implementers are technically possible but not recommended without separate review capacity.
O01/P01, W03 and W04 are committed. W04 adds validated real-browser end-to-end verification of the existing workbench. F01/D01 passed integrated validation and are committed; F02/D02 passed integrated validation and await acceptance/commit, while subsequent tasks remain prerequisite-gated.
## Second-wave handoff — 2026-10-22
All three tasks are `done` / `validated_committed` following owner approval: C02 `ee670a3`, C06 `43ffb54`, W02 `fe00ecd`. Worktrees are retained under `/tmp/stock-bot-wave2.M9vHDK/`.
| Task | Implemented and verified |
| --- | --- |
| C02 | Whole-load native validation preserves previously admitted data on any invalid row. Indexed errors cover malformed rows, OHLCV/VWAP, timestamps and unsupported types. 1001ms/1999ms remain distinct. Identical/conflicting duplicates and decreasing timestamps now reject explicitly; optional VWAP and zero volume remain accepted. |
| C06 | Default paper composition uses native research. Legacy TS requires explicit `role: 'research-only'`; startup and both exposed mode initializers reject cross-role activation before effects. Real paper account/ledger/checkpoint hashes and lifecycle stay unchanged through native success/cancel/failure jobs, and the paper feed continues afterward. No second execution framework was added. |
| W02 | Saved configuration and dataset evidence are distinguished from mutable legacy display fallbacks. Missing artifact/build versions stay unknown; known metric placeholders are unavailable while measured TS zeros remain visible. Limitations appear beside performance, and mutable legacy capital cannot fabricate cash profit. No stored results or financial calculations were rewritten. |
Combined integration gates:
- `CARGO_BUILD_JOBS=2 bun run check`: passed all gates; 54 tooling, 43 utility, 35 calculation, 293 integration and 37 Rust tests, with no failures. Build, typecheck, contracts, lint and secret audit passed. The 47 native bridge cases are included in integration, not an additional count.
- `bun run test:postgres` against disposable `stock_bot_safety` PostgreSQL and Redis DB15: 47 passed, 267 assertions. Includes two real-ledger research-isolation regressions. Temporary fixture containers were removed after validation; development databases/services were untouched.
- `git diff --check`: passed. All 21 authored implementation/test files match reviewed worktrees; the rebuilt integration addon hash is in the manifest.
Native subprocess builds/IPC and fixture networking required sandbox escalation. Existing Rust/frontend build warnings remain. Explicit linting of the old W01 test harness still reports its unchanged test-only curly findings; the repository lint gate and new scoped code checks pass. No real-browser E2E coverage is claimed here.
Limits: composition guards are not an untrusted-code sandbox; same-bar execution, canonical Rust accounting and owner-aware funding remain future tasks. ADR-002/003/004 still gate F01, and ADR-007 gates AI isolation. No push, PR or trading operation occurred. Subsequent O01/P01 work is tracked separately in the manifest.
## Third-wave handoff — 2026-10-22
O01 and P01 are independently reviewed and `validated_committed`: O01 `bba5aa1`, P01 `2e851ec`. Four implementation/test files were integrated from isolated worktrees under `/tmp/stock-bot-wave3.VjJvWX/`. The owner subsequently authorized W03 continuation.
- **O01:** Startup migrations acquire one transaction-scoped advisory lock on the same client before table initialization, discovery, checks, application and recording. The additive allowlist and SQL scripts are unchanged. Real PostgreSQL tests prove competing-client blocking, SQL/record failure rollback and retry, destructive-script exclusion, and preservation of saved runs, datasets, ledger and checkpoints.
- **P01:** `bun run scripts/benchmark-research.ts` runs a tiny deterministic self-test; `--measure` runs 1k/10k total-bar workloads over 1/10 assets. Three SMA configurations repeat twice per fresh process, with two processes per workload. Source/artifact/runtime/host/seed identities, raw phases, result bytes, RSS and economic hashes are retained. Existing dataset benchmarking is unchanged; no engine or financial behavior changed.
Combined gates passed: `CARGO_BUILD_JOBS=2 bun run check` (58 tooling, 43 utility, 35 calculation, 293 integration and 37 Rust tests; zero failures), plus `bun run test:postgres` (51 tests, 301 assertions). The four new migration cases and four benchmark cases are included in those totals. Explicit ESLint on all four files, standalone strict benchmark TypeScript checking and `git diff --check` also passed. Temporary PostgreSQL/Redis containers and their disposable data were removed afterward; development services were untouched. Worktrees and local measurement artifacts are retained.
Release measurements on Linux/x64, Ryzen 9 9950X3D, Bun 1.2.17 / rustc 1.88.0:
| Total bars / assets | Median whole-trial ms | Median bars/s |
| --- | --- | --- |
| 1,000 / 1 | 20.4 | 48,962 |
| 1,000 / 10 | 17.4 | 57,419 |
| 10,000 / 1 | 193.7 | 51,631 |
| 10,000 / 10 | 167.3 | 59,769 |
Whole-trial timing includes native construction/load/run, JS parsing, validation and hashing, but excludes fresh-process startup and initial dataset preparation (reported separately). All 48 trials reproduced economic hashes. Release addon SHA-256: `324f1e18de495791e9e53c4e36be39d0b165a11e13e9bcd82f5ca2b22d014674`. Raw timings and metadata: `/tmp/stock-bot-wave3.VjJvWX/research-release.json`; durable summary and hashes are in the manifest. The subsequent full check rebuilt the debug addon; its separate identity is also recorded.
These are single-host synthetic baseline measurements, not a speedup claim or financial certification. Reused JS inputs still reload the one-shot native engine each trial; native run includes serialization and logging. Native execution dominates the measured phases, but no internal bottleneck attribution is claimed. Callbacks, shared caches, queue/storage latency, allocation counts and parallel simulation remain explicitly unmeasured. 100k is opt-in and was not run. Linux peak RSS uses `/proc/self/status` VmHWM after Bun's `maxRSS` counter proved unreliable; unsupported platforms report unavailable.
No DSL, cache, scheduler or new service is justified by this wave. Same-bar execution and canonical ownership/funding remain gated future work. O01/P01 were committed with owner approval; no pushes, PRs or trading operations occurred.
## Fourth-wave handoff — 2026-10-22
W03 is independently reviewed and `validated_committed` as `9b9403e` following owner approval. Backend and frontend contributors used separate worktrees under `/tmp/stock-bot-wave4.iEBUTZ/` with a pinned API contract. All 18 implementation/test files match their reviewed versions.
- **Save / Save and run:** Web saves explicitly send `autoStart:false`. Save and run keeps the saved definition and original submission body/key through rejection or a lost response; retry does not save another definition. Immediate ref guards prevent duplicate clicks. Close waits for an unresolved definition write; closing after saving refreshes the list. Detail submissions have separate errors, explicit retry controls and late-navigation guards.
- **Durable admission:** `Idempotency-Key` is scoped to the existing verified operator or service principal, not a caller-supplied identity or browser-session nonce. A normalized intent fingerprint distinguishes retries from conflicts. Parent-row locking, immutable request snapshots and dispatch insertion remain in one transaction; the unique principal/key constraint also covers concurrent submissions across different definitions. Matching retries return the original run; changed intent returns 409 with existing 202/Location success behavior.
- **Migration / compatibility:** New additive `14-backtest-submission.sql` is admitted by O01's serialized startup runner. Legacy NULL-key rows remain readable. Omitted `autoStart` retains legacy auto-start, and keyless clients retain non-idempotent behavior. New web paths opt into explicit save and keyed submission. No financial simulation or paper-state behavior changed.
Combined validation:
- `CARGO_BUILD_JOBS=2 bun run check`: all gates passed; 60 tooling, 43 utility, 35 calculation, 310 integration and 37 Rust tests; zero failures. The 36 DOM interaction cases and 12 security cases are included in these totals, not additional suites.
- `bun run test:postgres`: 58 tests, 345 assertions, zero failures against disposable PostgreSQL/Redis, including a final rerun after the combined build. A database barrier proves both cross-definition contenders reach INSERT before release; tests verify one run/outbox, rollback/retry, numbering, principal separation, cookie renewal, frozen snapshots and preserved legacy rows.
- Explicit frontend typecheck, application-source lint, production build and `git diff --check` passed. Existing Rust/frontend warnings and the unchanged 12 curly findings in the old DOM test harness remain; the repository lint gate passes.
Independent review caught and corrected premature list refresh while saving and a submission error hidden after changing selected runs; dedicated real-component/route regressions cover both. Local logs and hashes are recorded in the manifest. Disposable test containers and their recreatable fixture data were removed; development services were untouched. Worktrees are retained.
Limits: UI retry identities are component-lifetime state, not recovery across reload/navigation. Definition POST response loss is not covered by run-submission idempotency. Operator/service scopes are the existing single-operator security model, not new user accounts or AI authorization. DOM tests do not prove browser layout, virtualized rows or full browser/API execution; that is W04. Existing native economic limitations remain visible and unchanged.
W03 was committed with owner approval; no push, PR or trading operation occurred. W04's subsequent execution is recorded below; canonical Rust finance still requires ADR-002/003/004 approval.
## Fifth-wave handoff — 2026-10-22
W04 is independently reviewed and `validated_committed` as `550d8b7` on base `95842c3`, following owner approval. The sole implementation owner used `/tmp/stock-bot-wave5.t2GVG7/w04`; the independent reviewer accepted the frozen five-file implementation and reran all browser cases. Integration and pre-commit verification preserved all five hashes. No production application source, financial behavior or business API changed.
- **Real product path:** Chromium uses the built frontend, authenticated existing routes/websocket projection, SQL repository, durable dispatcher and worker against isolated fixtures. Save-only creates no run/outbox; explicit submission, persisted progress, unsupported-control absence, completion, trades, limitations, frozen inputs and reopening survive navigation/reload.
- **Failure and race evidence:** Separate cases cover cancellation acknowledgement versus worker settlement, failed and zero-trade results, missing results/run, network failure/retry, actual client websocket disconnect/reconnect, and a delayed real API response after switching selected runs. The stale-response assertion waits for the exact old request to finish or fail before inspecting the selected run.
- **Native smoke:** The existing Rust adapter/subprocess executes 70 synthetic bars, persists native results and dataset provenance, and renders trades/reopened results. Fixed lifecycle fixture outputs are UI test data, not an alternate financial simulator or correctness oracle.
- **Harness:** `bun run test:e2e` requires explicit disposable `stock_bot_safety*` PostgreSQL, Redis DB15, a local build/addon and explicitly installed Chromium. It rebuilds the UI in production mode with same-origin API routing. It blocks external browser requests and unrelated fixture API routes, isolates schemas/queues/listeners, and reports prerequisite/readiness/cleanup failures instead of skipping tests. Playwright 1.53.2 is now an explicit dependency; no additional runner framework was introduced.
Combined validation:
- `CARGO_BUILD_JOBS=2 bun run check`: all gates passed; 60 tooling, 43 utility, 35 calculation, 310 integration and 37 Rust tests, zero failures. Build, typecheck, contracts, lint and secret audit passed.
- `bun run test:postgres`: 58 tests, 345 assertions, zero failures against disposable PostgreSQL/Redis after integration.
- `bun run test:e2e`: 4 tests, 42 assertions, zero failures on the final main-workspace build (18.99s). Author and independent reviewer also passed all four cases on the frozen implementation. These are additional gates, not included in the repository-check totals.
- Standalone strict TypeScript and explicit ESLint passed for all three new harness files. Frozen offline dependency installation passed. Missing fixture settings, unsafe PostgreSQL/Redis databases and a missing browser installation each failed explicitly before execution.
Logs, five reviewed file hashes and native artifact identities are recorded in the manifest. Exact disposable PostgreSQL/Redis containers and their recreatable fixture data, including leftovers from aborted diagnostic attempts, were removed after validation. Development services were untouched; worktree and local logs are retained. W04 was committed with owner approval; no push, PR or trading operation occurred.
Limits: Chromium only (138.0.7204.23). A standalone probe reproduced a Bun 1.2.17 server-initiated websocket close/reconnect shutdown hang; final coverage uses an actual client-initiated disconnect and does not suppress server cleanup failures or claim server-initiated shutdown coverage. An author-reported first clean-worktree build had a browser/logger type-resolution ordering failure; a retry and the combined check passed, but no fix or reproducible diagnosis is claimed. Existing build warnings remain. UI fixtures and native smoke do not certify same-bar execution, canonical accounting, ownership or funding semantics.
At the fifth-wave closeout, the readiness review found 32 remaining scheduled tasks and no ungated candidate. The owner subsequently explicitly approved ADR-002/003/004, unblocking F01/D01; that approval is separate from test completion or the earlier generic continuation request. R01 still requires ADR-006. Optimization/deferred work is not a substitute for prerequisite completion.
## Sixth-wave handoff — 2026-10-22
F01 and D01 are independently accepted and `done` / `validated_committed` in `b4af840`. Base `243e9ab`; isolated worktrees under `/tmp/stock-bot-wave6.uIuYHz/`. Financial and dataset owners implemented in parallel, with an independent read-only reviewer; the integrator merged their common types exports.
- **F01:** Pinned maintained decimal dependency; checked exact decimal ingress, fixed-8 half-away posting, bounded arithmetic, versioned Rust/TypeScript contracts, owner/decision identities and hand-derived economic fixtures. Strategy intents cannot parse as internal financial mutations. Safe integer, Unicode, strict decimal, overflow and wire-roundtrip regressions pass. The snapshot is only an economic projection. F02 still owns actual ledger/dedup transitions and operation-specific proportional basis arithmetic; generic multiply/divide was deliberately not introduced.
- **D01:** Additive v2 normalizer retains interval/event/availability time, source sequence, explicit versioned calendars, execution-series selection, universe/action coverage and limitations. Hash-verified v1 conversion retains its parent hash and makes unverifiable legacy VWAP unknown. DST/half-days, delayed availability, conflicts, overlapping intervals, parent-hash syntax and prefix stability are tested. Unsupported action/adjusted execution data rejects; unknown coverage remains exploratory. Initial intraday support requires full-duration session-contained bars.
Combined validation passed:
- `CARGO_BUILD_JOBS=2 bun run check`: 60 tooling, 43 utility, 35 calculation, 334 integration and 44 Rust tests, zero failures. Build, typecheck, contracts, lint and secret audit passed. The initial sandbox attempt failed native spawning/worker checks; the escalated full rerun passed.
- Final focused rerun after formatting two JSON fixtures: 35 TypeScript tests / 601 assertions and 44 Rust tests, zero failures. Parsed fixture values match the independently reviewed source exactly.
- Standalone strict TypeScript, explicit scoped ESLint, scoped Prettier and `git diff --check` passed. Reviewed hashes match except the deliberate shared-export merge and documented formatting-only differences. Full hashes, logs and independently rebuilt addon identities are in the manifest.
No PostgreSQL/Redis or Chromium rerun was needed for these additive, unused contracts: SQL, APIs, UI and current execution paths did not change. No throughput certification is claimed. Existing build warnings remain; isolated clean builds needed existing dependency builds/retries, without a build-system fix.
Only the verified stalled sandbox test processes were stopped after the successful rerun. No user services or data were removed; worktrees and logs remain available.
Existing v1 snapshots and financial runtimes remain unchanged. F01 is not a working canonical ledger; D01 prefix tests are not F06 replay enforcement. The subsequent owner request authorized the F01/D01 commit and F02/D02 continuation, not a push, PR or trading operation.
## Seventh-wave handoff — 2026-10-22
F02/D02 were independently accepted and subsequently committed as `b65accc` at owner request. Base `b4af840`; isolated worktrees under `/tmp/stock-bot-wave7.UIkAQD/`. Financial and data owners implemented in parallel; an independent reviewer checked both; root integrated all ten reviewed files with matching hashes.
- **F02:** Owner-keyed quantity, remaining basis, realized P&L and fees; exact rational intermediates rounded once into the maintained decimal posting type. Fee-inclusive funding, wrong-owner disposal, overflow and identity conflicts reject atomically. Command/fill aliases return original replay-labelled receipts, including after intervening operations. Explicit market marks remain separate from fill prices; owner-level marked postings reconcile to account equity. Same-session boundary repetition is an accepted no-op, not a false session-change effect. Ledger-only checkpoints retain and validate ordered receipts by replay; ordinary transitions touch only affected state.
- **D02:** Existing EOD `1m`/`5m`/`1h` Mongo collections now feed the common research storage admission path. Unix-second timestamps/listing identities validate; supported-provider capability reports distinguish configuration/connectivity from coverage. Default QuestDB priority remains, explicit provider selection is available at the storage API, and missing/error ranges never switch to daily/synthetic data. Real writer/read/normalizer composition and repeated legacy native runs are tested on synthetic provider records; HTTP/Mongo transport alone is replaced.
Combined validation:
- `CARGO_BUILD_JOBS=2 bun run check`: 60 tooling, 43 utility, 35 calculation, 342 integration and 59 Rust tests passed, zero failures. Build, typecheck, contracts, lint and secret audit passed. One Rust test is intentionally ignored by the ordinary suite because it is a manually invoked release measurement.
- Independent review: 22 financial Rust tests passed; 36 intraday/ingestion/dataset tests with 264 assertions passed. These overlap the combined totals, not additional independent cases.
- Standalone strict TypeScript including the real ingestion import graph, explicit scoped ESLint, Prettier, scoped rustfmt and `git diff --check` passed. Cargo.toml line endings were normalized alongside its pinned dependency additions; no dependency upgrades occurred. Only num-bigint was newly added to the lockfile.
- A repeatable release ledger workload runs 1k/10k prebuilt commands over one owner/asset or three owners/four assets, with three repeats and full state/effect byte equality. Transition, checkpoint-copy and restore times are recorded separately. Detailed raw measurements/build identities are in the manifest; these are not end-to-end backtest throughput or a speedup claim. Receipt memory and restore work grow with history; compaction is not implemented.
The manual release measurement also passed on the final integrated checkout (1 test, zero failures), with identical repeatability checksums to the author build. It is additional validation, not a skipped correctness test.
Limits: no F04 reservation/portfolio-risk policy, matcher, F06 replay, native session API, SQL/paper cutover, order/strategy/RNG session restoration or canonical-engine release. D02's provider selector is not a web/run-configuration control; no Mongo server-conformance, range-completeness or live-availability claim. Provider delayed-finalization caveats and the explicit bar-close simulation assumption are retained in the task evidence. PostgreSQL/Redis and Chromium suites were not rerun because their persistence/API/UI boundaries did not change. Existing build warnings remain.
Only exact identified stalled D02 sandbox test/worker processes were terminated after the successful escalated rerun; no development services/data were changed. Worktrees and logs remain available. The subsequent owner request authorized the seventh-wave commit and **F04 central cash reservations and portfolio risk enforcement**. No push, PR or trading operation occurred. Product/AI work remains subject to its unapproved ADRs.
## Eighth-wave handoff — 2026-10-22
F04 is independently accepted and `review` / `validated_uncommitted`. Base `b65accc`; isolated worktree `/tmp/stock-bot-wave8.pKzr7p/f04`. One owner implemented five financial files, two read-only reviewers accepted them, and root integrated exactly matching hashes. See [execution policy clarifications](backlog/tasks/F04.md#execution-policy-clarifications).
- **RiskAccount** privately owns the existing Ledger. Explicit and target-derived normalized orders share funded admission; strategy-owned sells cannot borrow inventory or credit anticipated proceeds. Fill-time checks account for other reservations, adverse gaps and split-fill rounding; rejection releases the remainder without changing prior fills. Commission is computed from exact quantity × price × rate, rounded once.
- Portfolio quantity/exposure uses owner-book rounding, including pending buys. Increasing risk requires fresh marks across held/pending assets. Reductions remain possible during stale data and marked-loss halts. Explicit account boundaries reset daily state only; drawdown peak/halt persists through rollover and restore. Instance-bound operator reset records its baseline, separate from strategy input.
- Recorded accepted/rejected outcomes and fill aliases replay without reapplying effects or moving the clock. Checkpoints reconstruct and verify risk/ledger state, reservations and receipts. Overflow/malformed internal commands remain atomic errors, not ordinary risk rejections. Future adapters must honor the outer replay flag before publishing nested financial effects.
Validation: `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit plus 60 tooling, 43 utility, 35 calculation, 342 integration and 77 Rust tests. Independent risk suites passed 18 cases; the broader financial suite passed 40 (overlapping totals). Two manual benchmarks are excluded from ordinary Rust runs; the new risk release benchmark was separately executed successfully in both author and integrated checkouts. Scoped rustfmt, diff checks and manifest DAG/readiness validation passed. Existing repository-wide rustfmt and planning-manifest Prettier style deviations were confirmed outside this change's formatting scope; no unrelated formatting rewrite.
The narrow release workload uses 1k/10k prebuilt mark/admit/partial-fill/release commands, three repeats, one active owner/asset or two active owners/four assets. Full checkpoint/outcome bytes and restored checkpoints match. Integrated 10k transition time was approximately 42–45ms single and 55–56ms multi, excluding build/loading/serialization; checkpoint and restore are measured separately. Only zero/one live reservation is exercised. This is not full backtest throughput or a scaling guarantee: normal risk checks scan retained book keys and live commitments with ordered-map costs; retained journal memory/restore work grows with history. Raw commands, logs, artifact/source hashes and measurements are in the manifest.
Limits: active legacy engines unchanged; no F05 matcher, target expansion/mode coordination, limit/TIF/capacity eligibility, F06 calendar/replay, F07 native sessions, paper/SQL cutover or full strategy/replay/RNG recovery. Operator capability is API separation, not untrusted-code security. PostgreSQL/Redis, browser and Python suites were not rerun because those boundaries did not change. No services/data were removed. No new-wave commit, push, PR or trading operation. Next after acceptance/commit: **F05 matching and order lifecycle on the canonical ledger/risk facade**; replay release remains gated by F06.
## Ninth-wave handoff — 2026-10-22
F05 is independently reviewed and `review` / `validated_uncommitted`. Its isolated worktree `/tmp/stock-bot-wave9.P8EKsc/f05` uses base `b65accc` plus the five exact F04 prerequisite files. The owner accepted continuation without requesting a prerequisite commit. One financial owner implemented; execution and quant reviewers accepted the final source; root integrated exactly matching hashes. See [F05 execution policies](backlog/tasks/F05.md#execution-policy-clarifications).
- **MatchingAccount** privately owns RiskAccount, with no competing ledger, fee or funding logic. Open-only and quote execution have explicit spread/slippage rounding, limit crossing, latency, session eligibility and shared liquidity. IOC/FOK/DAY/GTC transitions, partial fills, cancellation, rejection and terminal cancellation are deterministic. No synthetic end-of-run liquidation is introduced.
- Owner-scoped absolute targets account for holdings and live commitments. Omitted assets remain unchanged; repeated targets preserve partial orders. Changed targets cancel only the owner's relevant commitments before risk-checked replacement. Declared target-array order is priority, not an atomic portfolio rebalance. Target and explicit-order modes cannot be mixed for an owner.
- Structural batch validation precedes mutation. Physical execution identity prevents capacity reuse under changed delivery keys; delayed quotes retain their physical time and cannot fill orders that were not yet eligible. Exact retries replay original receipts without republishing nested effects. Checkpoints reconstruct matching, risk and ledger state. Unexpected numerical failure records the committed prefix and makes the attempt terminal; adapters must fail the run, never publish successful metrics from that prefix.
- Admission uses a coordinator revision, distinct from the nested ledger snapshot revision. F06 must honor that token, physical event timing and failure contract; it must not restamp missed opens. Full replay/strategy/RNG session restoration remains later work.
Combined validation: `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit plus 60 tooling, 43 utility, 35 calculation, 342 integration and **106 Rust tests**, zero failures. The 29 matching regressions also passed independently in both reviews (overlapping totals). Three manual benchmarks are ignored by the ordinary Rust suite; the new matching release measurement passed separately in both author and integrated builds. Scoped rustfmt, diff checks and final manifest/source verification passed.
The narrow release workload uses 1k/10k execution events and fills, each preceded by a submit (2k/20k coordinator commands plus setup), over one owner/asset or two owners/two assets, with three repeats. Integrated 10k apply time was 214–235ms single and 234–238ms multi. Apply includes fixture construction/assertions/outcome collection; checkpoint copying is separate, and restore includes cloning its checkpoint input. Serialization is outside these timers. Exact economics, checkpoint/outcome repeatability and restored checkpoint equality are asserted. Serialized checkpoint plus returned outcomes are approximately 12.6MB/128MB at 1k/10k; this is not RSS. Retained journals grow with history. These are component measurements, not end-to-end backtest throughput, a speedup claim or a reason to introduce caching/compaction prematurely. Full raw rows and artifact/source identities are in the manifest.
Limits: active legacy simulator and NAPI unchanged; no replay scheduler, paper/SQL cutover or full session restore. Checkpoints validate consistency, not authenticity or arbitrary-code security. PostgreSQL/Redis, browser and Python suites were not rerun because their boundaries did not change. Existing build warnings remain. No services/data removed; worktree/logs retained. **F04/F05 remain uncommitted. Next after acceptance: F06 deterministic availability-aware replay**, still the release gate for this matcher. No commit, push, PR or trading operation occurred.
## Tenth-wave handoff — 2026-10-22
F04/F05 were accepted and committed as `ccf333c` at owner request, superseding their uncommitted handoff status above. F06 is independently reviewed and `review` / `validated_uncommitted`. Isolated worktree `/tmp/stock-bot-wave10.8uCLfa/f06` starts at that commit. One implementation owner wrote three replay files; independent timing/execution and quant/performance reviewers accepted the frozen source; root integrated exactly matching hashes. See [F06 execution clarifications](backlog/tasks/F06.md#execution-handoff-clarifications).
- **Replay** owns MatchingAccount and one sorted immutable event vector. Available observations use an index prefix rather than repeated history copies. Declared cadence produces one synchronized barrier per timestamp; exact due owners submit against the matching admission revision. Missing/stale feature inputs remain explicit. Prepared input/config ordering is canonicalized; file permutations preserve trace/checkpoint bytes.
- Only the pinned execution series provides open opportunities, marks and liquidity derived from the physically latest completed available volume. Warmup cannot trade; terminal observations mark only. Late prior closes cannot overwrite a physically newer open even when their timestamps tie. True retained session opens are never restamped for mid-session starts. Risk-session boundaries are a separate explicit clock.
- Exact canonical input/config content, not an unverified label, binds checkpoints. Restore reconstructs event prefixes and fixed decision submissions, then verifies the full state. Both submission-time and automatic-event financial failures preserve terminal diagnostic prefixes without producing a successful run. Strategy-state/RNG recomputation remains F07/S01.
Combined validation: `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit plus 60 tooling, 43 utility, 35 calculation, 342 integration and **131 Rust tests**, zero failures. The **25 replay regressions** passed independently; the timing reviewer also ran the full frozen test binary. Four manual benchmarks are ignored by ordinary Rust runs; the new release replay measurement passed in both author and integrated checkouts. Scoped rustfmt, diff, task DAG/readiness and final source/artifact checks passed.
Release measurement: one/two assets, 1k/10k/100k execution bars plus one cadence-only row, three repeats each, one buy/fill per run. Full checkpoint bytes repeat exactly; independent expected cash/equity and restored checkpoints match. Integrated 100k load was 76–85ms and traversal 0.91–1.11s. Load includes canonicalization, validation, sorting and exact binding serialization; traversal includes financial marks/journals and the fixture decision. Input generation/cloning and output serialization are excluded. Checkpoint copying and full restore are timed separately. At 100k the serialized checkpoint is approximately 429MB, not RSS. Receipt history is retained; no compaction or cross-trial cache was introduced. This is not order-heavy, TS/NAPI, batch or storage throughput, nor a baseline speedup claim. Raw rows and hashes are in the manifest.
**Material model restriction:** existing sequential equal-time marks can latch intermediate portfolio loss/drawdown despite unchanged final synchronized equity. The implementation exposes this limitation and pins a permutation regression. R05's multi-asset default activation requires explicit owner acceptance or an approved coordinated atomic-mark correction. F06 acceptance does not waive that gate.
Other limits: trusted internal prepared bars only; F07 must verify/adapt frozen D01 inputs and preserve provenance/model limitations. Quote replay and abutting sessions explicitly reject. Event budget bounds count, not wall time. Active legacy simulator, native API, SQL/paper and web paths are unchanged; no PostgreSQL/Redis, browser or Python rerun was needed. Existing build warnings remain. No services/data removed; worktree/logs retained. **F06 remains uncommitted. Next after acceptance: F07 native pull-session/dataset adapter**; F08 result projection may follow with coordinated contract ownership. No push, PR, trading operation or further task implementation occurred.
## Eleventh-wave handoff — 2026-10-23
F06 was accepted and committed as `417a7bd` at owner request, superseding its uncommitted handoff status above. F07 was independently reviewed, validated and subsequently committed as `e3635f2` at owner request. Isolated worktree `/tmp/stock-bot-wave11.l8cJnN/f07` starts at the F06 commit. One native/worker owner implemented; a second owner supplied three disjoint benchmark files reviewed by root. Independent boundary/lifecycle and data/quant reviews accepted the boundary. Root integrated 22 matching source/test files. See [F07 clarifications](backlog/tasks/F07.md#execution-handoff-clarifications).
- **FinancialReplaySession:** thin NAPI export over one ReplayHost/F06 core; strict identity/version envelopes, event-count-bounded progress/decision/complete/failed steps, synchronized admission revisions, complete-batch submission, terminal success gate and disposal. One read-only observation-range accessor avoids checkpoint copies. The exact host is tested against direct Rust Replay with identical barriers, outcomes and receipts; TS uses the same frozen fixture and independent arithmetic.
- **TypeScript/worker:** existing D01 validator verifies actual data and derived eligibility/limitations. Numeric ingress expands scientific notation and rejects unsupported precision without rounding. Calendars, execution feed and availability are retained. Callbacks receive only shared immutable published deltas and financial views. Exceptions submit no partial batch; worker results must match captured identity/policy. Existing process cancellation, crash, wait-for-close and lease protections remain.
- **Scope:** fixed trace and fixture callbacks only, not S01 production strategy state/RNG or a DSL. The legacy request, durable runner default and paper/live behavior are unchanged. Exact architecture tests permit only the worker and its helper to reach native replay; shared schemas still cannot import native/data/services.
Final validation: `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit plus **63 tooling, 43 utility, 35 calculation, 353 integration and 133 Rust tests**, zero failures. Four earlier manual Rust measurements remain intentionally ignored by the ordinary suite. Independent frozen-artifact review ran 69 focused TS tests and 29 replay-related Rust cases (overlapping totals). Disposable PostgreSQL/Redis suites passed **58 tests / 345 assertions** before and after integration. Release-addon replay/binding tests passed **17 tests / 120 assertions**. Extra strict TypeScript for affected scripts/tests, scoped ESLint, rustfmt and diff checks passed. Explicit lint of the normally ignored architecture test confirms the same 13 pre-existing curly-style errors at HEAD and in the worktree; no new ones. The clean isolated build initially needed the existing logger prerequisite built manually; no build-system rewrite.
Release measurement: 1k/10k total bars, one asset/owner or ten assets/two owners, two fresh processes with two fresh native sessions each; alternate one-unit buy/sell targets. Full normalized results match across repeats, reverse callback order and debug/release profiles. Independent integer-cent cash/equity/basis/fee/fill checks pass. At 10k, release whole-trial times were **2.65–2.93s single / 3.51–3.61s multi**; finalization alone was **0.89–1.03s / 1.34–1.40s**. Final receipt payloads were approximately **66.7MB / 103.6MB**, not RSS. Cold imports and detached dataset verification, mapping, session load, real advance/submit/decision timings, bytes and process RSS are recorded separately in the manifest/logs. This is order-heavy component conformance throughput, not empty-crossing overhead, a production research benchmark, an isolated-host SLA or a legacy-engine speedup. No cache, batch pool, compaction or DSL was introduced.
Limits remain explicit: trusted host interface, not an untrusted-code sandbox; native prepared input does not independently authenticate D01. Quote/abutting-session replay remains unsupported; event count is not a wall-time guarantee. Sequential equal-time marks can still latch intermediate risk halts; R05's owner policy gate remains unresolved. Full receipts are retained and serialized; F08 can use these measurements when designing canonical results without prematurely adding a general storage framework.
Only the two named disposable fixture containers and their recreatable synthetic data were removed; development services were untouched. Worktree/logs retained. Browser/Python suites were not rerun because those boundaries did not change. **F07 is committed. Next recommended: F08 canonical metrics/result projections**, now code/ADR-ready but not yet authorized. S01 requires ADR-005 approval. No push, PR, default cutover or trading operation occurred.
## Twelfth-wave handoff — 2026-10-23
Two focused performance stories replace a broad optimization request: [F09](backlog/tasks/F09.md) emits compact authoritative terminal values/owned fills with optional complete diagnostics; [P07](backlog/tasks/P07.md) profiles no-trade, sparse and high-turnover workloads using the existing harness. F08 consumes F09 and later adds explicit session sampling/exposure/statistical policies. No session-close values are inferred from risk baselines, and fills are not relabelled completed trades.
Base `19e9dad`; isolated worktrees under `/tmp/stock-bot-wave12.F9Rlh4/`. One native/result contract owner, one disjoint benchmark owner, root planning/integration and independent review. Baseline profiling was measured on F07; compact comparisons used the accepted F09 contract. Internal journals/recovery, legacy/default paths and all mark-policy release gates remain. No framework, DSL, cache, worker-pool or web-pagination expansion.
Both stories are independently reviewed and `review` / `validated_uncommitted`. Root integrated 14 source/test files with exact reviewed hashes. F09's accepted contract was overlaid into P07's isolated worktree before compact comparison work; neither owner independently changed the other's contract.
- **F09:** native `project()` returns the existing authoritative ledger valuation and actual owned fills copied from committed commands/effects. It skips replay aliases and retains separate gross cash movement and fee postings, signed owner contributions and residual cost basis. Typed serialization borrows journal facts; no checkpoint copying, financial replay or TypeScript accounting is introduced. Complete-state/identity/format/cancellation guards cover the compact path. Full `finalize()` output, defaults, internal journals and recovery are preserved.
- **P07:** the existing harness now selects no-trade, sparse and turnover profiles with identical callback cadence, plus trace/projection/both output. It records native-finalization, decoding, validation and disposal separately. Comparisons require the same dataset, policy, strategy, artifact, terminal view and actual fill facts. Full per-format hashes remain independent; no TypeScript valuation is fabricated to compare formats. A 200,000-fill regression prevents a benchmark-only JavaScript argument-limit failure.
Validation: full `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit, 63 tooling, 43 utility, 35 calculation, 359 integration and **136 Rust tests**, zero failures; four existing manual benchmarks remain intentionally ignored. After the final benchmark files were integrated, all **72 tooling tests / 10,184 assertions** passed. Extra strict test/script TypeScript, scoped ESLint, rustfmt and diff checks passed. Disposable PostgreSQL/Redis suites passed **58 tests / 345 assertions** before and after integration. Independent debug and integrated release native/worker checks each passed **23 tests / 198 assertions**. These focused tests overlap larger suites. No browser/Python rerun was needed for unchanged boundaries.
Paired release results below use identical frozen source and addon `d98308d0…`, two fresh processes with two fresh native sessions each, including reversed callback order. Numbers are median **replay/decision/finalization/disposal time**, excluding native construction and benchmark-only oracle/hash work. Bars are total across assets. Preparation/imports, whole-trial time, all phase timings, RSS, hashes and raw report paths are recorded in the manifest. This is synthetic component conformance throughput on a shared host, not durable-job latency or an isolated-host SLA.
| Total bars | Profile | Assets / owners | Full trace | Compact | Reduction |
| --- | --- | --- | ---: | ---: | ---: |
| 10,000 | No trade | 1 / 1 | 1.142s | 0.744s | 34.9% |
| 10,000 | No trade | 10 / 2 | 0.599s | 0.296s | 50.7% |
| 10,000 | Sparse | 1 / 1 | 1.184s | 0.835s | 29.5% |
| 10,000 | Sparse | 10 / 2 | 0.720s | 0.419s | 41.8% |
| 10,000 | Turnover | 1 / 1 | 2.105s | 1.467s | 30.3% |
| 10,000 | Turnover | 10 / 2 | 2.598s | 1.804s | 30.6% |
| 100,000 | Sparse | 1 / 1 | 11.918s | 8.097s | 32.1% |
| 100,000 | Sparse | 10 / 2 | 7.312s | 4.245s | 41.9% |
| 100,000 | Turnover | 1 / 1 | 21.027s | 14.821s | 29.5% |
| 100,000 | Turnover | 10 / 2 | 26.501s | 18.743s | 29.3% |
Every selected comparison passed independent economic oracles, complete result repeatability and common financial equality. All six 10k diagnostic hashes also match the historical F07 baseline. That intermediate extended harness's source bodies were not retained, only their hashes, so historical timings are contextual; speedup claims use the final paired source, which is archived with all 21 changed files as measured. Final planning edits follow the measurements; application source remains identical. No 100k no-trade run is claimed.
At 10k turnover, output falls from **66.7MB to 9.8MB** single and **103.6MB to 19.4MB** multi. At 100k turnover it falls from 672MB/1.044GB to 98.6MB/195.8MB. Full diagnostics remain available; this is an export reduction, not deletion of retained history. Compact 10k advance/submit accounts for 70–88% of run time. Those mixed timers should be profiled before selecting another optimization. Fixture TS decisions take only 0.9–3.5%; these results do not justify a DSL. Compact schema validation and disposal remain measured costs; removing checks or recovery history is not the next step.
Only the two exact disposable fixture containers and their synthetic data were removed; development services were untouched. Worktrees, logs and measured-source archive remain available. No commits, pushes, PRs, default cutover or trading operation occurred. **Next after acceptance: F08 historical equity/session/exposure and versioned statistics**, with explicit sampling conventions. S01 and product/AI work retain their pending ADR gates; the equal-time multi-asset risk-mark restriction remains unresolved.
## Thirteenth-wave execution — 2026-10-23
F09/P07 were accepted and committed as `e3bd722`, superseding their uncommitted handoff above. [F08](backlog/tasks/F08.md#execution-contract--2026-10-23) is the next code/ADR-ready story. Isolated worktrees start at that commit under `/tmp/stock-bot-wave13.KfvceG/`.
Root pinned the reporting contract after Rust and quantitative review. One owner implements the native reporting accumulator/wire; a disjoint owner implements reviewed statistics and the additive analytics adapter. The accepted native schema is passed to the consumer before integration. An independent reviewer checks sampling, financial invariants and undefined-statistic handling.
Account-session samples follow all equal-time observations without changing the earlier risk reset or financial event indexes. Partial session returns remain visible but are excluded from full-period annualized ratios. Exposure counts the union of actual occupied intervals over elapsed calendar time, including open positions through termination. Statistical policy explicitly records annualization/risk-free conventions and unavailable benchmark/round-trip metrics; no hidden 2%/252 defaults are introduced for canonical reports.
F08 adds a canonical analytics DTO beside the existing result contract. It does not fabricate the legacy DTO's per-position mark/average/P&L fields or infer round trips from fills. R05 retains persisted/public-result migration and default cutover. Existing readers/UI remain compatibility gates. No new financial policy, cache/DSL, journal deletion or unrelated per-step performance change is included.
**Validated handoff:** F08 is `review` / `validated_uncommitted`. Root integrated all 22 owner files with exact independently reviewed hashes and added a real native → worker → analytics composition test. The planning commit is `1e16445`; no F08 implementation commit has been made.
- Rust records account-session equity after equal-time observations and unions actual occupied intervals, including open positions at termination. Restore reconstructs the same facts without changing financial event IDs, checkpoints or existing trace/projection output.
- Native `report()` and the existing worker transport expose the versioned facts. The additive TypeScript adapter reuses reviewed calculations with explicit annualization/risk-free policy, partial-period exclusion and nullable unsupported metrics. Shared calculations retain old defaults for old callers; exactly constant returns and zero terminal-equity CAGR now have pinned edge-case tests.
- Repository build, typecheck, contract, audit and lint gates passed, with 72 tooling, 43 utility, 44 calculation and 144 Rust tests. Four existing manual Rust benchmarks remain ignored. The initial integration run exposed missing explicit hold decisions in the new composition fixture; after that test-only correction, **375 integration tests / 3,345 assertions passed**. Strict test TypeScript, scoped ESLint/Prettier/rustfmt and diff checks passed. Disposable PostgreSQL/Redis recovery suites passed **58 tests / 345 assertions** before and after integration. The release addon passed **39 focused native/worker/analytics tests / 703 assertions**. Counts overlap; browser/Python boundaries did not change and those suites were not rerun.
Release measurements used six synthetic workloads with **10,000 total bars**, one asset/owner or ten assets/two owners, and no-trade/sparse/turnover strategies. The first candidate appeared 33–44% slower than the early baseline, including unchanged TypeScript callback/JSON phases. Shared host load varied materially. A contemporaneous rerun of the exact unchanged F09 release reproduced that slowdown; 128 relevant control source files match `e3bd722`. All complete result and financial hashes agree. Retain both sets of evidence; this is not a speedup claim.
| Workload | Early F09 median | Contemporaneous F09 control | F08 median | F08 vs control |
| --- | ---: | ---: | ---: | ---: |
| No trade, 1 asset / 1 owner | 722 ms | 1,050 ms | 1,037 ms | −1.2% |
| No trade, 10 assets / 2 owners | 301 ms | 422 ms | 413 ms | −2.2% |
| Sparse, 1 asset / 1 owner | 788 ms | 1,137 ms | 1,125 ms | −1.0% |
| Sparse, 10 assets / 2 owners | 425 ms | 589 ms | 582 ms | −1.3% |
| Turnover, 1 asset / 1 owner | 1,425 ms | 1,994 ms | 2,009 ms | +0.7% |
| Turnover, 10 assets / 2 owners | 1,820 ms | 2, 432 ms | 2,426 ms | −0.3% |
Each median has four fresh-session samples across two processes. A separate counterbalanced comparison of projection/report output passed all **48 sessions**, exact repeated report/analytics hashes and an independent integer-cent oracle. Removing reporting fields and normalizing the format discriminator to `projection` yields the identical complete projection. Report finalization medians were 0.24–6.77 ms higher; analytics took 0.50–1.28 ms. These fixtures have only one partial account period: they measure export/occupancy and minimal analytics, not long histories of session statistics, durable research throughput or empty NAPI cost. There is no demonstrated material replay regression on these workloads, and no stable-host SLA is claimed.
Raw samples, source/artifact hashes, commands and review evidence are in `manifest.json` → `thirteenth_wave_validation`, with retained files under `/tmp/stock-bot-wave13.KfvceG/`. Only the two exact disposable test containers were stopped; development services were untouched. Source worktrees and logs remain.
Limits: sampled drawdown is not intraday maximum; marks are last available without per-session freshness certification; benchmark-dependent and round-trip statistics remain null with reasons. Sequential equal-time marks can still latch intermediate risk halts. R05 retains its owner policy gate and public/persisted result cutover. **Next after acceptance: S01 stateful TypeScript strategy decisions**, requiring ADR-005 approval; R01/R11 require ADR-006. No pending decision, default cutover, push, PR or trading operation was implicitly approved.
## Fourteenth-wave execution — 2026-10-23
F08 was accepted and committed as `3838295`, superseding its uncommitted handoff above. S01 is the next satisfied task under ADR-004/005. Isolated runtime and verification worktrees start at that commit under `/tmp/stock-bot-wave14.JYfazy/`; root owns planning/integration and a separate reviewer checks the result.
[S01's execution contract](backlog/tasks/S01.md#execution-contract--2026-10-23) pins one shared pull loop, typed synchronous state-in/state-out strategy programs, per-owner observation/decision/RNG cursors, atomic staging around native submission and truthful admission feedback. Different strategy cadences must not lose another owner's observations. Rust remains the only financial authority.
Recovery deliberately follows the current research job boundary: restart the whole attempt from frozen inputs and original initial states/seeds. TS snapshots are diagnostic; no incomplete mid-run resume or new native checkpoint transport. S02 owns the first real strategy and trusted worker composition; S03 preserves durable paper integration, R05 the default/public-result cutover. The active legacy registry, SQL/paper state and web runner remain unchanged.
**Validated handoff:** S01 is `review` / `validated_uncommitted`. Eight author/verification files were integrated with exact independently reviewed hashes. Root added the permanent author type-test gate. The source bundle and raw logs remain under `/tmp/stock-bot-wave14.JYfazy/`; the manifest owns the precise validation record.
Callbacks now receive frozen prefix observations, isolated typed state/positions and scoped per-owner randomness. Every due callback uses the same native portfolio view; all next states/intents are staged before admission and all feedback is validated before one committed-state swap. Rejections advance state and carry actual Rust order status. Late callback failures, ambiguous native submissions and malformed feedback dispose the attempt and retain the last confirmed diagnostic state. The original conformance driver uses the same extracted pull loop with unchanged IDs and financial hashes.
Review caught two boundary defects before integration: unhandled Promise rejections from invalid async callbacks, and empty feedback envelopes accepted by `z.unknown()` fields. Narrow fixes observe actual Promise rejection without awaiting/invoking arbitrary thenables and require present object-valued feedback tags. Regression tests cover both, including foreign-realm Promises and failure after real native admission. No Rust semantics, worker protocol, SQL or legacy registry implementation changed.
Full `CARGO_BUILD_JOBS=2 bun run check` passed build/typecheck/contracts/audit/lint plus **78 tooling, 43 utility, 44 calculation, 390 integration and 144 Rust tests**, with four existing manual Rust measurements ignored. Extra strict test TypeScript, scoped ESLint/Prettier and diff checks passed. The initial temporary strict config lacked its root-relative Bun type lookup; fixing that external config resolved it without source changes. Disposable PostgreSQL/Redis suites passed **58 tests / 345 assertions**; final release tests passed **43 tests / 568 assertions**. Independent native verification contributed 15 scenarios / 249 assertions, overlapping the integrated totals. Browser and Python boundaries did not change and those suites were not rerun.
The unchanged conformance CLI passed all six 10k workloads with identical complete result/economic hashes and the same release native artifact as F08. Historical wall-time changes track shared-host load; they are not an extraction speedup claim. A separate counterbalanced benchmark compared stateful programs with **replay of their exact captured decisions**, including IDs. This avoids treating different identity/payload sizes as callback cost.
| 10,000 total bars | Recorded decisions | Stateful programs | Added wall time |
| --- | ---: | ---: | ---: |
| No trade, 1 asset / 1 owner | 861 ms | 949 ms | 88 ms / 10.3% |
| No trade, 10 assets / 2 owners | 357 ms | 372 ms | 14 ms / 4.0% |
| Sparse, 1 asset / 1 owner | 908 ms | 1,050 ms | 143 ms / 15.7% |
| Sparse, 10 assets / 2 owners | 511 ms | 527 ms | 16 ms / 3.1% |
| Turnover, 1 asset / 1 owner | 1,569 ms | 1,881 ms | 313 ms / 19.9% |
| Turnover, 10 assets / 2 owners | 1,925 ms | 2,212 ms | 287 ms / 14.9% |
All **48 timed sessions** match complete financial hashes; repeated/reversed program order preserves diagnostic state/RNG hashes. Each fresh child first captures a reference trace, so timed sessions are in a warmed process. Medians have four samples per mode. Wall time includes construction, state validation/staging, callbacks, admission feedback, finalization and disposal; post-run oracle/hash work is separate. Each callback updates four scalar fields and draws once. This is neither pure callback overhead nor complex-strategy, database/queue or cold-start throughput. The measured 3.1–19.9% overhead is retained as a profiling baseline, without removing correctness checks or introducing a DSL/cache.
Only the two exact disposable fixture containers were stopped; development services were untouched. Worktrees, archives and measurements remain. **Next after acceptance: S02**, port one SMA strategy and wire its explicit trusted version into the existing worker. Its handoff distinguishes indicator state reconstruction from unsupported native mid-run resume. R05 still owns durable/public-result activation; paper migration and other pending decisions remain separately gated. No S01 commit, push, PR or trading operation occurred.
## Fifteenth-wave execution — 2026-10-23
S01 is accepted and committed as `2bcadbd`, superseding its uncommitted handoff above. S02 now has satisfied prerequisites. Isolated strategy and worker worktrees start at that commit under `/tmp/stock-bot-wave15.zi3GmP/`; root owns integration and a separate reviewer checks both changes.
[S02's pinned contract](backlog/tasks/S02.md#execution-contract--2026-10-23) defines an explicit long-only SMA version with reviewed crossover arithmetic, owner-budget whole-share sizing, prefix-safe history and native freshness checks. The existing worker accepts only reviewed built-in selections and binds returned strategy provenance to the captured request. Legacy readers/factories, financial Rust semantics and active web/paper paths stay intact. No generic registry, source-code transport, feature framework or incomplete checkpoint resume is introduced.
S03 is code/ADR-ready but outside this wave. R05 retains durable canonical/default activation and its multi-asset policy gate; R01/R11 require ADR-006. No pending policy was implicitly approved.
**Validated handoff:** S02 is `review` / `validated_uncommitted`. Ten integrated source/test files match the independently reviewed hashes. `sma-crossover-long-only/v1` uses the existing aliases and reviewed crossover helper, exact whole-share budget sizing, bounded JSON state and explicit availability/freshness rules. The legacy long/short strategy stays intact. The existing child worker locally runs trusted programs over the canonical Rust session; the parent detaches input and checks exact effective selections plus native identity/policy/format. No callback source, module path, TS financial engine or default/paper activation was added.
The independent next-open fixture buys ten shares at5 and sells at2, with0.7 total fees and9969.3 terminal equity from10000. Further tests cover warmup entry sizing, delayed older bars, equality, stale inputs, unaffordable fees/gaps, same-order partial fills, owner attribution, JSON reconstruction and full retry. Worker tests reject altered provenance/economics, malformed/duplicate output and crashes, and preserve hard cancellation even after a result arrives before child close.
`CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/audit/lint plus **78 tooling, 43 utility, 44 calculation, 432 integration and 144 Rust tests**; four existing manual Rust measurements remain ignored. Dedicated test/fixture strict TypeScript and scoped lint/format/diff checks passed. Disposable PostgreSQL/Redis: **58 tests /345 assertions**. Final release tests: **48 /175**. Built `dist/native-worker.js` matches direct execution in trace, projection and report formats. Browser/Python boundaries did not change and were not rerun.
The worker owner's second elevated test run waited for approval and was aborted; root took over final validation after an explicit handoff. Root's restricted IPC run also stalled and was stopped, then passed unrestricted. Fixture correction uses a mutable detached dataset for the mutation test; schema `.min(1)` retains runtime nonempty validation without requiring a tuple input type. No economic failure was hidden by those environment/type corrections. Only the two exact disposable test containers were stopped.
The unchanged release addon is `6fe9dae…`. A paired benchmark compares actual SMA programs with replay of their **exact captured decisions**, including IDs. All **48 timed sessions** preserve complete financial hashes; repeated/reversed program order preserves diagnostics.
| 10,000 total bars | Recorded decisions | SMA callbacks | Added wall time |
| --- | ---: | ---: | ---: |
| SMA5/15, 1 asset /1 owner | 1,091 ms | 1,467 ms | 376 ms /34.5% |
| SMA5/15, 10 assets /2 owners | 410 ms | 478 ms | 69 ms /16.8% |
| SMA5/15, 10 assets /10 owners | 624 ms | 916 ms | 292 ms /46.8% |
| SMA15/252, 1 asset /1 owner | 1,018 ms | 2,351 ms | 1,333 ms /130.9% |
| SMA15/252, 10 assets /2 owners | 409 ms | 636 ms | 227 ms /55.5% |
| SMA15/252, 10 assets /10 owners | 594 ms | 1,681 ms | 1,087 ms /183.1% |
Each median has four samples across two processes, after an untimed reference capture. Imports/preparation are separate. Ten-assets/two-owners trades only two assets; the other eight still replay. Single-asset runs have9999 decisions and10000 advance calls; ten-assets/two-owners has1998 decisions/1000 calls, and ten-owners has9990 decisions/1000 calls. Warmup proportions and fills also differ. Cross-shape ratios do not isolate scaling. This is warmed direct-runtime throughput, not durable jobs, worker IPC, pure callbacks or NAPI cost; no speedup is claimed for S02.
The long-window decision/state phase accounts for roughly51–62% of wall time in the owner-dense cases, but cloning, freezing, schema validation, trailing calculation and allocation costs are not yet separated. [P08](backlog/tasks/P08.md) is the recommended next task **after S02 acceptance**, to profile and reduce that measured cost while preserving all strict-state and financial invariants. It is planned, not started. Immutable code artifacts remain R01/R05 work; no label-only reproduction guarantee is claimed. All raw evidence, exact commands, source archive and hashes are in `manifest.json` → `fifteenth_wave_validation` and `/tmp/stock-bot-wave15.zi3GmP/`. No new implementation commit, push, PR or trading operation occurred.
## Sixteenth-wave execution — 2026-10-23
S02 was accepted and committed as `ca5abdd`. The owner then explicitly stopped performance work and requested the remaining backlog. P08 is deferred; its initial inspection made no application changes and ran no profiling or benchmarks.
S03 is the next highest-priority code/ADR-ready task. [Its pinned execution contract](backlog/tasks/S03.md#execution-contract--2026-10-23) covers a stateless native transaction adapter, versioned SQL custody and actual strategy-state/RNG/batch-intent recovery. Native and durable owners use separate worktrees based on `ca5abdd` under `/tmp/stock-bot-wave16.kgaZm4/`; independent review checks the contract before integration.
Preserve existing row locks, journal context, idempotency and rollback behavior. Canonical next-event timing and immutable policy differ explicitly from legacy execution; refuse implicit account conversion. Retain failed native prefixes atomically as terminal, and keep notification delivery separate from financial commit. No performance work, default switch, paper feed activation or other pending ADR approval is included. S04 owns feed readiness; R01/R11 still require ADR-006.
**Validated handoff:** S03 is `review` / `validated_uncommitted`. Twenty-two source/test files are integrated with recorded hashes and independent G1/G2 signoff. `stageFinancialTransaction` restores private state and applies the existing Rust matcher. Its ordered financial views are reconstructed through the same risk reducer and checked against the authoritative result. Replayed commands return their original outcome with the current checkpoint and no new effect journal.
The canonical host uses the existing PostgreSQL account row lock. It commits all due owners' state/RNG/checkpoints and one complete batch intent together, then dispatches the batch in a separate transaction. Native snapshots, per-effect views, journals, input status and admission feedback commit atomically. Mixed-cadence owners retain their unconsumed observations. The shared decision helper preserves S01 research behavior. One additive migration stores complete canonical batches; legacy accounts explicitly refuse canonical envelopes and retain their existing execution path.
Coverage includes competing hosts, SQL rollback, lost acknowledgements, frozen callback inputs, all four time-in-force policies, risk reservations, stale quotes, exact quote-cursor decisions, and terminal failures during both admission and execution. A real SMA program matches uninterrupted state and journals after repeated replacement. Four separate-process kill cases cover decision staging, checkpoint commit, admission commit and fill/fee commit; recovery matches uninterrupted execution exactly.
`CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/audit/lint plus **82 tooling, 43 utility, 44 calculation, 432 integration and 150 Rust tests**. Four existing manual Rust measurements remain ignored. The complete disposable PostgreSQL/Redis suite passed **81 tests / 545 assertions**. Extra strict TypeScript exposed only test fixture typing issues; these were corrected without changing application behavior, then strict test compilation, scoped format/lint and **38 targeted tests / 281 assertions** passed. Browser/Python boundaries were unchanged and their suites were not rerun. No profiling, optimization or benchmark run occurred.
The native addon was built and verified against this checkout's debug library for the full gates, then rebuilt in release mode. Another **38 tests / 366 assertions** passed against the final release addon; no timing measurements were performed. Source archives, exact commands/hashes and logs are recorded in `manifest.json` → `sixteenth_wave_validation` and `/tmp/stock-bot-wave16.kgaZm4/`. Only the two exact disposable test containers were stopped; development services, worktrees and logs were retained.
Limits remain explicit: trusted SQL custody, new canonical account IDs, execution-series observations only, immutable declared program metadata rather than retained code artifacts, and invalid queued inputs that fail closed until diagnosed. Rust validates opaque financial receipts before each financial transition; startup alone is not a full receipt audit. **Next after acceptance/commit: S04**, feed scheduling, auxiliary observation manifests and operator readiness. S05 is independently code/ADR-ready; R01/R11 still require ADR-006. S03 does not activate paper/live execution or switch existing web/research defaults. No S03 commit, push or PR was created.
## Deferred and rejected
Conditional: shared feature cache D04; cross-trial resident datasets P03; large-detail pagination/storage P05; tiny DSL P06; expanded cross-service monitoring O02. Each has a measured/real-need trigger and is not a prerequisite for scheduled work.
Deferred economics: short/margin/borrow, multicurrency, full corporate actions, intrabar stops/OCO, detailed market impact and live brokers. Reject unsupported datasets/orders explicitly. The model is not generalized by pretending unsupported behavior exists.
Later product/research: embedded IDE, advanced optimizers, generalized ML training, Monte Carlo significance tooling. Basic immutable versions, chronological validation and evidence links are not deferred.
Rejected: competing TS/web simulators, wholesale Rust rewrite, hand-written decimal engine, new service/message bus/workflow framework, generic signal DSL, compatibility switches that re-enable defects, deleting reviewed calculations because they are currently unused. Keep existing local environment-file policy; no WCAG or cosmetic-dashboard scope here.
## Execution governance
Only [manifest.json](backlog/manifest.json) owns status/assignment/dependencies. [Task files](backlog/README.md) own scope/acceptance. Read the reusable [implementation](agents/implementation.md), [review](agents/review.md), [integration](agents/integration.md), [planning](agents/planning.md) briefs and [quality gates](QUALITY-GATES.md).
Approval of planning artifacts is not permission to commit, push or create PRs. Historical planning-only statements refer to the original audit; later execution records and the canonical manifest identify actual implementation, authorization and validation evidence.
## Seventeenth-wave execution — 2026-10-23
S03 was accepted and committed as `c01e96e`, superseding its uncommitted status above. S04 is in progress under its [pinned execution contract](backlog/tasks/S04.md#execution-contract--2026-10-23). Isolated feed and custody owners work under `/tmp/stock-bot-wave17.JfETUx/`; root owns shared contracts, API/composition and integration, with independent review. Performance tasks remain deferred by owner instruction.
The existing ingestion service has no working producer for its legacy paper Socket.IO client. This wave adds a validated trusted HTTP frame boundary and operator gate with deterministic feed-to-fill fixture coverage; it does not certify a vendor feed or activate paper/live trading. The canonical composition remains explicit and opt-in. Preserve S03 financial custody and financial semantics; retain paused work and require explicit historical recovery acknowledgement.
**Validated handoff:** S04 is `review` / `validated_uncommitted`. Twenty source/test files integrated; feed, custody and API-test slices match independently reviewed frozen hashes. Root supplied shared contracts, composition and HTTP/SQL SMA-to-fill/restart and research-isolation tests. New accounts start halted/disconnected. Exact frame receipts, retained physical quote ordering and generation fences prevent replay/reconnect from silently creating liquidity or resuming execution. Human halt stops the next locked step without discarding pending work. Historical recovery requires explicit acknowledgement and keeps original quote prices/times. Existing loopback auth bypass remains an explicit development exception, not authenticated-feed certification.
Validation: `bun run check` passed build, source/contracts, 82 tooling, 43 utility, 44 calculation, 454 integration and 150 Rust tests (four manual tests ignored), plus lint. Full isolated PostgreSQL/Redis suite: **104 tests / 719 assertions**. Strict new-test TypeScript, scoped lint/format and diff checks passed. Final release addon matches this checkout's native library; **55 tests / 481 assertions** passed against it. No performance measurements were run. Exact commands, hashes and raw logs are in `manifest.json` → `seventeenth_wave_validation` and `/tmp/stock-bot-wave17.JfETUx/`.
Sandbox-only connection/child-process restrictions were rerun with escalation; only the exact stalled test process was stopped. Both exact disposable fixture containers were stopped after validation. Development services, worktrees and logs were retained. No S04 commit, push, PR, default cutover or trading activation occurred. The current trusted HTTP feed boundary still needs a real provider producer and operational calendars. **Next after acceptance/commit: S05**, a small composable multi-signal/regime strategy example; performance remains deferred. R01/R11 still need ADR-006.
## Eighteenth-wave execution — 2026-10-23
S04 is accepted and committed as `75abae2`, superseding its uncommitted handoff above. S05 proceeds under its [pinned execution contract](backlog/tasks/S05.md#execution-contract--2026-10-23). Root owns shared selection/dispatch, integration and durable restart coverage; separate strategy and native-verification owners use worktrees under `/tmp/stock-bot-wave18.V1G17v/`, with independent review.
One new long-only mean-reversion program composes explicit trend/momentum/reversion filters and fixed per-observation volatility gating. Both regime/no-regime modes share warmup. Native target reconciliation handles partial entries and persistent exits; no TS accounting or Rust financial changes. R08 remains the gate for performance conclusions. Performance engineering, services, default cutover and trading activation remain out of scope.
**Validated handoff:** S05 is `review` / `validated_uncommitted`. Twenty source/test/config files integrate one small canonical dispatcher, a distinct versioned mean-reversion program, shared exact desired-share sizing, native/worker verification and one durable restart regression. SMA calculations/checkpoint semantics and Rust financial code are unchanged. Independent G1/G2 review accepted the integrated source and public malformed-selection tests; strict final test types passed.
The [comparison example](../../apps/stock/orchestrator/examples/canonical-regime-research.ts) creates four explicit requests: volatility filter on/off under baseline and caller-supplied alternative costs. Inputs, versions, seeds and policies accompany native reports. It adds no experiment scheduler or optimizer. Periods count observed bars; volatility is not elapsed-time normalized. Initial owner budgets size desired shares and do not guarantee realized spend through gaps/fees. R08 remains necessary before conclusions about trading performance.
Validation: `bun run check` passed build/source/contracts, 82 tooling, 43 utility, 44 calculation, 479 integration and 150 Rust tests (four manual ignored), plus lint. The final added public-schema matrix passed separately. Full disposable PostgreSQL/Redis suite: **105 tests / 728 assertions**. Final strict new-test types, scoped lint/format and diff checks passed. **98 tests / 580 assertions** passed against the final release addon, including the added matrix, worker reports, SMA regressions and durable recovery. Exact commands, hashes and logs are recorded in `manifest.json` → `eighteenth_wave_validation` and `/tmp/stock-bot-wave18.V1G17v/`.
Only the two exact disposable test containers and identified sandbox-stalled verifier test processes were stopped; development resources, worktrees and logs remain. No S05 commit, push, PR, optimization, benchmark measurement, default cutover or trading activation occurred. Next after acceptance/commit: **R01 immutable strategy versions and R11 dataset workbench integration**, subject to the pending [ADR-006 research-product decision](architecture/decisions/006-research-product.md). Performance work remains deferred.
## Nineteenth-wave execution — 2026-10-23
S05 is accepted and committed as `6a67ae8`, superseding its uncommitted handoff above. Owner continuation approves the explicitly linked ADR-006 research-product direction. R11 is the next focused vertical slice; R01 is ready but outside this wave. Backend and frontend worktrees under `/tmp/stock-bot-wave19.do4GnG/` reserve disjoint files. Root owns contracts, composition, source forwarding and browser integration; review is independent.
The workbench will select exact retained v1 datasets or explicit source requests through the existing durable runner. Metadata listing does not certify bar integrity or calendar coverage. V2 datasets remain visibly unsupported until R05; existing economics warnings remain. No new service, default engine cutover, trading activation, profiling or benchmark work.
**Validated handoff:** R11 is `review` / `validated_uncommitted`. Twenty-four source/test files add a metadata-only retained dataset catalog, exact hash selection shared by creation and Settings, explicit source forwarding through the existing runner, and run-specific preparation/pinned status. Intraday UTC milliseconds survive save/reopen. Missing/unsupported metadata stays visible; source mode remains independent of catalog availability. Save and submit validate exact compatibility; concurrent partial updates serialize under the existing backtest row lock. Accepted idempotent submissions still return their original receipt before checking current templates/catalog state.
Independent G1/G2 review accepted the final changes. Repository checks passed 498 integration and 150 Rust tests (four manual ignored), plus build/source/contracts, 82 tooling, 43 utility, 44 calculation and lint gates. The final row-lock fix passed the full disposable PostgreSQL/Redis suite: **111 tests / 792 assertions**. Final release-addon focused coverage: **94 tests / 596 assertions**. Final browser coverage: **6 workflows / 66 assertions**, including real native frozen-hash reuse/reopen/trades, exact intraday save/reopen, mismatch rejection before dispatch and source unpinned-to-pinned display. Strict changed-test types and scoped lint/format/diff checks passed. Exact commands, source hashes and logs are in `manifest.json` → `nineteenth_wave_validation` and `/tmp/stock-bot-wave19.do4GnG/`.
The catalog does not certify full content integrity or calendar coverage. Current web economics remain legacy/qualified; v2 entries remain unsupported until R05. No financial Rust change, schema migration, new service, performance measurement, default cutover or trading activation. The final release addon matches this checkout's release library. Both exact disposable fixtures were stopped; development resources, logs and worktrees remain. No R11 commit, push or PR. **Next after acceptance/commit: R01 immutable strategy versions**, now ready under approved ADR-006.
## Twentieth-wave execution — 2026-10-23
R11 is accepted and committed as `b106c1c`. R01 adds immutable strategy versions, retained bundles/locks, exact parameter validation and audited review. Root owns shared contracts/composition/seeding and integration; backend and offline packaging owners use disjoint worktrees under `/tmp/stock-bot-wave20.XIW6lx/`, with independent review.
R01 deliberately exposes no version-based execution. R02 catalog/forms can proceed before R05, but actual version submission requires R05 retained-artifact verification/execution. Candidate uploads remain non-runnable until A02. Existing legacy execution stays qualified and rejects unsupported catalog version references. No performance work, new service, engine cutover or trading activation.
**Validated handoff:** R01 is `review` / `validated_uncommitted`. Thirty source/config/migration/test files retain immutable bundled-JS versions and dependency locks, source/build identity, scalar parameter schemas with exact canonical validators, stable built-in families, lineage and operator review events. Metadata projection omits content; artifact retrieval verifies exact hashes. Publish/clone idempotency and archive/concurrent-edit behavior use existing SQL transactions. Credential proof excludes development bypass only for new catalog mutations. No candidate code compiles or executes in the API. Offline packaging/seeding commands are documented in [R01](backlog/tasks/R01.md#validated-handoff--2026-10-23).
Independent G1/G2/security review accepted the final implementation. Validation: build/source/contracts, 93 tooling, 43 utility, 44 calculation, 509 integration and 150 Rust tests (four manual ignored), plus lint. Full disposable PostgreSQL/Redis suite: **122 tests / 903 assertions**. Release-addon focused strategy/API suite: **65 tests / 377 assertions**, plus the final contract edge case. Browser regressions: **6 workflows / 66 assertions**. Strict new-test/script types and scoped lint/format/diff checks passed. Initial allowlist/lint/declaration errors were corrected; the browser contract boundary now builds from current type source after a combined-suite generated-file read failure. Exact commands and evidence are recorded in `manifest.json` → `twentieth_wave_validation` and `/tmp/stock-bot-wave20.XIW6lx/`.
All catalog versions remain non-runnable until retained-artifact execution is integrated; approval does not enable execution. Original TypeScript source/full-run provenance are not claimed by the bundled-JS catalog. Current legacy workflows remain qualified and reject unsupported catalog version IDs. No financial Rust changes, default cutover, real catalog seeding, trading activation, profiling or benchmarks. The release addon matches the checkout library; both exact test fixtures were stopped. No R01 commit, push or PR. **Next after acceptance/commit: R10 evidence retention; R02 catalog screens are also eligible with disjoint ownership.**
## Twenty-first-wave handoff — 2026-10-23
R01 accepted and committed as `4a2e5ad`. R10 is independently reviewed and `validated_uncommitted`; isolated API/database and frontend worktrees are retained under `/tmp/stock-bot-wave21.u7PX8e/`. All 20 implementation/test files match reviewed hashes.
- **Retained evidence:** Migration 17 replaces definition/run/result deletion cascades with restrictions and protects runs, results and frozen datasets from destructive writes. Immutable run identity/receipt/snapshot/bound dataset fields are guarded; normal progress, lease recovery, cancellation, completion and initial binding remain writable. Legacy pending NULL snapshots still backfill once. Existing R01 artifact/checksum custody is reused.
- **Template archive/restore:** The API serializes archive, edit, delete and new-run admission on the parent row. Templates with any run return 409 on deletion, with count and archive guidance; runless/missing deletion retains 204 compatibility. Idempotent accepted receipt replay precedes archive checks. A database admission trigger also covers direct repository creation. Accepted work continues after archive; no separate run-archive lifecycle or purge framework.
- **Workbench:** Confirmation-backed archive/restore, archived list filter/badge, viewable read-only settings and disabled fresh submissions. Active cancellation, selected results/trades and ambiguous submission keys survive archive; delayed navigation/filter responses cannot overwrite current state. Archived saved URLs reopen normally.
- **Validation:** Full repository gates passed: 93 tooling, 43 utility, 44 calculation, 520 integration and 150 Rust tests (4 manual ignored), plus build/types/contracts/lint/secrets. Real PostgreSQL/Redis: 131 tests / 987 assertions. Chromium: 7 workflows / 79 assertions, including archive during admitted execution/cancellation and restored submission. Strict new/modern changed tests and scoped formatting/lint passed. Full commands/logs/hashes are in the canonical manifest.
The initial sandbox run could not support native worker IPC or fixture network access; full checks were rerun successfully outside it. Optional broad strict legacy harness checks retain pre-existing errors, recorded in the manifest. Release addon is restored and matches the prior wave hash; Rust code and financial semantics were unchanged. Disposable fixture containers were removed; development services were untouched. No performance work, new R10 commit, push, PR or trading/default activation.
Legacy economic/provenance limitations remain explicit; retaining evidence does not certify its economics or create missing version history. Next: R02 strategy catalog UI and version-aware setup. R05 still owns retained-artifact execution and canonical durable cutover.
## Twenty-second-wave handoff — 2026-10-23
R10 is accepted and committed as `8cca0ee`, superseding its uncommitted handoff above. R02 is `review` / `validated_uncommitted`. Thirty-nine implementation/shared-contract/migration/test files were integrated from isolated backend/frontend owners and root browser/fixture integration, with independent review. Worktrees/logs remain under `/tmp/stock-bot-wave22.fPRkAC/`.
- **Catalog and versions:** Browse/create/edit/archive strategy families; select immutable versions; clone with frozen retry identity; compare retained bundled JavaScript/schema/identities as escaped text. Parameter forms preserve omission, explicit empty strings, false, zero, typed enums and decimal strings, and require exact server validation. Version-linked execution/deployment history remains explicitly unavailable.
- **Saved backtest setups:** Migration 18 retains exact version IDs and normalized parameters separately from execution settings. Create, save, reopen and edit catalog setups in the existing workbench. Archive/restore resets visible parameter state and validation together. Legacy pacing stays out of strict catalog settings. Existing supported legacy strategies retain their qualified independent workflow.
- **Admission boundary:** Every catalog version remains non-runnable, including approved built-ins. API, direct repository and SQL gates reject before run/outbox creation; accepted legacy receipts still replay first. No legacy alias fallback, catalog/legacy mode conversion, browser code execution or fabricated provenance.
- **Validation:** Full checks passed: 93 tooling, 43 utility, 44 calculation, **541 integration** and **150 Rust** tests (4 manual ignored), plus build/source/contracts/lint/secrets. Full disposable PostgreSQL/Redis: **137 tests / 1052 assertions**. Final unfiltered Chromium suite: **8 workflows / 117 assertions**, including catalog selection/save/reopen/edit/archive/clone and existing native/frozen-dataset workflows. Strict new/modern changed tests and scoped lint/format/diff checks pass. Exact commands, source hashes and limitations are in `manifest.json` → `twenty_second_wave_validation`.
The browser gate exposed intermittent Chromium control-pipe loss across serial launches, not a financial assertion failure. Isolated workflows passed. The fixture now shares one suite-owned Chromium process while giving each workflow a fresh context/server/schema/queue; the complete suite passed without retries. Production workers are unchanged. The release addon matches the prior wave and checkout library; no Rust financial semantics changed. Both exact disposable containers were stopped; development services were untouched.
No new R02 commit, push, PR, performance work or trading/default activation. **Next after acceptance/commit: R05**, connecting verified retained executable identity and canonical reports to durable runs. Start with a trusted-built-in single-asset vertical slice; do not certify a retained hash while executing an unrelated current built-in. Candidate execution remains gated by A02 and multi-asset default by the explicit mark-policy decision. R03 research metadata is also ready for disjoint work, but does not unlock catalog execution.
## Twenty-third-wave handoff — 2026-10-23
R02 is accepted and committed as `d929db7`. The initial R05 vertical slice is independently reviewed and `partial_validated_uncommitted`; R05 remains **in_progress**. Fifty-four implementation/contract/migration/test files connect approved retained built-ins, eligible single-series v2 datasets and explicit financial/reporting settings to the existing durable Rust runner. Isolated worker, durable and frontend worktrees plus evidence remain under `/tmp/stock-bot-wave23.D3gFzn/`.
- **Executable provenance:** Admission freezes exact retained package/lock bytes, version/review, parameters, dataset hash, seed, financial/time/reporting policies and worker/native/runtime build identities. The child verifies and imports the retained bundle; it never substitutes a current built-in by name. Approval/archive changes serialize with admission; accepted receipts and snapshots remain usable afterward.
- **Durability:** One queue/runner/repository lifecycle handles leases, heartbeats, fencing, cancellation/reaping and atomic results. Corrupt data, wrong builds or a non-native runner fail without provider/legacy fallback. Migration 19 preserves retention and adds versioned canonical results without rewriting old rows.
- **Workbench:** Review built-ins, save exact canonical settings against a retained dataset, submit, inspect canonical Rust balances/owners/fills/metrics/provenance, and reopen results. Exact UTC/DST warmup boundaries survive save/admission. Zeros and unavailable reasons are preserved; fills do not become invented round trips. Cross-parent results and late navigation replies are rejected; canonical positive drawdowns use correct severity colours.
- **Validation:** All relevant gates passed across the recorded commands: build/source/contracts/secrets; 93 tooling, 43 utility, 44 calculation, **576 final integration** and **150 Rust** tests (4 manual ignored); full PostgreSQL/Redis **150 tests / 1154 assertions**, plus **13 final release-admission/durability tests / 106 assertions**; Chromium **9 workflows / 164 assertions**. The canonical browser fixture proves two expected fills, `9969.30000000` equity, exact saved provenance and zero provider reads. Final strict new-test/script checks, application lint, modern test lint, formatting and diff checks passed.
The initial aggregate check exposed stale pure-contract allowlists and lint issues; those were corrected and affected gates rerun. Optional lint over all touched old fixtures still reports eight existing curly-rule errors in two files changed only to apply migration 19; no suppressions or unrelated cleanup. Full commands, review dispositions and exact source hashes are in `manifest.json` → `twenty_third_wave_validation`. The release addon equals the prior wave/checkout release hash; Rust financial code is unchanged. Both exact disposable fixture containers were stopped; no development/production state was seeded or migrated.
Deployment requires the existing native research runner (`useRustEngine: true`) and matching immutable build files. Capability is input/artifact validation, not worker health. An incompatible deployment fails an accepted run; historical build restoration belongs to R12. [R05](backlog/tasks/R05.md#first-vertical-slice--2026-10-23) documents the explicit offline v2 import and remaining source-preparation contract. No candidate/multi-asset/default activation, benchmark or performance work, new-wave commit, push or PR.
**Next after acceptance/commit: R03 research projects, hypotheses and evidence-linked findings APIs.** It is independently ready and adds useful research workflow without pretending full R05 is finished. R05's source-to-v2 preparation and broader cutover remain tracked; R06/S06 dependencies are not released by this partial milestone.
## Twenty-fourth-wave handoff — 2026-10-23
The initial R05 slice is accepted and committed as `618fb9e`; full R05 remains **in_progress**. R03 is independently reviewed and `validated_uncommitted`. Eighteen implementation/shared-contract/migration/test files add the research metadata APIs. Persistence and HTTP agents worked in isolated worktrees under `/tmp/stock-bot-wave24.3Qsd1y/`; root owned contracts, evidence resolution, composition and integration.
- **Research organization:** Projects can organize existing strategies, hypotheses and notes/findings. Project edits and real membership changes advance revision identity. Hypothesis/artifact edits append immutable narratives with explicit authorship; stale edits return 409. Archive/restore preserves prior narratives and cited results, with actor/time recorded.
- **Evidence:** Findings cite known scalar paths on exact completed retained runs, optionally binding the retained strategy version. The existing result reader supplies canonical or qualified legacy values; no copied metric truth or simulator was introduced. Null reasons, genuine zeros, units and result limitations are preserved. SQL references protect retained results and prevent later additions to an old revision's evidence set.
- **Authorship:** Verified operator/service submitter is separate from declared human/AI/unknown content origin. A service cannot claim human authorship. All prose remains unvalidated; a citation does not certify a conclusion. No AI credential, code execution or review framework was added.
- **Correctness fixes during review:** Evidence resolution now uses the active transaction connection, avoiding deadlock when the pool has one connection. Corrupt retained storage produces a sanitized server error with its diagnostic cause, rather than blaming a valid client request. Project membership changes also preserve actor attribution and optimistic revision identity.
- **Validation:** `bun run check` passed all gates, including **590 integration** and **150 Rust** tests (4 manual ignored), plus build/source/contracts/secrets/lint, 93 tooling, 43 utility and 44 calculation tests. Full disposable PostgreSQL/Redis: **159 tests / 1279 assertions**. Existing Chromium workflows: **9 / 164 assertions**, including actual retained canonical execution/reopen. Strict changed-test types, scoped formatting/test lint and diff checks passed. No research UI is claimed by these browser regressions; that is R04.
Exact source hashes, commands and review dispositions are recorded in `manifest.json` → `twenty_fourth_wave_validation`. The release addon matches the previous wave and checkout release library; Rust financial source is unchanged. After the interruption, all 18 implementation hashes were reverified and both disposable containers were confirmed removed. Development/production services and data were untouched; worktrees and logs remain for review.
R03's [implemented API contract](backlog/tasks/R03.md#implemented-contract--2026-10-23) documents revision inputs, archive/error behavior and evidence limitations. Initial metadata POSTs use ordinary creation semantics, so clients must handle ambiguous responses without blind retries. No R03 commit, push, PR, new simulator, performance work or trading/default activation.
**Next after acceptance/commit: R04 — research workspace and save-findings UI**, consuming these same APIs. R05's remaining source preparation and wider cutover are still tracked; R06/S06 gates remain intact.
## Twenty-fifth-wave handoff — 2026-10-24
R03 is accepted and committed as `ee45257`. R04 is independently reviewed and `validated_uncommitted`. Seventeen implementation/test files add the web research workspace while retaining existing APIs, persistence and financial semantics. Two UI agents worked in isolated worktrees under `/tmp/stock-bot-wave25.X7zzoe/`; root owned shared browser contracts, navigation, evidence display and browser integration.
- **Workspace:** Create/edit/archive projects, link catalog strategies, create hypotheses and notes, and view or revise immutable narratives. History URLs retain exact revision IDs. Archived projects remain readable. Declared AI/human authorship is separate from authenticated submitter, and prose stays unvalidated.
- **Findings:** Completed matching results offer a project/hypothesis/metric selector. Only reference identities are submitted; R03 resolves actual measurements. Display includes raw values, units, unavailable reasons, financial engine, dataset and exact run/version links. Existing findings keep their references when prose changes; legacy evidence remains qualified.
- **Failure behavior:** Duplicate clicks, late navigation responses, lost save responses, malformed success envelopes and stale revision conflicts have focused coverage. Ambiguous creation freezes the draft until explicit review/new request. Review caught and fixed draft loss during failed project refresh and same-entry discard behavior.
- **Validation:** Build/types/contracts/secrets, **628 integration**, **150 Rust** (4 manual ignored), 93 tooling, 43 utility and 44 calculation tests passed. Two new curly-rule lint issues were fixed and final source/test lint passed. Final focused UI/client tests: **38 / 207 assertions**. Strict changed-test types and formatting/diff checks passed. Real Chromium/PostgreSQL/Redis: **9 workflows / 184 assertions**. The expanded canonical browser fixture covers project → linked strategy → retained run → exact finding → revision/reload/archive → unchanged original result, preserving the expected two fills, `9969.30000000` equity and `0.70000000` fees.
The initial sandbox check stalled on native-worker IPC; permitted checks passed. Browser development caught a fixture endpoint allowlist omission and a test that read history before the revision response committed; both were corrected, and the final full suite passed without retries. The full standalone SQL suite was not rerun because backend/schema sources are unchanged; real browser fixtures exercise the existing research API and database. The release addon matches the previous wave and checkout release library. Exact hashes, commands, review and cleanup are recorded in `manifest.json` → `twenty_fifth_wave_validation`.
No backend financial authority, second evidence store or creation-receipt framework was added. Initial metadata creation still cannot guarantee exactly-once semantics across an ambiguous response; the UI makes this explicit. No performance work, new-wave commit, push, PR, candidate execution, default/multi-asset activation or trading operation occurred.
**Recommended next product slice: R12 original-run reproduction**, limited to already-retained inputs and a supported installed build. The current manifest still blocks R12 on full R05. Before implementation, record its narrower component prerequisite and pin lineage/admission/current-approval rules; migration 19 presently binds ordinary admission to current template settings, so snapshot copying alone is insufficient. Keep R05 incomplete, R06/S06 gated, and historical build provisioning/source preparation outside that slice.
## Twenty-sixth-wave handoff — 2026-10-24
R04 is accepted and committed as `e3bd708`. R12 is independently reviewed and `validated_uncommitted`. Twenty-six implementation/test files add original reproduction through the existing durable runner, retained artifacts and financial engine. Backend/frontend agents used disjoint worktrees under `/tmp/stock-bot-wave26.38tu9A/`; root owned shared contracts, comparison, migrations/fixtures and browser integration.
- **Original versus current:** the run detail previews the original dataset, immutable strategy version, parameters, financial policies and build. Reproduce original creates a new linked run; ordinary submission continues to use current template settings. Missing inputs or unsupported builds remain explicit, with old results readable.
- **Guarded admission:** authenticated preview/POST/comparison routes preserve the original economic request. Only new run/session/account identities and current approval of the original version change. Migration 21 enforces immutable lineage, retained identity and source-copy guards. Accepted idempotency receipts precede current eligibility checks; no provider or current-code fallback.
- **Comparison:** versioned server-side hashes cover the complete validated request, Rust financial envelope and canonical analytics. Normalize only admission identity; retain actual market sessions, owner/order/fill IDs, monetary strings, null reasons and ordered arrays. No second accounting implementation.
- **UI reliability:** ambiguous submissions retain the same intent/key; late responses cannot navigate away from a newer selection. Lineage and match/mismatch diagnostics survive reload. The existing controls test now restores its own ResizeObserver harness correctly.
- **Validation:** full repository check passed, including **662 integration and 150 Rust tests** (4 manual Rust ignored), build/source/contracts/secrets/lint and 93 tooling/43 utility/44 calculation tests. Full PostgreSQL/Redis: **169 tests / 1376 assertions**. Chromium: **9 workflows / 215 assertions**, including actual original-versus-current execution and receipt replay. Focused SQL: **10 / 97**; independent UI: **106 / 555**; independent HTTP/hash: **10 / 96**. Strict changed-test types, scoped lint/format and diff checks passed.
- **Recorded identity:** source archive/hash and all 26 authored file hashes are in `manifest.json` → `twenty_sixth_wave_validation`. Release addon SHA256 `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103` matches the previous wave; no Rust semantics changed. Both exact disposable test containers were stopped; development services were untouched.
Scope is completed retained canonical single-asset trusted built-ins on the same installed build. Hash agreement proves matching retained economic outputs, not statistical validity or profitability. Historical executable provisioning, provider-to-v2 preparation, candidate isolation and multi-asset/default cutover are not included. R05 remains partial; R06/S06 remain blocked. No performance optimization, profiling, benchmark, new-wave commit, push, PR or trading operation occurred.
**Recommended next wave:** an R06 retained-input experiment component, then a focused R07 sweep UI against pinned APIs. One immutable strategy version, eligible single-asset dataset, installed build and fixed policies; deterministic bounded parameter grids expand into the existing durable runs/outbox. Independent review confirms provider preparation is not required for those retained inputs. Before execution, record component prerequisites without marking full R05/R06 complete or silently releasing R06/R07/S06. Experiment admission needs its own SQL guard against the immutable manifest; do not mutate templates per trial or misuse reproduction lineage. Failed retry must preserve diagnostics and fencing; if omitted initially, leave R06 partial. No parallel worker scheduler or performance work. Root owns contracts/browser integration; one backend owner and one frontend owner can work with an independent reviewer.
## Twenty-seventh-wave handoff — 2026-10-24
R12 is accepted and committed as `30accfc`. R06/R07 retained-input components are independently reviewed and `partial_validated_uncommitted`; both full tasks remain in progress. Thirty-five implementation/test files deliver the first bounded experiment workflow through the existing APIs, durable runs and authoritative Rust engine. Backend/frontend worktrees are under `/tmp/stock-bot-wave27.iR6JOC/`; root owned shared contracts, composition, existing fixtures and browser acceptance.
- **Usable research flow:** start from a saved canonical backtest or Experiments, enter a named parameter grid, preview the exact retained dataset/version/window/build/policies, submit and inspect every candidate. Detail shows scalar metrics, units/null reasons, failures, missing/incomparable outcomes and exact saved-run links. Explicit refresh, cancellation and reopening are supported.
- **One execution path:** at most 100 trials are atomically admitted with the experiment receipt and existing dispatch outbox. Only validated strategy parameters and new run/account/session identities vary. All combinations must pass retained schema and built-in cross-field validation; normalized duplicates and reserved keys reject. No template rewrite loop, second scheduler, accounting logic or runner rewrite.
- **Reproducible admission:** the submit body commits to its preview hash, including current review/build and retained manifest. Drift rejects before persistence. Accepted receipts replay before current eligibility checks. SQL22 protects immutable experiment/trial identity, exact request reconstruction, current approval and retained inputs; ordinary/reproduction admission behavior is preserved.
- **Truthful outcomes:** cancellation latches and stops pending trials while existing workers acknowledge active cancellation. Terminal results remain unchanged. Detail counts come from the same loaded trial rows; comparison validates complete v1 statistical conventions and compact financial identity/policy. Summaries read selected JSON fields without financial/trade/OHLC/return arrays and do not recalculate economics.
- **Validation:** full repository check passed **696 integration and 150 Rust tests** (4 manual Rust ignored), plus 93 tooling / 43 utility / 44 calculation tests and build/source/contracts/secrets/lint. Full disposable PostgreSQL/Redis: **179 tests / 1508 assertions**. Full Chromium: **10 workflows / 258 assertions**, including actual varied-parameter native trials, rendered returns, receipt replay, post-admission template changes, standalone reproduction of an experiment trial, cancellation and reopening. The initial new browser selector included nested option text; correcting the selector resolved the test without production changes. Scoped strict types, lint, formatting and diff checks passed.
- **Independent review:** all 14 agent-owned hashes verified. Combined experiment contract/API/UI tests independently passed 34/230; isolated PostgreSQL/native 10/132 evidence reviewed. Review corrected pre-parser reserved-key loss, normalized duplicates, count/read consistency, full provenance comparisons, cancellation fencing, owned-link draft loss and retained timeframe rendering.
- **Recorded identity:** the manifest holds all 35 source/test hashes and archive identity. Release addon SHA256 `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103` matches the previous wave. Both exact disposable containers were stopped; development services were untouched.
Full R06 remains incomplete until failed-trial retry preserves prior diagnostics and passes stale-attempt fencing tests. R07 broader comparisons/table measurement remain outstanding; all performance work stays paused. R05 provider preparation and broader cutover remain partial; R08/A01/S06 are not silently released. No candidate/multi-asset/default/paper/live/AI execution, new-wave commit, push or PR occurred. Editor retry state lives in the current page; saved experiments and accepted receipts are durable. Hash/provenance agreement does not establish strategy merit.
**Next after acceptance/commit: complete R06 failed-trial retry** using the same immutable logical run and existing attempts/outbox. Append prior diagnostics before clearing active errors; reject retries with stored results or completed/cancelled state, retain old-attempt fencing and add a focused UI action only after the backend contract passes. Performance remains paused.
## Twenty-eighth-wave handoff — 2026-10-24
The previous experiment workbench is committed as `6f64ef6`. R06 failed-trial retries and focused R07 controls are implemented, independently reviewed and validated; these new changes are uncommitted. R06 is now in review with its retained-input acceptance satisfied. R05 and full R07 remain partial.
- **Durable retry:** A manual retry preserves the logical run, immutable request, dataset, strategy parameters and original approval snapshot. Current original-version approval/build eligibility is checked separately. One atomic SQL transaction captures the exact failure, advances the manual retry counter, clears active execution state and makes the existing dispatch outbox due. Lifetime attempt counters never decrease; recovery budgets are not reset. Existing workers supply the next fresh attempt UUID.
- **Recovery evidence:** Append-only receipts preserve PostgreSQL timestamp precision. Repeated acceptance returns the same receipt, including after completion or later eligibility changes. Cancellation, retained results, stale failure counters, direct SQL tampering and late old-worker callbacks cannot create an unauthorized retry or overwrite results. No financial engine, runner or dispatcher source changed.
- **Workbench:** Per-trial review/retry/history controls retain the exact unresolved request through refresh and uncertain responses. Saved history survives reopening. This records failures captured by manual retries, not invented historical automatic-attempt logs.
Validation passed: `bun run check` (93 tooling, 43 utility, 44 calculation, 738 integration and 150 Rust tests; four existing manual Rust tests ignored), full PostgreSQL/Redis (190 tests / 1609 assertions), and Chromium (11 workflows / 285 assertions). Strict test types, scoped lint, changed-file formatting and whitespace checks passed. Independent review accepted all 12 agent-owned hashes and the root browser fixture/test delta. All 27 source/test files are archived and hashed in `manifest.json` → `twenty_eighth_wave_validation`.
The release addon remains `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103`. Both disposable fixture containers were stopped; development services were untouched. Worktrees and logs remain under `/tmp/stock-bot-wave28.AqRnN8/`.
Next after acceptance/commit: **R08 bounded chronological selection and reset-segment validation**. Freeze train/validation/test windows and selection rules before execution, retain all tried candidates and distinguish reset segments from continuous portfolio performance. No performance work, standalone/bulk retries, candidate execution, multi-asset/default/paper/live activation, AI execution, new-wave commit, push or PR occurred.
## Twenty-ninth-wave handoff — 2026-10-24
The owner accepted R06 retries, committed as `b373410`; 35/45 scheduled tasks are fully committed. R08's first preflight component is implemented, independently reviewed and validated, but uncommitted. Full R08 and the existing R05/R07 exclusions remain incomplete.
- **Prepared chronological inputs:** The existing experiment editor accepts explicit UTC train/validation/test windows and previews their exact retained slices, candidate-wide warmup requirements, original policies and reset-account assumptions. Invalid or stale input never becomes a prepared result. Ordinary sweep submission remains separately labelled.
- **Point-in-time correctness:** Slices preserve original bars, availability, sequences, VWAP and legacy conversion provenance. They reject cut bars, out-of-range/overlapping evaluation windows and insufficient usable warmup. Each phase reuses the existing calendar clock logic while keeping capital, risk, costs, strategy and seed unchanged. Completed observations are distinguished from execution opens.
- **Honest scope:** Preview creates no datasets, experiments, runs, reports or selected winner. Its fixed future protocol selects from complete training evidence only; validation/test cannot retune. Staged execution and immutable evidence are still unavailable. No financial simulation, SQL admission or dispatcher behavior changed.
All gates passed: `bun run check` (93 tooling, 43 utility, 44 calculation, 786 integration and 150 Rust tests; four existing manual Rust tests ignored); full PostgreSQL/Redis (194 tests /1655 assertions); Chromium (12 workflows /306 assertions); strict test types, scoped lint, formatting and whitespace checks. Two native regressions prove fresh independent account/state and unchanged earlier economics after modifying the test suffix. The browser workflow proves preview/rejection/invalidation/reload with no database effects. Exact 19-file source hashes, review evidence and logs are in `manifest.json` → `twenty_ninth_wave_validation`.
The release addon remains `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103`. Both disposable fixture containers were stopped; worktrees/logs remain under `/tmp/stock-bot-wave29.kK85O1/`. Existing warnings remain; development data/services were untouched.
Next after acceptance/commit: **R08 immutable recipe and staged admission**. Freeze windows and selection rules before execution, retain all training candidates, then atomically freeze the winner before validation/test admission. Extend existing one-dataset admission/retry assumptions explicitly; do not add another scheduler. R09 stays blocked, and performance/default/trading/AI activation remains excluded. No new-wave commit, push or PR occurred.
## Thirtieth wave handoff — 2026-10-24
The accepted preflight is committed as `67ab30c`. The next R08 component is implemented, independently reviewed and validated, with changes left uncommitted. Full R08 remains in progress. Thirty-eight implementation/test files add a complete single train/validation/test workflow through the existing durable runner and authoritative Rust engine.
SQL24 extends `research_experiments`: the training root owns the immutable prepared manifest, write-once selection and final report; validation/test are ordinary singleton children. Existing SQL22 run admission and SQL23 retries remain unchanged. The ordinary manifest guard is mechanically extracted without semantic changes. SQL verifies exact source slices, availability, metadata, calendar clocks, candidate completeness and copied result facts; deferred checks prevent partial training or holdout admission. Root cancellation propagates through old/new APIs and direct SQL without upward trigger locks.
The web explicitly submits training, freezes the complete verified winner while atomically admitting both heldouts, and saves an immutable report. GET never advances work. Selection maximizes finite comparable training total return with original-index tie breaking; all training candidates are required. Full existing native-result/analytics verification precedes irreversible evidence. Accepted receipts survive subsequent eligibility changes; new holdouts require current original-version approval/build, while historical finalization works after archival/revocation. Failed phase trials reuse existing retry/history controls. Distinct phase names, reset assumptions, sample counts, unavailable reasons and precise report/run identities remain visible.
All gates passed: `bun run check` (93 tooling, 43 utility, 44 calculation, 825 integration and 150 Rust tests; four existing manual Rust tests ignored); PostgreSQL/Redis (205 tests /1773 assertions); Chromium (13 workflows /357 assertions); strict new-test types, scoped lint, formatting and whitespace checks. New native/database tests cover atomic rollback, receipt conflicts/races, direct SQL tampering, migration preservation, failed phase retries, cancellation races and unchanged training selection after modifying future test prices. The real browser completes the full lifecycle, finalizes after archival and reopens the exact report. Source hashes, overlays, independent review and logs are recorded in `manifest.json` → `thirtieth_wave_validation`.
The release addon remains `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103`. Both disposable fixture containers were stopped; logs/worktrees and the exact 38-file archive remain under `/tmp/stock-bot-wave30.K6IDyj/`. Initial manual browser setup hit the fixture network guard because a local VITE override was present; the corrected same-origin build passed both focused and final suites. Existing bundle-size/Rust warnings remain; development data/services were untouched.
Next after acceptance/commit: finish R08 with repeated nonoverlapping walk-forward windows and bounded cost sensitivity, reusing these durable recipe/experiment paths. Keep independent reset-account reporting explicit; do not imply a continuous portfolio or untouched external holdout. R09 remains blocked; R05/R07 and AI/default/trading gates are unchanged. No performance work, candidate execution, new scheduler/simulator, new-wave commit, push or PR occurred.
## Thirty-first wave handoff — 2026-10-24
R08's bounded walk-forward component is independently accepted and committed as `3ed7b98` on base `abd1c5b`. At this wave's completion, full R08 remained `in_progress` for bounded cost sensitivity; R09 remained blocked. Forty-one source/test/config files and four existing planning files comprise this wave.
- **Frozen series:** A focused `research_walk_forwards` header owns 2–10 ordered recipes and immutable train-root memberships. Every source/grid/build/policy is frozen before training. Total promised work includes all candidates and both future holdouts, capped at 100 runs. Training cutoffs increase and heldout intervals cannot overlap.
- **Reuse and integrity:** Existing chronological validations, per-window actions, durable runs/outbox and retries execute every member. SQL25 is additive; SQL22–24 are unchanged. All training roots/slices/runs/outbox admit in one transaction, including a pool-size-one proof. Exact membership, write-once reports and receipts resist direct SQL mutation. Series cancellation reaches all remaining member work; member cancellation stays local and completed evidence is preserved.
- **Research evidence:** Series finalization re-verifies all canonical native results behind every member report, then copies ordered validation/test evidence. Archival or current build eligibility cannot invalidate historical sealing/replay. Separate reset accounts are labelled honestly: no continuous equity, compounding or new statistical formula. Changing only later test prices leaves earlier training scores/winners unchanged.
- **Web workflow:** Explicit windows, preview, durable submission, saved series, member links and report save/reopen use the existing APIs. Shared editor ownership prevents ordinary/single-window/series submissions from competing. Ambiguous requests retain exact intent/key and late responses cannot replace another route. The real browser executes both windows, freezes inputs before template changes, seals after archival and reopens exact native evidence.
Validation: 93 tooling, 43 utility, 44 calculation, **882 integration** and **150 Rust** tests passed; **215 PostgreSQL/Redis tests /1881 assertions**, **14 Chromium workflows /412 assertions**, strict authored-test types and lint passed. The full check initially failed only missing-brace lint rules; final source lint/types passed after reviewed formatting-only fixes. Broad lint of old touched test fixtures still reports eight preexisting curly violations outside the added migration-list lines. Existing four ignored Rust cases and build warnings remain. No performance measurements ran.
Independent backend/frontend reviews accepted the exact eight/eleven-file overlays; root composition and browser coverage were independently reviewed. Source archive, 41 file hashes, native identities, commands and local logs: `manifest.json` → `thirty_first_wave_validation`, under `/tmp/stock-bot-wave31.QqUT6Z/`. Release addon was restored for final database/browser tests. Both disposable fixture containers were removed after validation; development services were untouched. No new-wave commit, push, PR or trading operation occurred.
Next: bounded fee/slippage sensitivity with an explicit immutable financial-policy admission contract, reusing the authoritative Rust engine. Do not encode costs as strategy parameters or mutate saved templates. Keep cost scenarios separate from frozen walk-forward selection unless an explicit later study requires their combination. Performance, candidate/AI execution and multi-asset/default/paper/live activation remain gated.
## Thirty-second wave handoff — 2026-10-24
Full supported R08 is independently accepted and `validated_uncommitted` on base `3ed7b98`; task status is `review` pending owner acceptance/commit. Thirty-seven source/test/config files and four existing planning files comprise this wave. The earlier chronological preflight, durable single-window and reset-window workflows remain intact.
- **Cost diagnostics:** One existing experiment stores a versioned fixed-template cost preview. Automatic original-cost baseline plus 1–99 explicit distinct normalized fee/slippage pairs; parameters and every other financial/data/build policy remain frozen. Each scenario reruns Rust, including fee reservation, funding, fills and subsequent strategy decisions. No cost-as-parameter trick, adjusted-P&L subtraction, ranking or universal monotonic-profit claim.
- **Reuse and SQL integrity:** Existing submission receipts, runs/outbox, cancellation, retries/results and original-run reproduction handle cost studies. SQL26 introduces no tables or columns. It leaves SQL22–25 and the callable v1 manifest validator unchanged, adds explicit version dispatch and one request reconstruction helper for admission/retry, and preserves all remaining guard bodies. Deferred checks require every scenario and dispatch row to commit together. Chronological/walk-forward sources remain v1-only.
- **Web:** Cost mode uses the ordinary experiment submission owner and existing list/detail/retry/history screens. Normalized rates, original baseline, fixed inputs and scenario order are visible; failed/missing/incomparable/null outcomes stay explicit. The detail page now synchronously owns refresh before a competing mutation. Exact ambiguous body/key and late-route protections are preserved. No new report lifecycle, scheduler or financial engine.
- **Evidence:** Hand-derived native fixtures assert exact execution prices, fees and terminal equity, including fee-inclusive funding rejection. The baseline reproduces the ordinary empty-grid economic hash. Original scenario inputs survive template edits, retry and reproduction. SQL tampering, atomic rollback, cross-kind receipts, observed lock contention and first/idempotent migration preservation pass. The actual browser verifies native policy/identity and metrics after template changes, then receipt replay, saved reopening and run drilldown.
All repository gates passed: **926 integration /150 Rust** tests, plus 93 tooling, 43 utility and 44 calculation cases; build, types, contracts, lint and secret audit. Final release **PostgreSQL/Redis: 224 tests /1967 assertions**; **Chromium: 15 workflows /457 assertions**. Authored-test strict types/lint, changed-source formatting and diff checks pass. Existing four ignored Rust tests and build warnings remain. No performance measurements ran.
Independent reviewer accepted exact backend/frontend eight-file overlays; root composition/browser/migration-chain fixes were independently reviewed. Source archive, 37 file hashes, native identities and logs are recorded in `manifest.json` → `thirty_second_wave_validation`, under `/tmp/stock-bot-wave32.Dg3iwI/`. The release engine was restored before database/browser validation. Both disposable fixture containers were removed after validation; development services remain untouched. New wave is uncommitted; no push, PR or trading operation occurred.
R08 completion covers deterministic unfitted strategies, explicit zero label horizon, frozen chronological selection, separate reset segments and bounded template cost diagnostics. Unsupported trainable/nonzero-horizon models reject; no purge/fitting framework or global OOS certification is claimed. Next non-performance slice: R07 comparisons across saved experiments with explicit policy/window/cost compatibility. Table measurements stay paused. R09 still also depends on partial R07; do not declare all downstream work ready merely because R08 is validated.
## Thirty-third wave handoff — 2026-10-24
R08 was accepted and committed as `397cd0e` at owner request. R07's functional comparison across saved experiments is now implemented and independently reviewed. Select two standalone parameter/cost experiments in click order, compare every candidate against the explicit left reference (default frozen index zero), change that reference and reopen its URL. Failed, cancelled, missing, incompatible and null-metric outcomes remain visible. Effective fee/spread/slippage and exact run links use retained inputs.
The existing service reads both details on one repeatable read-only snapshot. A small pure helper partitions retained data/window/capital/cost/execution/risk/clock/analytics/seed/build/model inputs, normalizing only the five pinned admission/owner identities. Strategy/version/parameter differences are allowed and shown. Compact summary availability remains separate from matching settings. No financial recalculation, ranking, statistical-validity claim, migration, persistent report or new engine path. Archived/revoked strategies remain historically readable. Review caught and fixed UUID case normalization and an exact selector-label issue before final gates.
All repository gates passed: **988 integration /150 Rust**, plus 93 tooling, 43 utility and 44 calculation tests, build/types/contracts/lint/secret audit. Final release **PostgreSQL/Redis: 228 tests /2013 assertions**; **Chromium: 16 workflows /500 assertions**. Strict all-authored-test types, scoped lint/format and diff/source/DAG checks pass. Four preexisting Rust cases remain ignored. Native browser proof uses five actual Rust trials and checks saved metrics, changed/archived template, approval revocation, reference changes/reload and exact-run drilldown without creating new work.
Independent review accepted both six-file overlays plus root contract/route/browser composition; all 17 source hashes and the archive are recorded in `manifest.json` → `thirty_third_wave_validation`, under `/tmp/stock-bot-wave33.c3IAY2/`. The unchanged release engine was restored before final database/browser gates. Both exact disposable containers were removed; development services are untouched. Wave33 remains uncommitted; no push or PR.
Full R07 remains partial solely because its large-table measurement is explicitly paused and unrun. After accepting/committing this functional component, R09 can consume it without waiting for performance work: record the component commit as a satisfied prerequisite rather than claiming the whole task complete. Next non-performance work is evidence/finding integration over existing R08 validation and cost outputs. R05 provider/default cutover, pending architecture approvals and candidate/AI/multiasset/paper/live activation gates remain unchanged.
## Thirty-fourth-wave handoff — 2026-10-24
The accepted R07 functional comparison is committed as `46a4f13`. Supported R09 is independently reviewed and validated, with new changes uncommitted. Its prerequisite uses the accepted R07 component; the paused table measurement is not a functional dependency. Existing R08 phase/reset/warmup/cost/sample displays remain intact.
- **Exact citations:** Existing immutable finding revisions can cite one standalone experiment, sealed chronological report or sealed walk-forward report, together with selected canonical run/metric references. SQL27 is additive; historical SQL20/22–26 are unchanged. Omitted source preserves the previous citation on revision; explicit null detaches only the new revision. Existing single-run findings and unvalidated narrative status remain.
- **Historical integrity:** One repeatable read-only client verifies immutable source identity, membership and full retained Rust results, including all training evidence underlying sealed reports. Archived, cancelled or currently ineligible sources remain historically readable. Checks reject forged reports, mismatched members, corrupt metrics and direct SQL insertion/timing bypasses. No new evidence store, scheduler, financial calculation or engine path.
- **Web workflow:** The existing finding form offers explicit eligible run/metric choices from experiment and report pages. Stored raw values carry units/null reasons. Source links survive edits, immutable history and reopening. Ambiguous writes remain frozen until the user checks saved records. Regime evidence is explicitly unavailable: S05 retains no versioned as-of classification series, so positive regime reconciliation is neither implemented nor claimed tested.
All final gates passed: **1024 integration /150 Rust** tests, plus 93 tooling, 43 utility and 44 calculation tests; build, types, contracts, lint and secret audit. Release **PostgreSQL/Redis: 235 tests /2099 assertions**; **Chromium: 16 workflows /569 assertions**. Strict affected-test types, scoped lint/format, source/hash/DAG and whitespace checks pass. The first full database run exposed a pre-SQL24 role-projection regression; a conservative metadata-presence projection fixed it, a real pre/post-migration test was added, and all gates were rerun successfully. Four preexisting manual Rust cases remain ignored.
Independent review accepted backend/frontend overlays and root contracts/browser/compatibility changes. Thirty source/test/config/SQL file hashes, exact archive, native identities and logs are recorded in `manifest.json` → `thirty_fourth_wave_validation`, under `/tmp/stock-bot-wave34.02YVEd/`. Archive SHA256: `7df43baf277dc28d7ee186aee233ad13c134b20e0bd86a7300688acb6e0fd8af`. The unchanged release engine was restored before final database/browser gates. Both exact disposable containers were stopped; development services were untouched.
R09 is in review pending acceptance/commit. R05 provider preparation/default cutover, R07 paused measurement, pending architecture approvals and candidate/AI/multiasset/paper/live activation gates remain unchanged. No performance measurements, new-wave commit, push or PR occurred.
## Thirty-fifth-wave handoff — 2026-10-24
R09 was accepted and committed as `06039d1`. R05's explicit source-export preparation slice is independently reviewed and validated; new changes are uncommitted. Full R05 remains partial for durable provider-query preparation/first-run binding and broader default cutover. Current stores do not prove publication times, retained calendars, universe selection or action coverage; none is inferred.
- **Web preparation:** Supply a complete JSON source export (`metadata` and `bars`) inside canonical setup. Preview the normalized hash, exact manifest, UTC bounds, source/calendar/universe/action declarations and availability assumptions without writes. Explicit retention then selects an eligible hash through the existing picker; settings and execution still require separate actions. Existing strategy/policy edits survive. Missing or unsupported evidence remains visible and unavailable for execution.
- **One custody path:** The existing strict normalizer owns content identity and eligibility. A small extracted helper shares immutable insert/readback verification with the unchanged offline import API/CLI, and one extracted existing workbench gate keeps selection/preview consistent. Recomputed hash drift rejects before storage; identical retries/concurrent requests converge on one immutable row. Corrupt retained content fails without overwrite. No new migration, scheduler, simulator or financial semantics.
- **Response and transport behavior:** Captured input/hash survives uncertain retention; definitive 400/409 allows repair. Same-event actions, late reads, changed parent drafts and unmount are fenced. Strict response shape prevents unknown fields being silently discarded. The web server's former 1 MiB restriction is removed with the same explicit setting used by browser fixtures; generic service limits remain unchanged. A real >1 MiB JSON request verifies transport/normalization without claiming unlimited size or measured throughput.
Final validation passed: **1077 integration /150 Rust** tests, plus 93 tooling, 43 utility and 44 calculation cases; build, types, contracts, lint and secret audit. Release **PostgreSQL/Redis: 240 tests /2157 assertions**; **Chromium: 16 workflows /590 assertions**. All affected/new tests passed strict types, and all 16 changed source/test files passed scoped lint/format, hash/DAG and whitespace checks. Four preexisting manual Rust cases remain ignored. The native browser uploads source data, proves zero preview writes and no retention-created jobs, retries the same hash, saves explicit settings, checks the existing hand-calculated fills/fees/equity and reopens saved findings/results. Initial browser failures were selectors, corrected without application changes.
Independent review accepted all eleven agent-owned files plus root contract/transport/browser composition. Review fixed synchronous retry-state clearing, non-strict manifest response parsing and definitive-rejection handling. Exact 16-file archive SHA256 `029dd93e14ee7a9fa72f7b06118c708ce1ecad6711fa6d0411bc0fe2e0ada7fa`, file hashes, reviewer evidence and logs are recorded in `manifest.json` → `thirty_fifth_wave_validation`, under `/tmp/stock-bot-wave35.fQycky/`. The unchanged release engine was restored before final database/browser gates. Both exact disposable containers were stopped; development services were untouched.
Source metadata is supplied evidence, not independently certified provider truth. V1 conversion and automatic provider preparation remain outside this slice. R07 performance measurement and other performance work remain paused; default/multiasset/candidate/AI/paper/live gates are unchanged. No new-wave commit, push or PR occurred.
## Thirty-sixth-wave handoff — 2026-10-24
The owner accepted explicit export preparation, committed as `366bee8`. R05's stored EOD intraday preparation component is independently reviewed and validated, with new changes uncommitted. There are still **37/45 scheduled tasks committed**: two partial (R05/R07), six blocked (S06/P04/A01–A04), six additional deferred and four merged IDs. Counts measure task closure, not remaining effort.
- **Real storage adapter:** The existing preparation panel now accepts complete metadata for one stored EOD raw1m/5m/1h series. The server validates and detaches declarations before querying the existing StorageService with exact bounds and explicit EOD selection. No initialization, shared paper state, external provider request, synthetic/auto fallback or inferred metadata. The row ordinal is deterministic adapter ordering, not a vendor publication sequence; missing VWAP stays null and interval-end availability is explicitly an assumption.
- **Captured data:** Preparation returns the full materialized input and the existing normalized manifest/hash. Retention submits those captured bytes through the unchanged endpoint. Source edits can change a fresh preview but cannot change the original retention/retry or admitted run. The export mode remains intact, invalid/unavailable evidence remains visible, and stale mode/file/parent responses cannot replace the active selection. Cancellation fences late data; the underlying Mongo request may finish in flight without producing a successful cancelled preview.
- **Simpler admission:** The original pending-source-query/first-binding run proposal is intentionally superseded. Canonical data is prepared, reviewed and retained before existing atomic request/hash admission, which the worker verifies before decisions. No new run kind, SQL, scheduler, result schema, financial semantics or runner path. Wider cutover/default/multiasset policy gates remain, so R05 and S06 are not declared complete.
All final gates passed: **1126 integration /150 Rust** tests, plus93 tooling/43 utility/44 calculation tests; build, secret audit, types, contracts and lint. Final release **PostgreSQL/Redis:242 tests /2196 assertions**; **Chromium:16 workflows /612 assertions**. Root strict affected/new-test types and all11-file lint/format/hash/DAG/diff checks pass without exceptions. Four existing manual Rust cases remain ignored. The browser preserves source-export coverage, materializes EOD through the actual adapter, changes stored prices, proves a fresh hash differs, retains/retries the original without another source read, and verifies the existing hand-calculated Rust economics plus reopening. Mongo transport is replaced in fixtures; real MongoDB-server conformance and vendor coverage certification are not claimed.
Independent review accepted five backend and three frontend files plus root shared DTO/fixture/native workflow. The exact11-file archive SHA256 `0fd200ae1a1a27eb919ca7326ced5c9e89c25f1c4d729124b3386fd36ea5ea0d`, source hashes, review evidence, logs and limitations are recorded in `manifest.json` → `thirty_sixth_wave_validation`, under `/tmp/stock-bot-wave36.3Ntmmj/`. The unchanged release engine was restored before final database/browser checks. Both exact disposable containers were stopped; development services were untouched.
Supported source preparation is now available before admission. Remaining substantive decisions concern broader cutover/multiasset mark-risk policy and ADR-007 AI trust; optional daily/QuestDB/v1 adapters are not prerequisites or substitute backlog work. Performance stays paused. No new-wave commit, push, PR or trading/AI activation occurred.
## Scheduled-backlog completion — 2026-10-24
The first parallel group owns: (1) R05/S06 canonical single-asset default and retirement of active competing execution, preserving historical readers/accounts/calculations; (2) A01 operator-provisioned research principals, transactional durable budgets and attribution; (3) R07 production-browser table measurements. Separate worktrees use base `0c6aec4`. Root owns UI cutover/integration and reviews contracts; overlapping runner/admission edits are exchanged as coordinated patches. Next are P04 bounded independent runner slots, A02 OS isolation, A04 human-reviewed paper deployment and A03 the typed evidence-linked client. No task closes until its required tests and review pass. Deferred IDs are not silently marked complete.
## Thirty-seventh-wave handoff — 2026-10-24
R05/S06/A01 are accepted. Production starts canonical research by default; explicit canonical paper remains halted until existing operator/feed/recovery checks pass. New legacy research and old native worker commands refuse, while historical results, prototype algorithms, calculations and durable recovery remain. Single-asset admission stays enforced; no simultaneous multi-asset policy is approved by this cutover.
Research credentials are hash-only, project/template scoped and independently revocable. SQL enforces active capacity, complete recipe work, attempt limits and deadlines across retries and validation phases. Operator UI provisioning, usage and revocation work against real APIs. Independent review closed retry/phase-budget bypasses and stale UI responses before acceptance. Accepted bounded work may finish after credential revocation.
Evidence: 1233 integration/tooling tests, 254 PostgreSQL tests, 17 real-browser workflows, 150 active Rust tests; four existing Rust tests remain ignored. Final types/lint/format and production builds pass. Exact source archives, native hash, logs and limitations: manifest `thirty_seventh_wave_validation`. The async replay/controller extraction is tested groundwork for A02; arbitrary candidate execution is not claimed complete.
Next owners: A02 owns candidate contracts/SQL29/sandbox/worker; P04 owns pool and research composition; A04 owns SQL30, promotion/evidence and paper runtime/UI. Root owns migration registration, bootstrap merge, shared navigation/browser integration and acceptance. A04 can build components in parallel but candidate release waits for A02. A03 follows candidate admission. No agent independently changes financial policy.
## Thirty-eighth-wave progress — 2026-10-24
P04 committed as `26b9726`: a configurable 1/2/4-slot pool reuses existing durable claims, one-shot native workers, cancellation and result fencing. Default concurrency remains one. Root reviewed pool ownership, run-scoped controls/status, shutdown and the benchmark. Slot reuse cannot report a prior run's progress; shutdown drains all executions and reports actual shutdown failures without treating expected rejected reservations as infrastructure faults.
Five paired 24 × 10,000-bar batches at each limit produced 360 matching per-candidate economic hashes. Median whole-batch completion: 51.853s / 28.629s / 16.315s at 1/2/4 slots (0.463 / 0.838 / 1.471 trials/s). Four slots measured about 3.18× median throughput on this host; sampled driver plus descendants peaked at 2.50 / 2.59 / 3.24GB. Queue-inclusive p95 and complete raw phases/hashes are in the manifest-linked report. This is one single-asset workload, not a universal scaling claim. A shutdown-only correction followed measurement; final focused gates passed: 63 unit/integration tests, 323 assertions, plus 5 real PG/Redis/native tests, 53 assertions, static types/lint/format. No financial engine semantics changed.
This intermediate P04 record is superseded by the final acceptance below. Conditional optimizations and unsupported multi-asset production policy remain deferred.
## Thirty-eighth-wave final acceptance — 2026-10-24
Implementation committed as `25b5cbf`; all **45 scheduled tasks are done**. A02/A03/A04 join the previously committed pool and canonical cutover. Six conditional tasks (D04/P03/P05/P06/P08/O02) keep their existing evidence/approval gates, and four merged IDs remain redirects. The manifest remains the scheduling source of truth.
A02 runs arbitrary retained TypeScript in a pinned local Linux x64 image with an unprivileged child, restricted syscalls, no network or host/data/secret mounts, cgroup limits, bounded framing and an independent Rust guardian. Native replay publishes only available prefixes; the supervisor validates identity and target intent before the same Rust financial engine applies it. Process exit, actual stdout EOF, deadline, cancellation and supervisor death fail safely. Catalog approval never changes a candidate's isolated research path. The small packaging CLI transpiles self-contained TypeScript inside isolation without evaluating it or installing dependencies. Candidate warmup and deterministic behavior remain unverified author declarations.
A03 adds a typed client and one bounded example, using existing APIs and shared pure response decoders. It captures candidate proposals before reading performance, runs training before server-selected holdouts, compares completed cost studies afterward, retains failed candidates, and saves exact evidence-linked AI findings. A mandatory durable receipt journal supports explicit recovery; non-idempotent narrative/family writes are never blindly replayed. No model SDK, agent framework, additional simulator or automatic promotion is introduced.
A04 links sealed test evidence and complete cost studies to immutable human-reviewed paper deployments. Native engine/wrapper/runtime/dependency identity must match the supporting research; worker and paper-host bundles retain distinct identities. The host starts unbound/halted, verifies the original human credential and browser Origin, loads the exact approved factory, and preserves cash, positions and strategy state across restart. Actual candidate research→human promotion→Rust paper fills→restart is tested with disposable accounts. The browser can create and reopen the deployment without creating an account or activating trading.
Integration review also fixed the agent project-link/revision authorization conflict through additive SQL31, retained ambiguous-write keys across same-event edits/navigation, normalized captured UUIDs and bound candidate parameters to the returned preview. These are narrow corrections to existing paths. The canonical default remains single asset/single series and cash-funded long-only; ownerBudget is a sizing input, not a separate Rust allocation constraint. Real activation, existing account migration, live execution and the simultaneous multi-asset mark decision remain outside this completion.
Validation: full `bun run check` passed (1,408 Bun tests across tooling/utilities/calculations/integration; 150 Rust tests passed, four existing ignored). The 273-case PostgreSQL run initially found three obsolete fixture assumptions: two candidate diagnostic strings and a public engine handle replaced by the private pool. After correcting those tests, all 18 affected-file cases passed, and the typed paper-isolation event variant passed 2/36 assertions. Final-profile candidate/AI/paper database proofs passed **13/259**; root sandbox/contract proofs **21/88**; the complete browser suite **18/655**, with the candidate workflow repeated on the final image **1/19**. Explicit authored-test types, scoped lint, formatting, guardian compilation/rustfmt and independent reviews passed. The manifest retains exact commands/log hashes, intermediate failures and their superseding evidence; no unresolved check is represented as passing.
The retained `scripts/benchmark-candidate-isolation.ts --measure` diagnostic used one 1,000-bar asset/strategy, a first-process pair and five alternating warm pairs. All 12 full financial hashes matched. Warm median trusted/isolated totals were **138.1/945.1ms**; isolated startup/replay/cleanup were **282.5/575.7/80.2ms**. Shared dataset/package/preflight setup was reported separately at **203.1ms**. The first pair is not an OS-cold measurement, and this shared-host result is not a capacity guarantee or authorization for a DSL/cache rewrite. Raw phases, identities and hashes are retained with the manifest; P04's independent 1/2/4-worker measurements remain above.

View file

@ -1,26 +0,0 @@
# Reusable implementation-agent brief
This is a role instruction, not a new agent framework. It authorizes nothing on its own.
## Invocation packet
Planner supplies: task ID/file, manifest revision, approved ADR IDs, base commit, branch/worktree path, reserved file locks, predecessor merge commits, acceptance scenarios, baseline failures and authorized test/commit/PR permissions.
## Procedure
1. Confirm global execution authorization, task readiness/claim and architecture approval. Read the task, relevant ADRs, quality gates and actual code. If evidence has drifted, report it before changing scope.
2. Work only in the assigned worktree. Preserve user/unrelated changes. Do not edit canonical task status or shared contracts owned by another agent.
3. Reproduce the defect or establish the current behavior. Implement the smallest cohesive change and its regression tests. Keep useful calculations, fixtures and recovery behavior.
4. Use the approved financial core and contracts. Do not create fallback accounting, change rounding/clock/ownership policy or expose broker execution to strategies.
5. Run mandatory task tests plus relevant gates; use disposable DB/queues. Record exact commands and failures. A missing dependency or skipped test is not success.
6. Review your own diff for unrelated edits, stale documentation, artifacts/secrets and backward compatibility.
7. If commits/PRs are authorized, produce a focused commit and PR against the assigned integration branch, referencing task ID, dependency commits, tests and limitations. Otherwise leave changes uncommitted and hand off a diff; do not infer permission.
8. Request independent review. Do not merge yourself or mark done.
## Stop / handoff conditions
Architecture ambiguity, blocked dependency, unexpected shared-contract change, failing economic invariant, unavailable isolation or irreconcilable baseline drift: report task ID, evidence, attempted checks, smallest decision needed and safe remaining work. Do not silently widen scope.
Unfinished handoff includes branch/worktree, base and latest commit or uncommitted diff, files touched, tests run, failing case, fixture expectations and next concrete step. Do not discard unfinished work.
First-wave prompts and exact writable/read-only boundaries are in [FIRST-WAVE.md](../FIRST-WAVE.md). Merged IDs are not work items. Do not add a compatibility toggle to preserve a correctness defect, or populate missing benchmark counters with zeros.

View file

@ -1,30 +0,0 @@
# Reusable integration-agent brief
One integrator owns the shared integration branch and canonical contract sequencing. No two agents modify tightly coupled canonical financial contracts concurrently. The first-wave Rust legacy terminal fix and TS legacy fee guard are disjoint corrections, not concurrent design of the new contract.
## Isolation and claim rules
After owner approval, planner atomically assigns one task and write locks in the canonical manifest on the coordination branch. Create a branch/worktree from the recorded integration commit, for example `plan/C01-terminal-equity` and a sibling worktree. These are examples for later execution, not commands run by this planning task.
Each implementation worktree edits only its code scope, never task status. The planner alone writes status/assignment changes; implementation PRs cannot overwrite a stale manifest. Acquire both symbolic locks and concrete-file ownership. SQL migration numbering/registry is assigned by the integrator.
## Integration sequence
1. Require dependencies merged and ADRs approved. Shared contract tasks merge before their consumers; no “probably compatible” simultaneous F01/F02/F04 changes.
2. Require independent review and exact task acceptance evidence.
3. Rebase/merge onto current integration base in dependency order; handle textual and semantic conflicts together. For contract overlap, pause a branch and let the contract owner resolve the design—never choose a side blindly.
4. Run relevant combined native/TS/SQL/browser gates, plus economic/decision hash fixtures. Test mixed old/new stored data where compatibility is claimed.
5. Update task completion through planning owner only after tests pass on the integrated commit. Record commit, review and gate references.
6. Recompute readiness and release locks. Do not unlock downstream implementation merely because a PR exists.
PR creation, commits and merges require explicit execution authorization; this plan does not grant it. No force-reset of user work. Rollback uses a deliberate compatible deployment/commit, not destructive rewriting of historical financial state.
## Safe concurrency
Recommend **3 implementation agents maximum**, with one of them holding the single financial-core lane. A fourth concurrent slot can be a read-only reviewer when available; otherwise rotate review between implementation batches. Do not independently spawn nested implementation teams.
Typical parallel lanes: Rust financial owner; web/product owner; data/tests/benchmark or metadata owner. See [FIRST-WAVE.md](../FIRST-WAVE.md) for the four exact independent assignments; rotate the fourth through the three implementation slots. Shared API DTOs, `libs/core/types`, worker protocol, run service and SQL registry serialize when they overlap—even if task lock names differ.
## Failed integration
Leave task in review/blocked with explicit failing combined test and owner. Preserve worktree and artifacts. No status “done except integration.” Paper/live state is never used as an integration fixture.

View file

@ -1,23 +0,0 @@
# Reusable planning-agent brief
Maintain the backlog, not application code. Read manifest, completed/reviewed changes, approved ADRs and newly discovered evidence.
## Source of truth and state
Only `backlog/manifest.json` owns scheduling state, dependencies, assignments, priorities and write locks. Task files own behavior/scope/acceptance. Roadmap/index/graphs are views; update them after metadata changes, never use them as a competing status board.
Merged IDs are traceability redirects and may never be claimed. Deferred optimization requires its measured activation decision. `dependencies` gate implementation; `release_gates` gate feature activation, not component integration/done.
States: ready -> claimed -> in_progress -> review -> done. blocked is for an actual unmet code/approval/environment prerequisite with a recorded reason; deferred requires its explicit future gate. All tasks also obey global `execution_authorized`. Initial ready means code-ready **after plan approval**, not permission to act.
## Work cycle
1. Check repository/task evidence drift and dependency completion. A task is ready only when required commits are integrated, ADRs approved and resources available.
2. Select a small ready batch with disjoint actual files and locks; prioritize economic correctness and early web value.
3. Assign owner/worktree/base/lock metadata in one serialized coordination update. Supply the implementation invocation packet.
4. Track blockers with evidence, smallest unblock decision and safe alternatives. Do not call a difficult task blocked merely to abandon it.
5. On accepted integration, record commit/review/test references, mark done and recalculate the DAG. On scope split, create a stable new ID and update edges; do not reuse IDs.
6. For an ADR change, obtain owner approval and identify every affected contract/task before reopening work.
7. Keep the first-wave/dependency views consistent; validate unique IDs, all references, no cycles, valid statuses and approved decision gates.
Do not launch coding agents, commit, open PRs or change application files unless the owner has separately authorized execution. P06 remains deferred until the measured gate and owner go/no-go are recorded.

View file

@ -1,21 +0,0 @@
# Reusable independent review-agent brief
Review the assigned task/approved ADRs and implementation diff independently. Do not implement fixes or approve your own financial change.
## Required review
- Re-derive financial fixture expectations; do not accept the engine output as its own oracle.
- Inspect time availability, same-bar execution, pending reservations, fees/rounding, owner basis, risk bypasses, ordering, partial failure and terminal marking.
- Check crash boundaries, idempotent identities, restore-before-decision and per-effect state. Native state must not advance past a rolled-back SQL transaction.
- Check API/schema compatibility, legacy provenance, data immutability and loading/error/empty UX. New browser pages must use the same API/core.
- Check sandbox boundary, actor permissions and no AI-to-live path.
- Look for unnecessary abstractions, duplicated calculation/simulation, unjustified deletions and scope creep.
- Re-run focused tests independently where available. Verify benchmark comparison uses identical semantics and inputs.
## Output
Return Accept / Changes requested / Blocked, with severity, file/line evidence, violated task criterion and required test. State what was and was not run. Approval requires all in-scope mandatory gates or an explicit owner-approved waiver that does not waive financial correctness.
A reviewer may suggest a future task but cannot silently amend ADRs or expand this PR. Communicate contract-impacting findings to integration/planning owner.
Check that remaining-cost residuals, target/order-mode exclusivity, immutable decision barriers and RNG restore are explicit. Distinguish component tests from release gates; do not require later UI/metrics/cache work to approve an independently correct component. Do not call statistical reporting outside Rust a competing simulator when it only consumes authoritative financial outputs.

View file

@ -1,44 +0,0 @@
# Whole-application architecture cleanup
**Complete: 14/14 cleanup tasks; 113/113 selected backlog tasks.** Baseline `1a9f07b2`. The owner authorized all October 28 audit recommendations and a commit after each validated task. Five optional extensions remain deferred; four merged IDs are redirects.
Agents worked on root-reserved, disjoint files in the integration worktree. Root reviewed and committed each task and built shared outputs. Independent reviews checked shared custody, composition, transactions, analytics startup and queue/handler lifecycle. No isolated native agent-build claim is made.
## Changes and commits
| Task | Result | Commits |
| --- | --- | --- |
| [CL22](backlog/tasks/CL22.md) | Own queue transports without deleting pending payloads | `3fc0a272`, `1aa35d2d` |
| [CL23](backlog/tasks/CL23.md) | Reject retired backtest creation before persistence | `cd1aa614` |
| [CL24](backlog/tasks/CL24.md) | Remove prototype dashboard from normal navigation | `5400dba4` |
| [CL25](backlog/tasks/CL25.md) | Share validated product response contracts | `366a6054`, `2a9382a2`, `ed7429cf` |
| [CL26](backlog/tasks/CL26.md) | Replace private application imports with explicit shared modules | `b4589d5a`, `33e22404` |
| [CL27](backlog/tasks/CL27.md) | Initialize enabled ingestion handlers once per container | `5c9e32d0`, `dac49ac1` |
| [CL28](backlog/tasks/CL28.md) | Compose research services with explicit collaborators | `24487d35` |
| [CL29](backlog/tasks/CL29.md) | Share transactional experiment run and dispatch insertion | `731acc41` |
| [CL30](backlog/tasks/CL30.md) | Separate research UI workflow state from rendering | `a411f9a6` |
| [CL31](backlog/tasks/CL31.md) | Publish a stable strategy authoring contract | `3a63b203` |
| [CL32](backlog/tasks/CL32.md) | Separate paper safety enforcement from readiness projection | `2165a2ef` |
| [CL33](backlog/tasks/CL33.md) | Isolate legacy repository writers from production capabilities | `ec582bd5` |
| [CL34](backlog/tasks/CL34.md) | Normalize provider symbols and remove unused scaffolding | `e2292e48` |
| [CL35](backlog/tasks/CL35.md) | Make optional Python analytics composition honest and testable | `7ae6ac21` |
The API and orchestrator now share server-side historical storage, admission and lazy artifact inspection through `libs/trading-runtime`. Browser-safe contracts remain in `stock-config`, and strategy authors use the type-only `@stock-bot/research/strategy-api`. Rust remains authoritative for financial semantics. Existing compatibility paths preserve historical readers and tests.
Independent review caught the queue's previous worker timeout of two seconds and manager timeout of five seconds falsely completing shutdown. Follow-up commits retain the actual drain promise; the regression runs beyond both former deadlines and proves transports stay usable until the worker completes. A real Redis fixture verifies pending payload survival and later consumption.
## Final verification
- `CARGO_BUILD_JOBS=2 bun run check`: all gates passed — build, source/contract types, secret audit, lint, 179 tooling, 43 utility, 44 calculation, 1,609 integration and 150 Rust tests.
- `bun run test:postgres`: **287 passed**, 2949 assertions, 0 conditional skips; disposable PostgreSQL/Redis only. Covers transaction rollback, duplicate submissions, numbering, holdout boundaries, leases, recovery, paper safety, provider mapping and queue shutdown.
- `bun run test:e2e`: **27 Chromium workflows passed**, 971 assertions, against the same disposable stores and a fresh production web build.
- `bun run test:analytics-api`: **11 passed**, including actual FastAPI app import/lifespan with missing optional dependencies, structured unavailable responses and successful runtime stubs.
- Additional new-test lint, scoped formatting and whitespace checks passed. Native addon SHA256: `df0ecbd5c3772d7e8aeb0226b40ae290cfaddf9d87fb3a7375f2a31c2acf05e5`.
The first combined check exposed Bun bundling descriptor interference and two old web fixtures using incomplete records/wrong success statuses. Bundling probes now use isolated processes, fixtures match actual 202 run and 201 review responses, and the complete repository gate passed on rerun. Chromium also caught valid historical SQL-null configuration rejected by the new response schema; nullable read contracts and guarded UI access now preserve those records, with regression coverage. Browser error assertions now follow the actual server and transport diagnostics.
The subprocess replay regression now has a 30-second deadline (`8c54eb7e`); its financial and hash assertions are unchanged. Its previous five-second deadline timed out during concurrent browser verification. The final repository check ran sequentially and passed.
Four manual Rust cases remain ignored, and 14 opt-in real OS-isolated candidate integration tests were not enabled. Python successful scientific and multipart paths use stubs; heavy optional runtimes were not installed. This cleanup does not claim new market-data coverage, faster backtests, or live-trading readiness.
Full command logs for this session are `/tmp/stock-bot-architecture-cleanup-check-final.log`, `/tmp/stock-bot-architecture-cleanup-postgres.log`, `/tmp/stock-bot-architecture-cleanup-browser.log` and `/tmp/stock-bot-cl35-root.log`. Task files retain focused acceptance evidence; [manifest.json](backlog/manifest.json) remains the canonical status record.

View file

@ -21,4 +21,4 @@ Correctness/policy hashes must match. Keep financial event processing serial wit
## October 28 review outcome
P08 implements one measured local TypeScript state-handling optimization, preserving exact Rust economic hashes. D04/P03/P05/P06 remain deferred; CL21 also remains unnecessary without a concrete replay edit. No new blanket performance pause is imposed. [Review, raw measurements and verification](../../conditional-review.md).
P08 implements one measured local TypeScript state-handling optimization, preserving exact Rust economic hashes. D04/P03/P05/P06 remain deferred; CL21 also remains unnecessary without a concrete replay edit. No new blanket performance pause is imposed; see [benchmarks.md](../benchmarks.md) for measured figures.

View file

@ -4,7 +4,7 @@
> the pre-migration state and proposed design, not today's runtime. For the implemented
> connections and current strategy API, start with the [project guide](../../guide/README.md).
Planning baseline: commit `b7aeca4`, inspected 2026-10-22. This is a proposed plan, not an implementation or project correctness-gate evidence. [Decisions](../backlog/manifest.json) and [verified findings](../backlog/findings.md) distinguish user mandates, proposed policies and uncertainties.
Planning baseline: commit `b7aeca4`, inspected 2026-10-22. This is a historical baseline, not today's runtime contract; see [architecture decisions](./decisions) and [PLATFORM-PLAN.md](../../PLATFORM-PLAN.md) for current boundaries and locked decisions.
## What exists

View file

@ -1,255 +0,0 @@
# Canonical development backlog
**E13 architecture cleanup: CL22–CL35 (14/14 complete).** Each task is committed and the combined repository, database and browser gates passed. [Execution record](../architecture-cleanup-execution.md). Earlier milestone counts below are historical.
**Current scheduled backlog: 113/113 complete (100%).** The October 28 whole-application cleanup adds 14 completed tasks to the earlier 99. Five optional extensions remain deliberately deferred, and four merged IDs remain redirects. [Conditional decisions](../conditional-review.md).
**The original 45/45 scheduled tasks are complete.** The canonical Rust engine, TypeScript research/workbench, bounded worker pool, isolated candidates, AI evidence workflow and human-reviewed paper promotion are validated. Implementation commits: `bbf0dd4`, `26b9726`, `25b5cbf` (R07 measurement `ab08db8`). Six conditional tasks remain deferred; four merged IDs remain redirects. This is scheduled-backlog completion, not live-trading activation.
**New work:** [13 cleanup stories](../CLEANUP.md) were proposed on October 26, 2026. The owner subsequently authorized implementation and commits; see [execution evidence](../cleanup-execution.md). All 13 are implemented and independently accepted; review corrections are recorded in [real-data-research.md](../real-data-research.md).
## One source of truth
[manifest.json](manifest.json) owns scheduling metadata: status, priorities, dependencies, ADR approvals, assignments and write locks. Task Markdown owns implementation scope/evidence/acceptance. This index and the [graph](dependencies.mmd) are derived views. Only the planning/integration owner updates scheduling state.
**Current total: 122 retained IDs — 113 done, 5 deferred, 4 merged.** No selected task is ready or active. D04/P03/P05/P06/CL21 retain their documented reopen conditions. The manifest owns scheduling and verification evidence.
States: ready, claimed, in_progress, review, done, blocked, deferred, merged. “Ready” means no code/ADR prerequisite, not execution authority. Implementation dependencies require accepted integration. `release_gates` govern enabling an end-to-end feature, not component coding or integration; conditional gates apply only to the named capability. F05 may integrate before F06, but its replay behavior is not released until F06 proves it.
Relative size: S narrow correction, M coherent boundary, L sensitive owner-controlled integration; not calendar estimates. Actual file overlap overrides symbolic lock names. No compatible structured issue tracker was found; do not duplicate task state in another system.
## Complete task index
### E1 — Immediate correctness and runtime containment
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [C01 Correct native terminal valuation](tasks/C01.md) | P0 / done | None | — | Rust financial correctness / S |
| [C02 Reject malformed native data and preserve milliseconds](tasks/C02.md) | P1 / done | None | — | Rust/NAPI boundary / S |
| [C03 Close the existing TypeScript fee-funding hole](tasks/C03.md) | P0 / done | None | — | Trading infrastructure implementation / M |
| [C04 Make partial runtime initialization recoverable](tasks/C04.md) | P1 / done | None | — | Trading infrastructure implementation / S |
| [C05 Create economic regression fixtures independent of implementations](tasks/C05.md) | P0 / merged → F01 | None | — | Quantitative correctness/test engineering / M |
| [C06 Contain legacy research/paper interference without a second runtime](tasks/C06.md) | P0 / done | C04 | — | Trading infrastructure implementation / S |
### E2 — Canonical Rust financial engine
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [F01 Define the minimal financial contract and economic fixtures](tasks/F01.md) | P0 / done | ADR-002, ADR-003, ADR-004 (approved) | — | Rust financial contract owner / M |
| [F02 Implement one owner-aware financial ledger](tasks/F02.md) | P0 / done | F01, ADR-002 | — | Rust accounting / L |
| [F03 Add strategy-owned position books and fill allocations](tasks/F03.md) | P0 / merged → F02 | None | — | Rust portfolio accounting / M |
| [F04 Enforce cash reservations and portfolio risk centrally](tasks/F04.md) | P0 / done | F02, ADR-002, ADR-003 | — | Rust financial risk / L |
| [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / done | F04, ADR-003 | F06 | Rust execution semantics / L |
| [F06 Implement deterministic replay once, with linear historical traversal](tasks/F06.md) | P0 / done | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M |
| [F07 Expose bounded Rust step sessions through existing NAPI workers](tasks/F07.md) | P0 / done | F06, C02, ADR-004 | — | Rust/TypeScript integration / M |
| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / done | F06, F09, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M |
| [F09 Return compact canonical replay projections](tasks/F09.md) | P1 / done | F07, ADR-002, ADR-003, ADR-004 | — | Rust/TypeScript financial integration / M |
### E3 — Point-in-time datasets and features
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [D01 Introduce availability-aware dataset v2](tasks/D01.md) | P0 / done | ADR-003 (approved) | — | TypeScript trading infrastructure / M |
| [D02 Connect supported intraday storage to research datasets](tasks/D02.md) | P1 / done | D01 | — | TypeScript trading infrastructure / M |
| [D03 Add dataset eligibility and corporate-action safeguards](tasks/D03.md) | P1 / merged → D01 | None | — | TypeScript trading infrastructure / M |
| [D04 Provide prefix-safe shared feature calculation](tasks/D04.md) | P1 / deferred | S01, P01 | — | Quantitative feature engineering / M |
### E4 — TypeScript strategies and durable paper integration
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [S01 Run deterministic TypeScript decisions on Rust sessions](tasks/S01.md) | P0 / done | F07, ADR-004, ADR-005 | — | TypeScript trading infrastructure / M |
| [S02 Adapt one SMA strategy for the first canonical path](tasks/S02.md) | P1 / done | S01 | — | TypeScript strategy/quant engineering / M |
| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / done | S01, C06, ADR-005 | — | Durable execution/Rust integration / L |
| [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / done | S02, S03 | — | TypeScript trading infrastructure / M |
| [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / done | S02, F08 | R08 | Quant strategy research / M |
| [S06 Retire duplicate simulator paths after cutover proof](tasks/S06.md) | P2 / done | S03, S04, R05 | — | TypeScript trading infrastructure / M |
### E5 — Existing web backtest vertical slice
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [W01 Make existing run controls and selection truthful](tasks/W01.md) | P1 / done | None | — | Full-stack React/API / M |
| [W02 Expose result provenance and legacy correctness limitations](tasks/W02.md) | P1 / done | W01 | — | Full-stack research UX / M |
| [W03 Separate save, submit and repeat-safe run creation](tasks/W03.md) | P1 / done | O01 | — | Full-stack durable workflow / M |
| [W04 Verify the first research vertical slice in a browser](tasks/W04.md) | P1 / done | W01, W02, W03, C06 | — | Full-stack test engineering / M |
### E6 — Research product, provenance and validation
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [R01 Persist immutable strategy versions and parameter schemas](tasks/R01.md) | P1 / done | O01, ADR-006 | — | Full-stack research product / M |
| [R02 Deliver strategy catalog and version-aware backtest setup](tasks/R02.md) | P1 / done | R01, W03, ADR-006 | W04 | Full-stack research product / M |
| [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / done | R01, R10, ADR-006 | — | Full-stack research product / M |
| [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / done | R03, W02, ADR-006 | W04 | Full-stack research product / M |
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / done | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / done | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M |
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / done (measurement committed ab08db8) | R06, ADR-006 | W04 | Full-stack research product / M |
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / done | R06, ADR-006 | — | Quantitative research integrity / M |
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / done | R08, committed R07 functional component, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M |
| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / done | R01, ADR-006 | — | Full-stack research product / M |
| [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / done | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M |
| [R12 Reproduce an original run separately from rerunning current settings](tasks/R12.md) | P1 / done | Accepted R05 retained-input component; W04/R01/R10/F08/S02/D01/W03/C06, ADR-006 | — | Full-stack reproducible research / S |
### E7 — Measured research throughput
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [P01 Measure existing research paths before extending the benchmark](tasks/P01.md) | P2 / done | None | — | Performance/infrastructure engineering / M |
| [P02 Remove measured replay queue and hot-loop overhead](tasks/P02.md) | P2 / merged → F06 | None | — | Performance/infrastructure engineering / M |
| [P03 Reuse validated datasets within bounded native workers](tasks/P03.md) | P2 / deferred | F07, P01, ADR-004, ADR-008 | — | Performance/infrastructure engineering / M |
| [P04 Schedule deterministic batches across a bounded worker pool](tasks/P04.md) | P2 / done | F07, R06, C06, P01, ADR-008 | — | Performance/infrastructure engineering / M |
| [P05 Separate result summaries from paged detail payloads](tasks/P05.md) | P2 / deferred | R06, P01 | — | Performance/infrastructure engineering / M |
| [P06 Conditionally add a minimal Rust-executed strategy plan](tasks/P06.md) | P2 / deferred | P04, S01, ADR-008 | — | Rust/TS performance compiler boundary / M |
| [P07 Profile representative canonical replay workloads](tasks/P07.md) | P1 / done | F07, P01 | F09 for compact comparisons | Performance/test infrastructure / M |
| [P08 Reduce measured TypeScript strategy decision overhead](tasks/P08.md) | P1 / done | S02, P07 | — | TypeScript performance/runtime engineering / M |
### E8 — Authorized, isolated AI research
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [A01 Add research-only principals and durable job budgets](tasks/A01.md) | P1 / done | R06, O01, ADR-007 | — | Backend security/durable scheduling / M |
| [A02 Isolate untrusted TypeScript strategy builds and decisions](tasks/A02.md) | P1 / done | A01, S01, P01, ADR-007 | — | Process isolation/security / L |
| [A03 Implement an evidence-linked AI research workflow client](tasks/A03.md) | P2 / done | A02, R08, R03, ADR-007 | — | AI research integration / M |
| [A04 Add human-reviewed promotion to paper deployment](tasks/A04.md) | P2 / done | S04, R09, A01, R01, ADR-007, ADR-005 | — | Full-stack paper trading integration / M |
### E9 — Migration and operational safeguards
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [O01 Serialize additive schema migrations safely](tasks/O01.md) | P1 / done | None | — | PostgreSQL/backend infrastructure / S |
| [O02 Expose truthful research and paper readiness diagnostics](tasks/O02.md) | P1 / done | S04 | — | Infrastructure/observability / M |
### E10 — Cleanup and maintainability foundations
Scope and first execution wave: [CLEANUP.md](../CLEANUP.md). The owner has authorized implementation and commits. Current completion evidence is in [cleanup-execution.md](../cleanup-execution.md); the manifest owns task state.
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
| --- | --- | --- | --- | --- |
| [CL01 Replace permissive DI configuration tests with production-path assertions](tasks/CL01.md) | P1 / done | None | — | TypeScript infrastructure testing / M |
| [CL02 Normalize database configuration once and enforce consistent service switches](tasks/CL02.md) | P1 / done | CL01 | — | TypeScript configuration and database adapters / M |
| [CL03 Roll back failed shared-service startup and clear initialization timers](tasks/CL03.md) | P1 / done | None | — | TypeScript resource lifecycle and concurrency / M |
| [CL04 Provide one consistent research startup path and repair stale commands](tasks/CL04.md) | P1 / done | None | — | Bun/Turbo developer tooling / S |
| [CL05 Extract shared dataset and reporting logic behind a research library boundary](tasks/CL05.md) | P2 / done | D01, F08, R05 | — | TypeScript domain boundaries and package migration / M |
| [CL06 Use shared dataset response schemas and eligibility checks in the workbench](tasks/CL06.md) | P2 / done | CL05 | — | Shared contracts and frontend validation / M |
| [CL07 Share JSON transport handling across experiment and validation clients](tasks/CL07.md) | P2 / done | None | — | Frontend HTTP contracts and retry semantics / M |
| [CL08 Split backtest template, run and reproduction responsibilities behind the existing service](tasks/CL08.md) | P2 / done | CL05 | — | TypeScript application services and PostgreSQL transactions / M |
| [CL09 Separate strategy metadata, version inspection and publication UI](tasks/CL09.md) | P2 / done | None | — | React strategy workflows / M |
| [CL10 Separate experiment modes and make draft/submission state explicit](tasks/CL10.md) | P2 / done | None | — | React experiment workflow state / M |
| [CL11 Separate backtest template loading, run monitoring and submission state](tasks/CL11.md) | P2 / done | None | — | React asynchronous state and durable-run UX / M |
| [CL12 Simplify retired execution seams while preserving historical reads](tasks/CL12.md) | P2 / done | CL08 | — | Compatibility cleanup and execution boundaries / M |
| [CL13 Hide placeholder navigation while preserving useful product routes](tasks/CL13.md) | P2 / done | None | — | React navigation and product clarity / S |
## Scheduling checks
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
R06/R08/R09 and the R07 comparison/measurement are complete. The default supports canonical single-asset research. Regime panels require actual retained annotations; no arbitrary candidate regime labels or profitability claims are inferred. The six conditional tasks keep their evidence/approval gates. Completing scheduled implementation does not activate paper/live trading or approve a multi-asset mark policy.
## Completion review — October 28, 2026
**Historical review before the owner resumed performance. Superseded by the [conditional review](../conditional-review.md) and current manifest counts above.**
The owner requested “commit and continue until backlog is complete”. Rechecking the canonical manifest found 97 completed scheduled tasks, seven deferred items and four merged redirects, with no active or otherwise ready tasks. The review preserves deferred status rather than inventing implementation or silently cancelling scope. The earlier explicit performance pause remains in effect while the owner answers the scope clarification.
| Conditional task | Activation requirement | Current outcome |
| --- | --- | --- |
| [D04 Shared features](tasks/D04.md) | Profiling demonstrates meaningful repeated identical feature work | Unmeasured; use the reviewed calculations directly. |
| [P03 Resident datasets](tasks/P03.md) | Repeated admission is a material measured sweep cost | No accepted activation measurement; preserve isolated one-request workers. |
| [P05 Paged result detail](tasks/P05.md) | Large-detail query/payload/render measurements justify paging | Existing experiment summaries and full retained exports remain; no new paging layer. |
| [P06 Rust strategy plan](tasks/P06.md) | Representative profiles, owner go/no-go, explicit prototype budget/target | No prototype decision or budget. The financial-authority defect in its historical audit evidence is already resolved by F02–F07/S06. |
| [P08 TypeScript overhead](tasks/P08.md) | Owner resumes the performance work paused on October 23 | Scope question pending. Saved aggregate SMA timings do not identify the internal cost to remove. |
| [O02 Cross-service readiness](tasks/O02.md) | Activate the optional monitoring expansion | Still unfinished: legacy monitoring has placeholder metrics. Existing run diagnostics and paper readiness do not amount to this broader capability. |
| [CL21 Replay preparation extraction](tasks/CL21.md) | A concrete upcoming calendar/timeframe edit benefits from the split and owner activates it | No such edit is scheduled; avoid a purely cosmetic financial-core move. |
On source commit `974a29c7`, `CARGO_BUILD_JOBS=2 bun run check` passed: build, application/contracts types, secrets, lint, **169 tooling / 43 utility / 44 calculation / 1,548 integration / 150 Rust tests**, zero failures. Fourteen existing integration skips and four ignored Rust tests remain. Full log: `/tmp/stock-bot-backlog-completion-check.log`. This does not rerun PostgreSQL/browser suites or certify paper/live activation. The latest source-scoped browser gate remains RP32's 26 passing tests.
This review changes documentation and scheduling summary only. Application code, task statuses, conditional gates and trading activation remain unchanged. No new benchmark, real-data experiment, external message, push or PR was performed. The manifest owns the machine-readable audit and exact build identity.
## E11 — Orchestrator and engine cleanup
Owner authorized planning and per-task implementation commits. [Execution plan and validation](../orchestrator-engine-cleanup.md). All seven scheduled stories CL14–CL20 are complete. CL21 remains conditional. Earlier cleanup reviews and the six original conditional tasks remain unchanged.
| Task | Priority | Dependencies |
| --- | --- | --- |
| [CL14 Require canonical capabilities in durable research contracts](tasks/CL14.md) | P1 | None |
| [CL15 Retire abandoned Rust architecture scaffolding](tasks/CL15.md) | P1 | None |
| [CL16 Give orchestrator composition an explicit shutdown owner](tasks/CL16.md) | P1 | None |
| [CL17 Separate historical reads from unused storage writes](tasks/CL17.md) | P2 | CL14 |
| [CL18 Share strict native parsing and financial view projection](tasks/CL18.md) | P2 | CL15 |
| [CL19 Share pure strategy bookkeeping and event ordering](tasks/CL19.md) | P2 | None |
| [CL20 Return validated retained results from the worker supervisor](tasks/CL20.md) | P2 | CL14 |
| [CL21 Extract private deterministic replay preparation when needed](tasks/CL21.md) | P3 | Conditional |
## E12 — Real-data research workflow
- [RP01: Stored source coverage and quality](tasks/RP01.md) — done, `5bfaf37d`; explicit indexed instrument/timeframe lookup and window diagnostics.
- [RP02: Retained real-data pilot](tasks/RP02.md) — done after explicit approval; nine completed runs, exact reproduction, independently reconciled results and an evidence-linked finding reopened in the web app. [Evidence](../real-data-research.md).
- [RP03: Declared-session source preparation](tasks/RP03.md) — done, `d2b78eac`; explicit session capture preserves strict validation and captured-input retention.
- [RP04: Evaluation horizon and CAGR presentation](tasks/RP04.md) — done, `302ba60e`; retained UTC bounds and calendar duration make short-sample annualization explicit.
- [RP05: Retained dataset reuse](tasks/RP05.md) — done, `6d549542`; load older catalog pages or select and verify a known hash.
- [RP06: Settings and preparation custody](tasks/RP06.md) — done, `c838e3d0`; preserve the current backtest draft and captured retry across tabs/run URLs.
- [RP07: Retained dataset download](tasks/RP07.md) — done, `b959779a`; export validated original inputs for local research.
- [RP08: Original run result download](tasks/RP08.md) — done, `e8a6b709`; reuse the loaded canonical result for local analysis.
- [RP09: Strategy handoff custody](tasks/RP09.md) — done, `49da701a`; finish or clear publication/clone work before handing a version to backtest setup.
- [RP10: Missing-template recovery](tasks/RP10.md) — done, `f0e7d074`; preserve valid experiment choices when the linked template lookup fails.
- [RP11: Partial hypothesis-history recovery](tasks/RP11.md) — done, `32f40ee7`; retain verified exact links despite unrelated history errors.
- [RP12: Available run history](tasks/RP12.md) — done, `a050c710`; keep saved runs selectable while optional metrics load.
- [RP13: Isolated candidate reproduction](tasks/RP13.md) — done, `773314d2`; accept the existing null-review candidate preview without weakening built-in approval checks.
- [RP14: Backtest dialog navigation](tasks/RP14.md) — done, `0d022ecc`; preserve drafts and pending saves during same-tab strategy inspection.
- [RP15: CLI recovery evidence](tasks/RP15.md) — done, `e3d6512b`; preserve accepted receipts when journal persistence fails.
- [RP16: Automatic publication lineage](tasks/RP16.md) — done, `cc49f038`; accept valid server-assigned parents and exact publication retries.
- [RP17: Candidate default parameters](tasks/RP17.md) — done, `1502ab41`; decode normalized validation children without changing original inputs or hashes.
- [RP18: October multi-session pilot](tasks/RP18.md) — done; nine retained native runs, exact reproduction, independent accounting/provenance review and opened web findings passed. The seven conditional tasks stay deferred.
- [RP19: Final risk state](tasks/RP19.md) — done, `e6616fdc`; canonical results show exact native halt flags, limits and snapshot times without inferring halt history.
- [RP20: Production research authentication](tasks/RP20.md) — done, `7de497e9`; normal API startup uses the existing research resolver, with actual issued-credential and quota regressions.
- [RP21: Bounded volatility-filter study](tasks/RP21.md) — done; ten isolated trials, exact receipt recovery, independently audited results and reopened findings. Both variants lost money on test and whole-window cost runs; credential revoked.
- [RP22: Candidate decimal admission](tasks/RP22.md) — done, `b7116473`; additive SQL33 preserves known-program decimal normalization and exact raw-input receipts.
- [RP23: Cross-study findings client](tasks/RP23.md) — done, `8dc8724c`; typed comparisons accept null/omitted source while preserving canonical versioned evidence and supplied-source identity checks.
- [RP24: Single-run finding acknowledgements](tasks/RP24.md) — done, `f80ae2f3`; verify every returned source/citation and preserve uncertain drafts, including canonical and historical single-run findings.
- [RP25: Typed artifact reads](tasks/RP25.md) — done, `e39989c4`; authenticated reads preserve exact retained revisions, authorship, evidence and historical qualifications.
- [RP26: Saved research revision download](tasks/RP26.md) — done, `54349502`; download exact current/historical hypotheses, notes and findings with retained citations and authorship.
- [RP27: Complete canonical run reads](tasks/RP27.md) — done, `66af201d`; research credentials inspect full native results through shared validation while the backend preserves trusted SQL binding.
- [RP28: Frozen data reads for research](tasks/RP28.md) — done (`4b9c6428`); exact retained exports with complete content/hash verification in the typed client.
- [RP29: Original hypothesis reads](tasks/RP29.md) — done (`fa78b6a7`); reopen saved hypotheses and select their original immutable revisions through the typed client.
- [RP30: Revision acknowledgement custody](tasks/RP30.md) — done (`e4056c7d`); verify saved revision identity/content/evidence before clearing web drafts.
- [RP31: Creation acknowledgement custody](tasks/RP31.md) — done (`57ba86d0`); verify project/hypothesis/note/finding creations before leaving drafts or displaying saved success.
- [RP32: Project/archive acknowledgement custody](tasks/RP32.md) — done (`f84fa82b`); verify project patches and entry archive outcomes, preserving uncertain drafts until explicit reload.
## E13 — Whole-application architecture cleanup
- [CL22 — Own queue transports without deleting pending payloads](tasks/CL22.md)
- [CL23 — Reject retired backtest creation before persistence](tasks/CL23.md)
- [CL24 — Remove prototype dashboard from normal navigation](tasks/CL24.md)
- [CL25 — Share validated product response contracts](tasks/CL25.md)
- [CL26 — Replace private application imports with explicit shared modules](tasks/CL26.md)
- [CL27 — Initialize enabled ingestion handlers once per container](tasks/CL27.md)
- [CL28 — Compose research services with explicit collaborators](tasks/CL28.md)
- [CL29 — Share transactional experiment run and dispatch insertion](tasks/CL29.md)
- [CL30 — Separate research UI workflow state from rendering](tasks/CL30.md)
- [CL31 — Publish a stable strategy authoring contract](tasks/CL31.md)
- [CL32 — Separate paper safety enforcement from readiness projection](tasks/CL32.md)
- [CL33 — Isolate legacy repository writers from production capabilities](tasks/CL33.md)
- [CL34 — Normalize provider symbols and remove unused scaffolding](tasks/CL34.md)
- [CL35 — Make optional Python analytics composition honest and testable](tasks/CL35.md)

View file

@ -1,388 +0,0 @@
flowchart TD
%% Generated view of manifest.json. Solid edges: implementation; dotted: release only.
subgraph E1["E1: Immediate correctness and runtime containment"]
C01["C01: Correct native terminal valuation"]
C02["C02: Reject malformed native data and preserve milliseconds"]
C03["C03: Close the existing TypeScript fee-funding hole"]
C04["C04: Make partial runtime initialization recoverable"]
C06["C06: Contain legacy research/paper interference without a second runtime"]
end
subgraph E2["E2: Canonical Rust financial engine"]
F01["F01: Define the minimal financial contract and economic fixtures"]
F02["F02: Implement one owner-aware financial ledger"]
F04["F04: Enforce cash reservations and portfolio risk centrally"]
F05["F05: Unify matching and order lifecycle on the ledger"]
F06["F06: Implement deterministic replay once, with linear historical traversal"]
F07["F07: Expose bounded Rust step sessions through existing NAPI workers"]
F08["F08: Publish canonical metrics and versioned result projections"]
F09["F09: Return compact canonical replay projections"]
end
subgraph E3["E3: Point-in-time datasets and features"]
D01["D01: Introduce availability-aware dataset v2"]
D02["D02: Connect supported intraday storage to research datasets"]
D04["D04: Provide prefix-safe shared feature calculation (conditional)"]
end
subgraph E4["E4: TypeScript strategies and durable paper integration"]
S01["S01: Run deterministic TypeScript decisions on Rust sessions"]
S02["S02: Adapt one SMA strategy for the first canonical path"]
S03["S03: Adapt durable paper transactions to Rust financial reducers"]
S04["S04: Establish a verified paper feed and operator safety gate"]
S05["S05: Add a small composable multi-signal regime example"]
S06["S06: Retire duplicate simulator paths after cutover proof"]
end
subgraph E5["E5: Existing web backtest vertical slice"]
W01["W01: Make existing run controls and selection truthful"]
W02["W02: Expose result provenance and legacy correctness limitations"]
W03["W03: Separate save, submit and repeat-safe run creation"]
W04["W04: Verify the first research vertical slice in a browser"]
end
subgraph E6["E6: Research product, provenance and validation"]
R01["R01: Persist immutable strategy versions and parameter schemas"]
R02["R02: Deliver strategy catalog and version-aware backtest setup"]
R03["R03: Add projects, hypotheses and evidence-linked findings APIs"]
R04["R04: Deliver research workspace and save-findings flow"]
R05["R05: Freeze complete provenance and cut over durable canonical runs"]
R06["R06: Create immutable experiments and bounded sweep expansion"]
R07["R07: Deliver sweep configuration and comparable-result views"]
R08["R08: Add bounded chronological and reset-segment validation"]
R09["R09: Expose validation, cost and regime evidence in the workbench"]
R10["R10: Protect retained research evidence and artifact integrity"]
R11["R11: Select and reuse frozen datasets in the workbench"]
R12["R12: Reproduce an original run separately from rerunning current settings"]
end
subgraph E7["E7: Measured research throughput"]
P01["P01: Measure existing research paths before extending the benchmark"]
P03["P03: Reuse validated datasets within bounded native workers (conditional)"]
P04["P04: Schedule deterministic batches across a bounded worker pool"]
P05["P05: Separate result summaries from paged detail payloads (conditional)"]
P06["P06: Conditionally add a minimal Rust-executed strategy plan (conditional)"]
P07["P07: Profile representative canonical replay workloads"]
P08["P08: Reduce measured TypeScript strategy decision overhead (done)"]
end
subgraph E8["E8: Authorized, isolated AI research"]
A01["A01: Add research-only principals and durable job budgets"]
A02["A02: Isolate untrusted TypeScript strategy builds and decisions"]
A03["A03: Implement an evidence-linked AI research workflow client"]
A04["A04: Add human-reviewed promotion to paper deployment"]
end
subgraph E9["E9: Migration and operational safeguards"]
O01["O01: Serialize additive schema migrations safely"]
O02["O02: Expose truthful research and paper readiness diagnostics (done)"]
end
C04 --> C06
ADR002 --> F01
ADR003 --> F01
ADR004 --> F01
F01 --> F02
ADR002 --> F02
F02 --> F04
ADR002 --> F04
ADR003 --> F04
F04 --> F05
ADR003 --> F05
F06 -. release only .-> F05
F05 --> F06
D01 --> F06
P01 --> F06
ADR003 --> F06
F06 --> F07
C02 --> F07
ADR004 --> F07
F06 --> F08
F09 --> F08
ADR002 --> F08
ADR003 --> F08
F07 --> F09
ADR002 --> F09
ADR003 --> F09
ADR004 --> F09
ADR003 --> D01
D01 --> D02
S01 --> D04
P01 --> D04
F07 --> S01
ADR004 --> S01
ADR005 --> S01
S01 --> S02
S01 --> S03
C06 --> S03
ADR005 --> S03
S02 --> S04
S03 --> S04
S02 --> S05
F08 --> S05
R08 -. release only .-> S05
S03 --> S06
S04 --> S06
R05 --> S06
W01 --> W02
O01 --> W03
W01 --> W04
W02 --> W04
W03 --> W04
C06 --> W04
O01 --> R01
ADR006 --> R01
R01 --> R02
W03 --> R02
ADR006 --> R02
W04 -. release only .-> R02
R01 --> R03
R10 --> R03
ADR006 --> R03
R03 --> R04
W02 --> R04
ADR006 --> R04
W04 -. release only .-> R04
F08 --> R05
S02 --> R05
R01 --> R05
R10 --> R05
D01 --> R05
W03 --> R05
C06 --> R05
ADR006 --> R05
%% R06 component consumes accepted R05 retained-input slice 618fb9e; full R05 stays partial.
R01 --> R06
R10 --> R06
F08 --> R06
S02 --> R06
D01 --> R06
W03 --> R06
C06 --> R06
R12 --> R06
ADR006 --> R06
R06 --> R07
ADR006 --> R07
W04 -. release only .-> R07
R06 --> R08
ADR006 --> R08
R07 -. accepted functional component 46a4f13 .-> R09
R08 --> R09
ADR006 --> R09
S05 -. Regime comparison is enabled .-> R09
R01 --> R10
ADR006 --> R10
D01 --> R11
O01 --> R11
ADR003 --> R11
ADR006 --> R11
W04 -. release only .-> R11
%% R12 also requires R05's accepted retained-input component (618fb9e), not full cutover.
R01 --> R12
R10 --> R12
F08 --> R12
S02 --> R12
D01 --> R12
W03 --> R12
C06 --> R12
W04 --> R12
ADR006 --> R12
F07 --> P03
P01 --> P03
ADR004 --> P03
ADR008 --> P03
F07 --> P04
R06 --> P04
C06 --> P04
P01 --> P04
ADR008 --> P04
R06 --> P05
P01 --> P05
P04 --> P06
S01 --> P06
ADR008 --> P06
F07 --> P07
P01 --> P07
F09 -. compact comparisons only .-> P07
S02 --> P08
P07 --> P08
R06 --> A01
O01 --> A01
ADR007 --> A01
A01 --> A02
S01 --> A02
P01 --> A02
ADR007 --> A02
A02 --> A03
R08 --> A03
R03 --> A03
ADR007 --> A03
S04 --> A04
R09 --> A04
A01 --> A04
R01 --> A04
ADR007 --> A04
ADR005 --> A04
S04 --> O02
R03 -. save or link finding only .-> R09
classDef conditional stroke-dasharray: 5 5,fill:#fff3cd,color:#222
class D04,P03,P05,P06,P08,O02 conditional
%% Merged traceability only: C05 -> F01; F03 -> F02; D03 -> D01; P02 -> F06.
subgraph E10["E10: Cleanup and maintainability foundations"]
CL01["CL01: Replace permissive DI configuration tests with production-path assertions"]
CL02["CL02: Normalize database configuration once and enforce consistent service switches"]
CL03["CL03: Roll back failed shared-service startup and clear initialization timers"]
CL04["CL04: Provide one consistent research startup path and repair stale commands"]
CL05["CL05: Extract shared dataset and reporting logic behind a research library boundary"]
CL06["CL06: Use shared dataset response schemas and eligibility checks in the workbench"]
CL07["CL07: Share JSON transport handling across experiment and validation clients"]
CL08["CL08: Split backtest template, run and reproduction responsibilities behind the existing service"]
CL09["CL09: Separate strategy metadata, version inspection and publication UI"]
CL10["CL10: Separate experiment modes and make draft/submission state explicit"]
CL11["CL11: Separate backtest template loading, run monitoring and submission state"]
CL12["CL12: Simplify retired execution seams while preserving historical reads"]
CL13["CL13: Hide placeholder navigation while preserving useful product routes"]
end
CL01 --> CL02
D01 --> CL05
F08 --> CL05
R05 --> CL05
ADR001 --> CL05
ADR003 --> CL05
ADR004 --> CL05
CL05 --> CL06
CL05 --> CL08
ADR005 --> CL08
ADR006 --> CL08
CL08 --> CL12
ADR005 --> CL12
%% CL02 and CL03 also serialize on the di-container file lock; no artificial dependency edge.
subgraph E11["E11: Orchestrator and engine cleanup"]
CL14["CL14: Require canonical capabilities in durable research contracts"]
CL15["CL15: Retire abandoned Rust architecture scaffolding"]
CL16["CL16: Give orchestrator composition an explicit shutdown owner"]
CL17["CL17: Separate historical reads from unused storage writes"]
CL18["CL18: Share strict native parsing and financial view projection"]
CL19["CL19: Share pure strategy bookkeeping and event ordering"]
CL20["CL20: Return validated retained results from the worker supervisor"]
CL21["CL21: Extract private deterministic replay preparation when needed"]
end
CL14 --> CL17
CL14 --> CL20
CL15 --> CL18
class CL21 conditional
%% CL14/CL16 serialize container.ts changes; no artificial dependency.
subgraph E12["E12: Real-data research workflow"]
RP01["RP01: Scoped stored-source inspection"]
RP02["RP02: Retained real-data research pilot"]
RP03["RP03: Declared-session source preparation"]
RP04["RP04: Evaluation horizon and CAGR presentation"]
end
CL05 --> RP01
CL06 --> RP01
CL17 --> RP01
CL02 --> RP02
CL03 --> RP02
R05 --> RP02
R08 --> RP02
R12 --> RP02
%% RP01 supports manual inspection but does not block offline pilot preparation.
%% RP02 execution retains the existing human strategy-version approval gate.
RP01 --> RP03
D01 --> RP03
RP02 --> RP04
RP03 --> RP05
R11 --> RP05
RP03 --> RP06
RP05 --> RP07
R05 --> RP07
RP07 --> RP08
R05 --> RP08
R02 --> RP09
A02 --> RP09
R07 --> RP10
R04 --> RP11
W01 --> RP12
R12 --> RP13
A02 --> RP13
R02 --> RP14
W03 --> RP14
A03 --> RP15
A03 --> RP16
R01 --> RP16
A02 --> RP17
R08 --> RP17
A01 --> RP20
A03 --> RP20
RP20 --> RP21
A02 --> RP21
A03 --> RP21
RP03 --> RP21
R08 --> RP21
R09 --> RP21
A02 --> RP22
RP17 --> RP22
RP22 --> RP21
A03 --> RP23
RP21 --> RP23
R04 --> RP24
R09 --> RP24
RP23 --> RP24
A03 --> RP25
RP23 --> RP25
R04 --> RP26
RP08 --> RP26
RP25 --> RP26
A03 --> RP27
F08 --> RP27
RP25 --> RP27
A03 --> RP28
RP07 --> RP28
RP27 --> RP28
A03 --> RP29
R03 --> RP29
RP25 --> RP29
R04 --> RP30
RP24 --> RP30
R04 --> RP31
RP24 --> RP31
RP30 --> RP31
R04 --> RP32
RP30 --> RP32
subgraph E13["E13: Whole-application architecture cleanup"]
CL22["CL22: Own queue transports without deleting pending payloads"]
CL23["CL23: Reject retired backtest creation before persistence"]
CL24["CL24: Remove prototype dashboard from normal navigation"]
CL25["CL25: Share validated product response contracts"]
CL26["CL26: Replace private application imports with explicit shared modules"]
CL27["CL27: Initialize enabled ingestion handlers once per container"]
CL28["CL28: Compose research services with explicit collaborators"]
CL29["CL29: Share transactional experiment run and dispatch insertion"]
CL30["CL30: Separate research UI workflow state from rendering"]
CL31["CL31: Publish a stable strategy authoring contract"]
CL32["CL32: Separate paper safety enforcement from readiness projection"]
CL33["CL33: Isolate legacy repository writers from production capabilities"]
CL34["CL34: Normalize provider symbols and remove unused scaffolding"]
CL35["CL35: Make optional Python analytics composition honest and testable"]
end
CL26 --> CL28
CL28 --> CL29
CL25 --> CL30
CL26 --> CL31

View file

@ -1,290 +0,0 @@
# Revalidated audit findings
The original findings below describe their stated historical baseline. For the current cleanup extension, see [Cleanup audit 2026-10-26](#cleanup-audit-2026-10-26); completed financial migration findings must not be mistaken for newly reopened defects.
Baseline: `b7aeca4`, inspected 2026-10-22. No standalone structured audit/backlog was found in existing docs; this matrix reconciles the supplied audit concerns against current code. Existing informal docs remain historical context, not a second task tracker.
**Verified** means the cited implementation establishes the behavior or gap. **Likely** would mean an inference not yet reproduced; none is promoted to a confirmed defect here. **Needs Investigation** marks runtime/coverage questions that source alone cannot certify. No full application test suite or new performance benchmark was run during this planning-only task. Numeric acceptance examples are new test requirements, not fabricated passing tests.
## FIN-01 — Critical / Verified
Both execution paths can act on a completed bar and fill against its current close; this is not a defensible default bar-close policy.
Evidence: [apps/stock/engine/src/backtest/engine.rs:249](../../../apps/stock/engine/src/backtest/engine.rs#L249); [apps/stock/orchestrator/src/services/ExecutionService.ts:224](../../../apps/stock/orchestrator/src/services/ExecutionService.ts#L224).
Disposition: [F01](tasks/F01.md), [F05](tasks/F05.md), [F06](tasks/F06.md), [W02](tasks/W02.md).
## FIN-02 — Critical / Verified
Native forced liquidation occurs after the last equity mark; reported final value reads that earlier mark, omitting terminal costs.
Evidence: [apps/stock/engine/src/backtest/engine.rs:135](../../../apps/stock/engine/src/backtest/engine.rs#L135); [apps/stock/engine/src/backtest/simple_results.rs:308](../../../apps/stock/engine/src/backtest/simple_results.rs#L308).
Disposition: [C01](tasks/C01.md), [F01](tasks/F01.md), [F02](tasks/F02.md).
## FIN-03 — Critical / Verified
Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash.
Evidence: [apps/stock/engine/src/risk/mod.rs:89](../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../apps/stock/orchestrator/src/execution/model.ts#L234).
Disposition: [C03](tasks/C03.md), [F01](tasks/F01.md), [F02](tasks/F02.md), [F04](tasks/F04.md).
## FIN-04 — Critical / Verified
Native fills notify every strategy. TypeScript realized P&L uses aggregate symbol cost basis, not per-strategy cost basis.
Evidence: [apps/stock/engine/src/backtest/engine.rs:489](../../../apps/stock/engine/src/backtest/engine.rs#L489); [apps/stock/orchestrator/src/execution/model.ts:108](../../../apps/stock/orchestrator/src/execution/model.ts#L108).
Disposition: [F01](tasks/F01.md), [F02](tasks/F02.md), [S02](tasks/S02.md), [S05](tasks/S05.md).
## FIN-05 — Critical / Verified
Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks.
Evidence: [apps/stock/engine/src/api/backtest.rs:63](../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114).
Disposition: [F01](tasks/F01.md), [F02](tasks/F02.md), [F05](tasks/F05.md), [F07](tasks/F07.md), [S01](tasks/S01.md), [S03](tasks/S03.md), [S06](tasks/S06.md), [R05](tasks/R05.md), [P01](tasks/P01.md), [P06](tasks/P06.md).
## FIN-06 — High / Verified
Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure.
Evidence: [apps/stock/engine/src/backtest/engine.rs:374](../../../apps/stock/engine/src/backtest/engine.rs#L374); [apps/stock/engine/src/backtest/engine.rs:414](../../../apps/stock/engine/src/backtest/engine.rs#L414).
Disposition: [F01](tasks/F01.md), [F04](tasks/F04.md), [F05](tasks/F05.md), [S04](tasks/S04.md).
## FIN-07 — High / Verified
Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics.
Evidence: [apps/stock/engine/src/backtest/simple_results.rs:374](../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../apps/stock/engine/src/backtest/simple_results.rs#L542).
Disposition: [F08](tasks/F08.md), [W02](tasks/W02.md), [R07](tasks/R07.md), [R08](tasks/R08.md).
## DAT-01 — Critical / Verified
Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times.
Evidence: [libs/core/types/src/historical-data.ts:90](../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../apps/stock/orchestrator/src/services/StorageService.ts#L177).
Disposition: [F06](tasks/F06.md), [D01](tasks/D01.md), [R08](tasks/R08.md), [R11](tasks/R11.md).
## DAT-02 — High / Verified
Native input parsing silently discards malformed rows and truncates timestamps to seconds.
Evidence: [apps/stock/engine/src/api/backtest.rs:217](../../../apps/stock/engine/src/api/backtest.rs#L217); [apps/stock/engine/src/api/backtest.rs:290](../../../apps/stock/engine/src/api/backtest.rs#L290).
Disposition: [C02](tasks/C02.md).
## DAT-03 — High / Verified
Missing VWAP is replaced with typical price; reported volume and provider-adjusted prices are not a complete corporate-action execution model.
Evidence: [apps/stock/orchestrator/src/data/historical-dataset.ts:230](../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L230); [libs/core/types/src/historical-data.ts:98](../../../libs/core/types/src/historical-data.ts#L98).
Disposition: [D01](tasks/D01.md).
## DAT-04 — High / Verified
Historical storage selects QuestDB or daily MongoDB; the Mongo path explicitly rejects intraday requests. Ingestion-to-research routing requires an executable provider/interval capability check.
Evidence: [apps/stock/orchestrator/src/services/StorageService.ts:287](../../../apps/stock/orchestrator/src/services/StorageService.ts#L287); [apps/stock/orchestrator/src/services/StorageService.ts:299](../../../apps/stock/orchestrator/src/services/StorageService.ts#L299).
Disposition: [D02](tasks/D02.md).
## RUN-01 — Critical / Verified
TypeScript research preparation calls the shared mode manager, which shuts down the current mode, so a research job can interfere with paper runtime.
Evidence: [apps/stock/orchestrator/src/container.ts:101](../../../apps/stock/orchestrator/src/container.ts#L101); [apps/stock/orchestrator/src/core/ModeManager.ts:47](../../../apps/stock/orchestrator/src/core/ModeManager.ts#L47).
Disposition: [C06](tasks/C06.md).
## RUN-02 — High / Verified
Partial initialization can allocate services before isInitialized becomes true; shutdown exits early on that failure path.
Evidence: [apps/stock/orchestrator/src/core/ModeManager.ts:55](../../../apps/stock/orchestrator/src/core/ModeManager.ts#L55); [apps/stock/orchestrator/src/core/ModeManager.ts:157](../../../apps/stock/orchestrator/src/core/ModeManager.ts#L157).
Disposition: [C04](tasks/C04.md).
## KEEP-01 — High / Verified
Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone.
Evidence: [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151).
Disposition: [F01](tasks/F01.md), [C06](tasks/C06.md), [F02](tasks/F02.md), [F05](tasks/F05.md), [S01](tasks/S01.md), [S03](tasks/S03.md), [S06](tasks/S06.md), [A04](tasks/A04.md).
## KEEP-02 — High / Verified
Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine.
Evidence: [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
Disposition: [F07](tasks/F07.md), [D01](tasks/D01.md), [D04](tasks/D04.md), [W04](tasks/W04.md), [R05](tasks/R05.md), [R06](tasks/R06.md), [R11](tasks/R11.md), [R12](tasks/R12.md), [P01](tasks/P01.md), [P03](tasks/P03.md), [P04](tasks/P04.md), [O02](tasks/O02.md).
## STR-01 — High / Verified
Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering.
Evidence: [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315).
Disposition: [F02](tasks/F02.md), [D04](tasks/D04.md), [S01](tasks/S01.md), [S02](tasks/S02.md), [S05](tasks/S05.md), [S06](tasks/S06.md), [R01](tasks/R01.md), [R02](tasks/R02.md), [A02](tasks/A02.md).
## WEB-01 — High / Verified
The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders.
Evidence: [apps/stock/web-app/src/app/App.tsx:24](../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
Disposition: [W01](tasks/W01.md), [W03](tasks/W03.md), [W04](tasks/W04.md), [R01](tasks/R01.md), [R02](tasks/R02.md), [R03](tasks/R03.md), [R04](tasks/R04.md), [R06](tasks/R06.md), [R07](tasks/R07.md), [R09](tasks/R09.md), [P05](tasks/P05.md), [A01](tasks/A01.md).
## WEB-02 — High / Verified
Detail exposes native-unsupported pause/resume controls, omits cancel wiring, and overlapping polling/selection can apply stale responses.
Evidence: [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:379](../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L379); [apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts:160](../../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts#L160).
Disposition: [W01](tasks/W01.md), [W04](tasks/W04.md), [O02](tasks/O02.md).
## WEB-03 — High / Verified
Definition creation auto-starts by default and catches submission failure; run creation has no client submission key. Re-run uses current definition rather than immutable original input.
Evidence: [apps/stock/web-api/src/services/backtest-v2.service.ts:105](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L105); [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:173](../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L173).
Disposition: [W03](tasks/W03.md), [R12](tasks/R12.md).
## WEB-04 — High / Verified
Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields.
Evidence: [libs/core/types/src/backtest-run.ts:4](../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
Disposition: [F08](tasks/F08.md), [W02](tasks/W02.md), [R01](tasks/R01.md), [R03](tasks/R03.md), [R04](tasks/R04.md), [R05](tasks/R05.md), [R06](tasks/R06.md), [R07](tasks/R07.md), [R10](tasks/R10.md), [R11](tasks/R11.md), [R12](tasks/R12.md), [A03](tasks/A03.md).
## WEB-05 — High / Verified
SQL deletion cascades from definitions to runs/results; evidence retention must be defined before research findings reference those results.
Evidence: [database/postgres/init/08-create-runs-table.sql:13](../../../database/postgres/init/08-create-runs-table.sql#L13); [database/postgres/init/06-create-backtest-tables.sql:25](../../../database/postgres/init/06-create-backtest-tables.sql#L25).
Disposition: [R03](tasks/R03.md), [R10](tasks/R10.md).
## OPS-01 — High / Verified
Migration runner uses an explicit safe allowlist; adding SQL alone will not run it. Concurrent migration admission lacks an advisory lock.
Evidence: [apps/stock/web-api/src/migrations/migration-runner.ts:42](../../../apps/stock/web-api/src/migrations/migration-runner.ts#L42); [apps/stock/web-api/src/migrations/migration-runner.ts:57](../../../apps/stock/web-api/src/migrations/migration-runner.ts#L57).
Disposition: [O01](tasks/O01.md).
## PER-01 — Medium / Verified
EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements.
Evidence: [apps/stock/engine/src/backtest/mod.rs:138](../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../apps/stock/engine/src/api/backtest.rs#L194).
Disposition: [F06](tasks/F06.md), [F07](tasks/F07.md), [P01](tasks/P01.md), [P03](tasks/P03.md), [P04](tasks/P04.md), [P05](tasks/P05.md), [P06](tasks/P06.md).
## AI-01 — High / Verified
Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary.
Evidence: [libs/core/di/src/http/security.ts:4](../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../libs/core/di/src/http/security.ts#L144).
Disposition: [A01](tasks/A01.md), [A02](tasks/A02.md), [A03](tasks/A03.md), [A04](tasks/A04.md).
## RES-01 — High / Verified
Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence.
Evidence: [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168).
Disposition: [D04](tasks/D04.md), [S05](tasks/S05.md), [R08](tasks/R08.md), [R09](tasks/R09.md), [A03](tasks/A03.md).
## OPS-02 — High / Needs Investigation
Paper/live operational readiness is not demonstrated end-to-end. Live is deliberately disabled; preserve that gate until feed, reconciliation and broker-specific recovery are verified.
Evidence: [apps/stock/orchestrator/src/core/ModeManager.ts:33](../../../apps/stock/orchestrator/src/core/ModeManager.ts#L33); [apps/stock/orchestrator/src/container.ts:152](../../../apps/stock/orchestrator/src/container.ts#L152).
Disposition: [S04](tasks/S04.md), [A04](tasks/A04.md), [O02](tasks/O02.md).
## Corrections to over-broad audit conclusions
- The first web workflow is not missing: real list/detail/routes, transactional dispatch and committed-state websocket updates exist. W01–W04 repair and verify it.
- Durable recovery and frozen data are implemented, not planned placeholders. Preserve them through S03; do not replace them for language uniformity.
- Native callback support is explicitly unavailable; NAPI types alone do not imply TS strategies already run in Rust replay.
- Future/native/experimental strategy files and Python research routines are not project-gated runtime capabilities. Do not enable them simply because names appear in a dropdown.
- Provider-adjusted data is not automatically executable corporate-action accounting. Hashing a dataset does not establish point-in-time correctness.
- No runtime evidence here establishes real broker reliability. Live-disabled guards remain intact.
- Exact hardware throughput, storage hot spots, memory limits and sandbox availability require P01/A02 measurements, not architectural confidence.
- Preservation rules in [cleanup audit](../../cleanup-audit.md) remain: reviewed calculations, restored helpers and useful research prototypes are not disposable dead code.
## Cleanup audit 2026-10-26
Baseline: `fbf2eb9e`. The read-only audit passed `bun run typecheck`, `bun run lint:check`, and 39 focused tests / 384 assertions across canonical SMA, strategy-runtime, canonical-durable-runner, QuestDB configuration and chart lifecycle suites. It did not rerun the complete PostgreSQL/browser suites or performance measurements. The planning stories below do not claim additional implementation or test completion.
### CL-F01 — High / Verified — Configuration precedence and field loss
A no-connection probe supplied enabled PostgreSQL/MongoDB/cache configuration and explicitly disabled those services through builder options. The resolved configurations stayed enabled; QuestDB's disable option behaved differently. PostgreSQL SSL/pool/timeout fields also exist in the core schema but are omitted by the DI schema/registration path.
Evidence: [builder precedence](../../../libs/core/di/src/container/builder.ts#L88), [core PostgreSQL schema](../../../libs/core/config/src/schemas/database.schema.ts#L4), [DI PostgreSQL schema](../../../libs/core/di/src/config/schemas/postgres.schema.ts#L3), [registration](../../../libs/core/di/src/registrations/database.registration.ts#L43). Story: [CL02](tasks/CL02.md).
### CL-F02 — High / Verified — Partial shared startup retains resources
An isolated cache-success/mongo-failure probe recorded cache connection and startup rejection without cache disconnection. Shared initialization uses Promise.all without rollback; timeout timers are not cleared on settled initialization. This differs from C04's completed ModeManager-specific recovery scope.
Evidence: [shared lifecycle](../../../libs/core/di/src/utils/lifecycle.ts#L24), [timeout creation](../../../libs/core/di/src/utils/lifecycle.ts#L97), [builder startup](../../../libs/core/di/src/container/builder.ts#L74). Story: [CL03](tasks/CL03.md).
### CL-F03 — High / Verified — Older infrastructure tests can pass without proving production behavior
DI success tests accept any exception as a passing result and replace production normalization with a module-local implementation. The older QuestDB client suite exercises a SimpleQuestDBClient defined in the test file; it is not production client transport coverage. Existing newer real-path tests remain valuable.
Evidence: [permissive assertions](../../../libs/core/di/test/container-builder.test.ts#L114), [test client](../../../libs/data/questdb/test/questdb.test.ts#L9), [instantiation](../../../libs/data/questdb/test/questdb.test.ts#L121). Story: [CL01](tasks/CL01.md). CL02 extends real wire-configuration coverage; this finding is not authority for an unrelated test-suite rewrite.
### CL-F04 — High / Verified — Shared research logic is imported from application internals
The web API imports orchestrator dataset validation, reporting and host build/sandbox helpers through source-relative paths. Reusable pure domain code and runtime integration are mixed in the import boundary. Only the pure subset should move; runtime adapters retain their process responsibilities.
Evidence: [admission imports](../../../apps/stock/web-api/src/services/canonical-research.service.ts#L31), [report import](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L37), [dataset implementation](../../../apps/stock/orchestrator/src/data/historical-dataset-v2.ts#L1). Story: [CL05](tasks/CL05.md).
### CL-F05 — Medium / Verified — Dataset response structures are maintained independently
The browser backtest client contains a large manifest/preparation schema overlapping backend dataset structures and workbench eligibility checks. Shared structures can be consolidated while full content/hash verification remains server-owned.
Evidence: [browser manifest](../../../apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts#L113), [dataset metadata](../../../apps/stock/orchestrator/src/data/historical-dataset-v2.ts#L34), [eligibility](../../../apps/stock/web-api/src/services/canonical-research.service.ts#L51). Story: [CL06](tasks/CL06.md).
### CL-F06 — Medium / Verified — Repeated experiment-client transport plumbing
Experiment and durable validation clients separately implement fetch, abort handling, JSON parsing, expected-status checks and domain-error wrapping. A small common transport layer can remove repetition while domain parsers and uncertain-acceptance rules remain explicit.
Evidence: [experiments](../../../apps/stock/web-app/src/features/experiments/services/experimentApi.ts#L44), [validation](../../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts#L29). Story: [CL07](tasks/CL07.md).
### CL-F07 — Medium / Verified — Application modules combine independent lifetimes
At this baseline BacktestServiceV2 is 1,071 lines, StrategyDetailPage 796, ExperimentEditor 623, BacktestDetailPageV2 645 and useBacktestV2 571. The finding is mixed responsibility/state ownership, not a line-count rule: template operations, run admission, reproduction, version publication, preview ownership and selected-run monitoring have different lifetimes.
Evidence: [backtest service](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L167), [strategy detail](../../../apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx#L20), [experiment editor](../../../apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx#L49), [backtest hook](../../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts#L34). Stories: [CL08](tasks/CL08.md), [CL09](tasks/CL09.md), [CL10](tasks/CL10.md), [CL11](tasks/CL11.md).
### CL-F08 — Medium / Verified — Developer commands are inconsistent or stale
Root db:setup-ib, db:init and proxy commands point at absent files. docker:start omits MongoDB while infra:up includes it. These are command/configuration defects, not evidence that missing setup capabilities should be reimplemented from scratch.
Evidence: [root commands](../../../package.json#L55), [Docker helper](../../../scripts/docker.sh#L93). Story: [CL04](tasks/CL04.md).
### CL-F09 — Medium / Verified — Retired execution seams remain in current control flow
Current admission rejects non-catalog execution, but later retains a legacy snapshot fallback. The runner retains an explicit retired entrypoint, and the native wrapper exposes old and canonical exports together. Their presence is verified; unused/deletable status is not inferred. Historical readers, artifacts and useful old algorithms must survive.
Evidence: [canonical guard](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L461), [fallback](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L486), [retired entry](../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L70), [native exports](../../../apps/stock/engine/index.mjs#L28). Story: [CL12](tasks/CL12.md), limited to proven control-flow cleanup and boundary checks.
### CL-F10 — Low / Verified — Primary navigation advertises placeholder pages
Portfolio, Analytics and Settings appear in navigation while their routes only render Coming Soon. Existing run/experiment analytics are separate working capabilities and must remain accessible.
Evidence: [navigation](../../../apps/stock/web-app/src/lib/constants.ts#L32), [placeholder routes](../../../apps/stock/web-app/src/app/App.tsx#L34). Story: [CL13](tasks/CL13.md).

File diff suppressed because it is too large Load diff

View file

@ -1,72 +0,0 @@
# A01 — Add research-only principals and durable job budgets
Parent epic: E8. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Backend security/durable scheduling.
Scheduling source of truth: [manifest entry A01](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **AI-01 — Verified:** Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary. [libs/core/di/src/http/security.ts:4](../../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../../libs/core/di/src/http/security.ts#L144).
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
## Intended behavior and implementation scope
Extend the small existing auth boundary with stable owner/agent identities and research-scoped permissions. Enforce per-agent concurrent-job/trial/time/resource budgets at admission and execution; record actor and audit events. Do not reinstate global historical data truncation limits.
Measurable benefit: Allows autonomous research without autonomous brokerage control.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- libs/core/di/src/http/security.ts
- apps/stock/web-api/src/routes/
- apps/stock/web-api/src/services/ (admission)
- apps/stock/orchestrator/src/backtest/BacktestRunner.ts
Write locks: auth-contract, experiment-api. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [R06](R06.md), [O01](O01.md) integrated.
Architecture decisions: ADR-007. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- AI research token can register hypotheses and submit authorized experiments but cannot call paper/live administration or mutate financial constraints.
- Budget reservations are transactional and released on failure/cancellation/restart; retries do not double-charge.
- User-configured budgets and rejections are visible; operator's large trusted datasets remain supported.
## Mandatory tests
- research_token_live_denied, budget_concurrent_admission, budget_recovery, actor_audit.
- Existing security/browser-session/CSRF tests; do not break current operator workflow.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: Research-scoped credential routes/claims; typed403/429 with budget diagnostics on same experiment APIs.
- Backend/data dependencies: Minimal principal/budget/audit persistence; existing local owner maps to one principal.
- Loading/error/empty behavior: API identifies quota wait vs invalid request; UI can show admission error without losing experiment draft.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Accepted completion — 2026-10-24
Operator-provisioned hashed research credentials, scoped write grants, explicit AI authorship, SQL-budgeted admissions/retries/validation phases and bounded attempts/deadlines are implemented. Shared historical reads remain permitted; paper/live and credential administration reject research principals. Browser provisioning/usage/revocation, receipt recovery and stale response fencing are verified.
Independent review and final repository/native/PostgreSQL/browser gates pass. Exact results and source identities: manifest `thirty_seventh_wave_validation` and the [handoff](../../ROADMAP.md#thirty-seventh-wave-handoff--2026-10-24). No real account migration or paper/live activation occurred.

View file

@ -1,73 +0,0 @@
# A02 — Isolate untrusted TypeScript strategy builds and decisions
Parent epic: E8. Priority/severity: P1 / High. Relative complexity: L. Recommended specialization: Process isolation/security.
Scheduling source of truth: [manifest entry A02](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **AI-01 — Verified:** Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary. [libs/core/di/src/http/security.ts:4](../../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../../libs/core/di/src/http/security.ts#L144).
- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315).
## Intended behavior and implementation scope
Compile/import AI artifacts only in an OS-restricted process/container without network, secrets, DB, broker access or full future dataset. Engine supervisor sends prefix-only context and receives intents through a small IPC protocol. Apply wall/CPU/memory limits; pin artifact dependencies. node:vm alone is not a security boundary.
Measurable benefit: Makes arbitrary AI code execution a contained research capability.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- apps/stock/orchestrator/src/backtest/ (isolated strategy host)
- apps/stock/web-api/src/services/ (artifact registration)
- scripts/ (sandbox launch profile)
Write locks: sandbox-contract, worker-protocol. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [A01](A01.md), [S01](S01.md), [P01](P01.md) integrated.
Architecture decisions: ADR-007. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Malicious imports, filesystem/network/env probing and infinite loops fail safely without affecting the API/paper process.
- Candidate cannot access future bars through files/native handles; only the supervisor owns financial engine and data.
- Trusted reviewed artifact fast path is an explicit human promotion, never self-selected by code.
## Mandatory tests
- deny_network_secret_read_child_spawn, infinite_loop_kill, malformed_intent, future_context_exfiltration, worker_cleanup.
- Sandbox availability check fails closed; benchmark IPC overhead separately from trusted NAPI path.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Native runtime/process privileges can invalidate the sandbox; independent security review required.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Pinned implementation contract — 2026-10-24
Preserve built-in request bytes and the canonical Rust engine. Add an origin-discriminated candidate branch retaining nullable review only for candidates, server-bound baselineVersionId, generic target selection and exact sandbox execution descriptor. Package execution declares fixed warmupBars. Candidate overrides change version/derived owner identities and parameters only; the original frozen template financial grant remains exact. Explicit operator own-candidate grants authorize owned unreviewed versions in isolation. Revocation blocks new work; ordinary approval never selects a trusted research import.
Use the existing durable runner and shared async replay lifecycle. One isolated container receives only published observations/context and returns strictly validated owner/barrier/sequence/decision intents; Rust owns every economic result. The Linux x64 local scratch image contains pinned installed Bun, required runtime libraries, trusted host and a small independent guardian; no external downloads or host/data/secret mounts. Fixed profile:512MiB,1CPU,64PIDs,16MiB tmp,300s wall,8MiB protocol frame and64KiB captured stderr. Shorter agent attempt deadline wins. Missing enforcement fails closed. Test process/namespace/network/filesystem denial, resource exhaustion, malformed/forged messages, cancellation and supervisor death through actual container removal.
A small same-sandbox CLI may transpile self-contained TypeScript without importing it or installing dependencies; no remote build service. Candidate code is not automatically deterministic or unfitted: retain an unverified-candidate chronology policy, author-declared warmup and actual reproduction comparison. Preserve all built-in chronology bytes. A04's separate human promotion receipt controls trusted paper imports.
Root owns browser/response integration; A02 owns SQL29 and worker/contracts. Runtime registry/bootstrap merges are serialized by root. Full acceptance still requires native/SQL/browser and independent isolation review; feasibility probes alone do not close A02.
## Accepted implementation — 2026-10-24
Completed and independently reviewed. The [final wave record](../../ROADMAP.md#thirty-eighth-wave-final-acceptance--2026-10-24) and canonical manifest contain the implementation commit, actual regression/SQL/browser proofs, measurement identities and remaining limitations. Completion does not activate real trading or waive conditional architecture gates.

View file

@ -1,67 +0,0 @@
# A03 — Implement an evidence-linked AI research workflow client
Parent epic: E8. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: AI research integration.
Scheduling source of truth: [manifest entry A03](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **AI-01 — Verified:** Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary. [libs/core/di/src/http/security.ts:4](../../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../../libs/core/di/src/http/security.ts#L144).
- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168).
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
## Intended behavior and implementation scope
Implement a typed authorized research API client/example using backend R03/R06/R08 contracts, independent of whether project UI is complete. Propose hypothesis, register candidate, preview/submit bounded experiments, inspect all outcomes, request validation and save run-linked findings. No new AI service/framework or mandatory vendor/model SDK.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- apps/stock/web-api/src/routes/ (research API contracts)
- scripts/ (research client example)
- test/integration/ (AI research flow)
Write locks: ai-workflow-client. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [A02](A02.md), [R08](R08.md), [R03](R03.md) integrated.
Architecture decisions: ADR-007. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Every AI finding links immutable run/artifact IDs and distinguishes proposed hypotheses from validated evidence.
- An execution failure is returned as a diagnostic, not filtered out of candidate history.
- Client cannot promote itself to paper/live or alter operator account risk policy.
## Mandatory tests
- ai_hypothesis_to_validated_finding_contract, bounded_search_rejected, failed_trial_reported, evidence_mismatch_rejected.
- Replay the workflow with deterministic fake model suggestions; no paid model call required for CI.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: Reuse projects/hypotheses/versions/experiments/artifacts endpoints and diagnostics; publish typed request/response examples.
- Backend/data dependencies: No second task store or AI-only results database.
- Loading/error/empty behavior: Client handles202 polling,429 budgets,409 conflicts and terminal failures; UI shows AI authorship in existing workspace.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Accepted implementation — 2026-10-24
Completed and independently reviewed. The [final wave record](../../ROADMAP.md#thirty-eighth-wave-final-acceptance--2026-10-24) and canonical manifest contain the implementation commit, actual regression/SQL/browser proofs, measurement identities and remaining limitations. Completion does not activate real trading or waive conditional architecture gates.

View file

@ -1,68 +0,0 @@
# A04 — Add human-reviewed promotion to paper deployment
Parent epic: E8. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Full-stack paper trading integration.
Scheduling source of truth: [manifest entry A04](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **OPS-02 — Needs Investigation:** Paper/live operational readiness is not demonstrated end-to-end. Live is deliberately disabled; preserve that gate until feed, reconciliation and broker-specific recovery are verified. [apps/stock/orchestrator/src/core/ModeManager.ts:33](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L33); [apps/stock/orchestrator/src/container.ts:152](../../../../apps/stock/orchestrator/src/container.ts#L152).
- **AI-01 — Verified:** Existing small operator auth has read/admin/service roles, not a research-only principal or arbitrary-code isolation boundary. [libs/core/di/src/http/security.ts:4](../../../../libs/core/di/src/http/security.ts#L4); [libs/core/di/src/http/security.ts:144](../../../../libs/core/di/src/http/security.ts#L144).
- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151).
## Intended behavior and implementation scope
Human-only paper deployment of a frozen version requires S04 readiness, research-only permission separation and explicit evidence. It must work for human-authored as well as AI-originated strategies; the A03 AI client is not a prerequisite. Reuse version/evidence APIs and add a deployment record only when this flow is implemented.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- apps/stock/web-app/src/features/strategies/
- apps/stock/web-api/src/routes/ (paper promotion)
- apps/stock/orchestrator/src/paper/PaperTradingManager.ts
- database/postgres/init/ (optional deployment table)
Write locks: paper-runtime, web-strategies, sql-migrations. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [S04](S04.md), [R09](R09.md), [A01](A01.md), [R01](R01.md) integrated.
Architecture decisions: ADR-007, ADR-005. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Research-only token cannot create/activate a deployment; operator must review OOS/cost evidence and limitations.
- Only paper deployment is offered; live remains explicitly unavailable.
- Promotion never overwrites existing account capital/checkpoints or silently upgrades strategy state.
## Mandatory tests
- human_only_promotion, immutable_deployment_version, incompatible_checkpoint_block, no_live_option.
- Browser AI candidate -> evidence review -> paper status workflow.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: POST paper-deployments and explicit activate/halt operations for operator only; read-only history for research clients.
- Backend/data dependencies: Optional deployments table with version/account/evidence FKs, existing durable paper state.
- Loading/error/empty behavior: Not-ready reasons, approval pending, active/halted/failed; no cosmetic success before backend confirmation.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Accepted implementation — 2026-10-24
Completed and independently reviewed. The [final wave record](../../ROADMAP.md#thirty-eighth-wave-final-acceptance--2026-10-24) and canonical manifest contain the implementation commit, actual regression/SQL/browser proofs, measurement identities and remaining limitations. Completion does not activate real trading or waive conditional architecture gates.

View file

@ -1,56 +0,0 @@
# C01 — Correct native terminal valuation
Parent epic: E1. Priority/severity: P0 / Critical. Relative complexity: S. Recommended specialization: Rust financial correctness.
Scheduling source of truth: [manifest entry C01](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-02 — Verified:** Native forced liquidation occurs after the last equity mark; reported final value reads that earlier mark, omitting terminal costs. [apps/stock/engine/src/backtest/engine.rs:135](../../../../apps/stock/engine/src/backtest/engine.rs#L135); [apps/stock/engine/src/backtest/simple_results.rs:308](../../../../apps/stock/engine/src/backtest/simple_results.rs#L308).
## Intended behavior and implementation scope
Correct the current native forced-liquidation path only: mark the final account after all closing fills and update the existing terminal-time equity sample instead of appending a duplicate timestamp. Preserve current matching, sizing, liquidation and fee policies. Do not implement the new engine here.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/engine/src/backtest/engine.rs
- apps/stock/engine/src/backtest/simple_results.rs
- test/integration/native-terminal-equity.test.ts (new, only if public API can exercise the same fixture)
Write locks: legacy-native-finance. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md.
## Dependencies and blockers
No code prerequisite. Global execution approval and write-lock acquisition still required.
No additional economic-policy approval is needed for this narrowly scoped task.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- A deterministic test strategy/direct internal fixture buys exactly1 share at4 from cash10, with1% entry/exit fees and zero slippage: final cash/equity/finalValue=9.92 and total fees=0.08.
- Positions eligible for liquidation in these fixtures are flat; every closing fill is included once, including multiple symbols. Preserve the existing micro-position threshold; any retained residual still contributes its marked value to final equity.
- No-position/zero-fee behavior remains correct; there is exactly one final-time equity sample.
## Mandatory tests
- Inline Rust fixtures: terminal_fee_equity, terminal_no_positions, terminal_zero_fee, terminal_multiple_symbols, terminal_timestamp_unique.
- cargo test -p engine --lib --offline; build current addon with bun run --cwd apps/stock/engine build:debug; then bun test test/integration/backtest-result-mapping.test.ts test/integration/backtest-ledger.test.ts.
- If a new native-terminal-equity.test.ts is added, run it too. Do not derive expected quantity from production position sizing.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,55 +0,0 @@
# C02 — Reject malformed native data and preserve milliseconds
Parent epic: E1. Priority/severity: P1 / High. Relative complexity: S. Recommended specialization: Rust/NAPI boundary.
Scheduling source of truth: [manifest entry C02](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **DAT-02 — Verified:** Native input parsing silently discards malformed rows and truncates timestamps to seconds. [apps/stock/engine/src/api/backtest.rs:217](../../../../apps/stock/engine/src/api/backtest.rs#L217); [apps/stock/engine/src/api/backtest.rs:290](../../../../apps/stock/engine/src/api/backtest.rs#L290).
## Intended behavior and implementation scope
Validate all input rows before admission; return row-indexed errors instead of filter_map dropping rows. Preserve epoch milliseconds, reject non-finite/invalid OHLC and duplicate conflicting identities.
Measurable benefit: Stops silent dataset corruption.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/engine/src/api/backtest.rs
- test/integration/ingestion-backtest.test.ts
Write locks: native-public-api. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
No code prerequisite. Global execution approval and write-lock acquisition still required.
No additional economic-policy approval is needed for this narrowly scoped task.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- One invalid row causes an atomic load failure with its index; valid neighbors are not partially installed.
- Events at 1001ms and 1999ms remain distinct and ordered; unknown data types fail explicitly.
## Mandatory tests
- Native bridge tests invalid OHLC/NaN/missing field/unsupported type and sub-second round trip.
- Existing native load fixtures remain accepted.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,57 +0,0 @@
# C03 — Close the existing TypeScript fee-funding hole
Parent epic: E1. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Trading infrastructure implementation.
Scheduling source of truth: [manifest entry C03](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-03 — Verified:** Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. [apps/stock/engine/src/risk/mod.rs:89](../../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../../apps/stock/orchestrator/src/execution/model.ts#L234).
## Intended behavior and implementation scope
Narrow interim fix: retain the current legacy gross-exposure financing model and its reducing-order exemption. Add projected unpaid commissions to the existing non-reducing capital test, using proposed remaining quantity plus pending remaining quantities and each order's frozen commission policy. At fill, exclude the current order from other reservations and use its stored policy. Paid fees already reduce current equity and must not be counted again. No new cash-reservation table, schema, long-only rule or independent financing subsystem.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/orchestrator/src/execution/model.ts
- apps/stock/orchestrator/src/execution/SimulationExecution.ts
- test/integration/fee-funding.test.ts (new)
Write locks: ts-execution-model. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md.
## Dependencies and blockers
No code prerequisite. Global execution approval and write-lock acquisition still required.
No additional economic-policy approval is needed for this narrowly scoped task.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Under existing non-reducing policy:10000 cash, buy100@100,1% fee rejects without financial mutation; buy99@100 succeeds leaving1.
- Two zero-liquidity pending buys of50@100 with1% fees cannot both pass: reserved commitments would total10100. Cancellation releases the computed commitment.
- A99-share order filled10 then89 shares pays99 total commission and leaves1; duplicate events charge nothing twice.
- Existing short/reversal and risk-reducing behavior is unchanged. This fix does not claim the legacy financing model is cash-only or that insolvent short covers cannot create debt.
## Mandatory tests
- Dedicated test/integration/fee-funding.test.ts: fee_budget_10000, fee_budget_99, pending_fee_commitments, partial_fee_not_double_counted, cancelled_commitment_released, frozen_order_fee_policy.
- bun test test/integration/fee-funding.test.ts test/integration/order-execution.test.ts test/integration/strategy-recovery.test.ts; bun run typecheck; bun run test:contracts.
- Integration owner runs the existing disposable PostgreSQL order-execution suite before merge; no development trading DB.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,55 +0,0 @@
# C04 — Make partial runtime initialization recoverable
Parent epic: E1. Priority/severity: P1 / High. Relative complexity: S. Recommended specialization: Trading infrastructure implementation.
Scheduling source of truth: [manifest entry C04](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **RUN-02 — Verified:** Partial initialization can allocate services before isInitialized becomes true; shutdown exits early on that failure path. [apps/stock/orchestrator/src/core/ModeManager.ts:55](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L55); [apps/stock/orchestrator/src/core/ModeManager.ts:157](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L157).
## Intended behavior and implementation scope
Keep the successful lifecycle ordering. Register cleanup before each stage that may partially acquire resources; on initialization failure stop admission/feed, attempt all applicable cleanups, preserve the original initialization error and clear failed engine/config readiness. Retrying must be safe. Do not redesign runtime composition or add an imaginary native dispose method.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/orchestrator/src/core/ModeManager.ts
- test/integration/mode-lifecycle.test.ts
Write locks: runtime-composition. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md.
## Dependencies and blockers
No code prerequisite. Global execution approval and write-lock acquisition still required.
No additional economic-policy approval is needed for this narrowly scoped task.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Inject failure in execution initialize, storage initialize, strategy restore and market initialize. Clean up the failing stage as well as previously acquired stages; untouched stages are not invented resources.
- Cleanup failure neither masks the original error nor prevents remaining cleanup; feed stops before strategy/account teardown.
- No successful modeChanged event is published on failure; engine/config access cannot expose failed readiness; a retry succeeds.
- Existing shutdown ordering and live-disabled validation remain unchanged.
## Mandatory tests
- bun test test/integration/mode-lifecycle.test.ts with initialization_failure_each_stage, partial_acquisition_cleanup, cleanup_preserves_original_error, failed_init_retry and no_success_event.
- bun run typecheck; bun run test:contracts.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,5 +0,0 @@
# C05 — Merged into F01
This ID is retained for traceability and must not be claimed or implemented separately.
Its required behavior, fixtures and tests are owned by [F01](F01.md). See [skeptical review](../../REVIEW.md) for the effort reduction and [manifest](../manifest.json) for canonical scheduling metadata.

View file

@ -1,56 +0,0 @@
# C06 — Contain legacy research/paper interference without a second runtime
Parent epic: E1. Priority/severity: P0 / Critical. Relative complexity: S. Recommended specialization: Trading infrastructure implementation.
Scheduling source of truth: [manifest entry C06](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **RUN-01 — Verified:** TypeScript research preparation calls the shared mode manager, which shuts down the current mode, so a research job can interfere with paper runtime. [apps/stock/orchestrator/src/container.ts:101](../../../../apps/stock/orchestrator/src/container.ts#L101); [apps/stock/orchestrator/src/core/ModeManager.ts:47](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L47).
- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151).
## Intended behavior and implementation scope
Contain the legacy TS shared-mode hazard without building a second run-local TS execution framework. Use explicit composition roles: a shared paper runtime accepts only already-isolated native research; legacy TS research is allowed only in an explicit research-only composition with paper initialization/activation disabled. Reject unsafe combinations before mode mutation. Canonical TS strategies later use the Rust worker/session path. Keep the existing single-run busy guard.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/orchestrator/src/container.ts
- apps/stock/orchestrator/src/backtest/BacktestRunner.ts
- apps/stock/orchestrator/src/backtest/BacktestEngine.ts
Write locks: runtime-composition. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [C04](C04.md) integrated.
No additional economic-policy approval is needed for this narrowly scoped task.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Attempting a legacy TS run in a paper composition fails with a specific unsupported-combination diagnostic before paper shutdown, cash/checkpoint mutation or feed interruption.
- Explicit legacy research-only startup remains usable and cannot activate paper in that same composition.
- Native research alongside paper preserves paper lifecycle/account hashes; repeated cancelled/failed jobs do not alter them.
## Mandatory tests
- legacy_paper_combination_rejected_before_prepare, standalone_legacy_research_allowed, research_only_paper_activation_denied, native_paper_isolation.
- Existing backtest-workflow/typescript-backtest/mode-lifecycle suites; no new worker for legacy TS.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,64 +0,0 @@
# CL01 — Replace permissive DI configuration tests with production-path assertions
Parent epic: E10. Priority/severity: P1 / High. Complexity: M. Specialization: TypeScript infrastructure testing.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a maintainer, I want configuration tests to fail when a valid configuration stops working, so subsequent cleanup has a trustworthy safety net.
Expected benefit: Removes false passing coverage before changes to configuration and startup.
## Verified evidence
- **Verified — CL-F03:** Several success tests also pass when any exception is thrown; the test file supplies its own toUnifiedConfig implementation through a module mock. [libs/core/di/test/container-builder.test.ts:114](../../../../libs/core/di/test/container-builder.test.ts#L114).
## Implementation scope
- Replace the locally reimplemented config normalizer with the real configuration path for builder tests. Use complete, valid fixtures and skip external initialization.
- Make successful construction assert actual registered configuration/services. Make invalid input assert the specific expected rejection.
- Remove success-or-error catch blocks and prevent module mocks from contaminating other suites. Keep tests for current supported behavior; CL02 owns regressions for currently broken options/settings.
Likely existing files/modules:
- `libs/core/di/test/container-builder.test.ts`
- `libs/core/di/test/di.test.ts`
## Exclusions
- No production configuration behavior changes.
- No blanket replacement of every infrastructure test or rewrite of the test runner.
## Dependencies and ownership
Implementation prerequisites: None.
Write locks: `di-builder-tests`.
Parallel execution: Ready independently. Can run with CL03 and CL04 in isolated worktrees; do not share test-process module mocks. CL02 waits for this test baseline.
## Acceptance criteria
1. Every success case fails if its production builder call throws; no assertion treats an arbitrary error as success.
2. Tests use the actual toUnifiedConfig and DI schemas and check resulting values, not only container existence.
3. Invalid fixtures have explicit rejection assertions; valid fixtures do not depend on network access, local credentials, or running stores.
4. Tests pass individually and alongside the existing real-path QuestDB configuration regression without leaking mocks.
## Mandatory verification
Use existing workspace builds. Tests requiring PostgreSQL/Redis must use explicitly disposable safety fixtures.
```sh
bun test libs/core/di/test/container-builder.test.ts
bun test test/integration/questdb-configuration.test.ts
bun run typecheck
```
Required regression cases: valid full config, invalid required fields, nested/flat normalization, QuestDB credential propagation, and module-mock isolation.
## Risks and definition of done
Removing permissive assertions may expose old invalid fixtures. Repair fixtures against the supported schema; do not weaken validation or rewrite expectations to conceal production defects.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,79 +0,0 @@
# CL02 — Normalize database configuration once and enforce consistent service switches
Parent epic: E10. Priority/severity: P1 / High. Complexity: M. Specialization: TypeScript configuration and database adapters.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a developer, I want my connection settings and explicit service-disable choices to reach the intended clients unchanged, so configuration cannot silently enable services or discard settings.
Expected benefit: Addresses a reproduced enable/disable defect and the same multi-stage mapping pattern that caused the QuestDB credential failure.
## Verified evidence
- **Verified — CL-F01:** An isolated probe with supplied enabled configurations and all three enable options false still resolves enabled PostgreSQL, MongoDB and cache configurations. [libs/core/di/src/container/builder.ts:88](../../../../libs/core/di/src/container/builder.ts#L88).
- **Verified — CL-F01:** The canonical PostgreSQL schema accepts SSL, pool size and timeouts, while the DI schema and registration omit them. [libs/core/config/src/schemas/database.schema.ts:4](../../../../libs/core/config/src/schemas/database.schema.ts#L4).
- **Verified — CL-F01:** Client registration reconstructs only part of the accepted PostgreSQL configuration. [libs/core/di/src/registrations/database.registration.ts:43](../../../../libs/core/di/src/registrations/database.registration.ts#L43).
## Implementation scope
- Use the existing core configuration schemas as the canonical database representation; keep compatibility aliases in a single boundary adapter rather than multiple reconstruction passes.
- Define consistent precedence: an explicit service option false disables that service; true permits but does not override an explicitly disabled configured service. Preserve documented defaults when neither is specified.
- Carry supported credentials, SSL, pool and timeout settings into client-specific configuration, including explicit ilpPort/influxPort translation. Audit accepted fields for silent loss and document supported mappings.
- Add real-path tests with distinctive nondefault values for each store. Update configuration types and DI registration together.
Likely existing files/modules:
- `libs/core/config/src/schemas/database.schema.ts`
- `libs/core/config/src/schemas/unified-app.schema.ts`
- `libs/core/di/src/config/schemas/`
- `libs/core/di/src/container/builder.ts`
- `libs/core/di/src/registrations/database.registration.ts`
- `libs/core/di/src/registrations/cache.registration.ts`
- `test/integration/questdb-configuration.test.ts`
- `libs/core/di/test/container-builder.test.ts`
Proposed new files/modules (names may be adjusted within this scope):
- `test/integration/store-configuration.test.ts`
## Exclusions
- No credential rotation, environment-file deletion, new configuration framework or database replacement.
- No connection to development trading state in automated tests; no financial-policy changes.
## Dependencies and ownership
Implementation prerequisites: [CL01](CL01.md).
Write locks: `di-configuration`, `di-container`, `di-builder-tests`.
Parallel execution: After CL01. Must be serialized with CL03 because both can edit container/builder.ts; this is an actual-file lock, not an additional code dependency.
## Acceptance criteria
1. The audit probe with configured stores enabled and explicit options false resolves disabled/null PostgreSQL, MongoDB and cache services without opening sockets.
2. Configured enabled=false remains disabled when the corresponding service option is true.
3. Nondefault PostgreSQL SSL, pool size and connection/idle timeouts reach final wire settings; QuestDB credentials and ports retain their existing regression guarantees.
4. Each supported database field has one explicit translation to the client representation; no accepted setting silently disappears during schema conversion.
5. Existing nested and flat configuration callers remain compatible, including intentional precedence when both appear.
## Mandatory verification
store-configuration.test.ts is a proposed new test file. Capture real client/wire configuration without connecting to stores; substitute external transports only where necessary.
```sh
bun run --cwd libs/core/di build
bun test libs/core/di/test/container-builder.test.ts
bun test test/integration/store-configuration.test.ts test/integration/questdb-configuration.test.ts
bun run typecheck
```
Required regression cases: all explicit disable switches, configured disable with option true, absent defaults, nested/flat precedence, optional credentials, SSL and nondefault pool/timeouts.
## Risks and definition of done
Configuration precedence and client SSL representations differ today. Preserve existing defaults, reject unsupported combinations explicitly, and do not make a broad strict-schema change that rejects unrelated process environment variables.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,73 +0,0 @@
# CL03 — Roll back failed shared-service startup and clear initialization timers
Parent epic: E10. Priority/severity: P1 / High. Complexity: M. Specialization: TypeScript resource lifecycle and concurrency.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a developer restarting services, I want a failed or timed-out initialization to release resources it acquired, so a retry starts from a clean state.
Expected benefit: Fixes a reproduced resource-ownership gap in shared DI startup without changing trading recovery.
## Verified evidence
- **Verified — CL-F02:** Initialization awaits Promise.all without rolling back earlier successful connections; an isolated cache-success/mongo-failure probe records no cache disconnect. [libs/core/di/src/utils/lifecycle.ts:24](../../../../libs/core/di/src/utils/lifecycle.ts#L24).
- **Verified — CL-F02:** Timeout promises retain timers after successful initialization. [libs/core/di/src/utils/lifecycle.ts:97](../../../../libs/core/di/src/utils/lifecycle.ts#L97).
- **Verified — CL-F02:** A failed lifecycle call rejects build before the caller receives a container to clean up. [libs/core/di/src/container/builder.ts:74](../../../../libs/core/di/src/container/builder.ts#L74).
## Implementation scope
- Track the resources and initialization work owned by a build attempt. Clean up acquired resources when initialization or service resolution fails.
- Clear initialization timeout handles when work settles. Keep startup failure bounded and retain cleanup ownership of any late-settling initializer.
- Reuse the existing lifecycle manager and client cleanup methods. Ensure cleanup errors do not hide the original startup failure and repeated cleanup is safe.
- Add failure-oriented tests with controlled deferred promises and fake/controlled timers; do not depend on live stores.
Likely existing files/modules:
- `libs/core/di/src/utils/lifecycle.ts`
- `libs/core/di/src/container/builder.ts`
- `libs/core/di/test/lifecycle.test.ts`
Proposed new files/modules (names may be adjusted within this scope):
- `test/integration/service-startup-rollback.test.ts`
## Exclusions
- No changes to ModeManager, strategy checkpoints, paper recovery, research leases or financial execution.
- No new lifecycle framework or blanket migration of all application shutdown handlers.
## Dependencies and ownership
Implementation prerequisites: None.
Write locks: `di-container`, `di-service-lifecycle`.
Parallel execution: Ready independently and disjoint from CL01/CL04. Serialize with CL02 on di-container; use separate test files from CL01.
## Acceptance criteria
1. When one service connects and another initialization fails, the connected service is cleaned up and build rejects with the original failure.
2. Resolution failures and timeouts also release resources acquired by that attempt; late successful initialization cannot leave an orphaned connection after failure.
3. Successful initialization leaves no pending startup timeout handles; failure paths clear settled-work timers.
4. Cleanup failure does not prevent remaining cleanup or conceal the initiating failure. Repeated shutdown is safe.
5. Existing successful startup and shutdown contracts remain covered; no tests require waiting for the production 30-second timeout.
## Mandatory verification
service-startup-rollback.test.ts is a proposed new test file. Use simulated services and controlled clocks; no databases or native builds are needed.
```sh
bun test libs/core/di/test/lifecycle.test.ts
bun test test/integration/service-startup-rollback.test.ts
bun run typecheck
```
Required regression cases: partial success followed by failure, dependency-resolution exception, timeout, late completion, cleanup exception, repeated cleanup and successful timer disposal.
## Risks and definition of done
A timeout does not cancel an arbitrary promise. The implementation must retain responsibility for pending work and clean up late resources, rather than assuming Promise.race cancelled initialization.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,71 +0,0 @@
# CL04 — Provide one consistent research startup path and repair stale commands
Parent epic: E10. Priority/severity: P1 / Medium. Complexity: S. Specialization: Bun/Turbo developer tooling.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a developer, I want documented startup commands to launch the required research services on predictable ports, so getting the workbench running does not require debugging obsolete scripts.
Expected benefit: Removes three broken command targets and inconsistent infrastructure startup.
## Verified evidence
- **Verified — CL-F08:** db:setup-ib, db:init and proxy reference files absent at the audit baseline; docker:start and infra:up use different paths. [package.json:55](../../../../package.json#L55).
- **Verified — CL-F08:** docker:start starts Dragonfly, PostgreSQL and QuestDB but omits MongoDB, unlike infra:up. [scripts/docker.sh:93](../../../../scripts/docker.sh#L93).
## Implementation scope
- Offer one clearly named research development command selecting web-api, orchestrator and web-app through existing tooling; reuse the current build dependencies.
- Make the documented infrastructure-start aliases agree on required stores and the supported Docker Compose invocation.
- Remove obsolete missing-file aliases or redirect them only to existing, reviewed equivalents. Preserve migration safeguards; ordinary startup must never execute destructive init/reset scripts.
- Document ports 2003/2004/5173 and required authentication configuration without printing or generating new secrets. Add dry-run/command-target checks to existing tooling tests.
Likely existing files/modules:
- `package.json`
- `scripts/docker.sh`
- `scripts/test/workspace.test.ts`
- `README.md`
- `apps/stock/README.md`
- `apps/stock/web-app/README.md`
## Exclusions
- No new process supervisor, deployment stack or package manager.
- No automatic reset, credential changes, provider ingestion, paper/live activation or startup of optional monitoring/admin services.
## Dependencies and ownership
Implementation prerequisites: None.
Write locks: `root-scripts`, `docker-startup`, `startup-documentation`.
Parallel execution: Ready independently. Can run with CL01/CL03. CL05 uses the existing libs/* workspace glob and must not edit root scripts concurrently.
## Acceptance criteria
1. Every retained script alias resolves to an existing executable target or documented installed tool; the three identified missing-file commands are repaired or removed.
2. The research dev task plan contains exactly the three intended application dev roles plus required build tasks; it does not start ingestion or activate paper/live accounts.
3. Infrastructure aliases agree on their store set and propagate failures instead of printing success after a failed Compose command.
4. Documentation matches actual commands and fixed ports. Existing .env files and contents remain intact.
5. Tests can verify task selection and command targets without starting services or provisioning containers.
## Mandatory verification
Use existing workspace builds. Tests requiring PostgreSQL/Redis must use explicitly disposable safety fixtures.
```sh
bun test scripts/test/workspace.test.ts
bun run build --dry=json
git diff --check
```
Required regression cases: missing command targets, exact dev task selection, startup failure exit propagation, and exclusion of reset/init/activation commands.
## Risks and definition of done
Changing convenience aliases can break local habits. Keep safe compatibility aliases where useful and make intentionally removed aliases explicit in documentation.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,84 +0,0 @@
# CL05 — Extract shared dataset and reporting logic behind a research library boundary
Parent epic: E10. Priority/severity: P2 / High. Complexity: M. Specialization: TypeScript domain boundaries and package migration.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a backend or research-tool developer, I want reusable dataset and reporting logic to have a stable package interface, so clients do not import another application implementation directory.
Expected benefit: Creates a small shared boundary for the API, workers and future research clients while preserving existing behavior.
## Verified evidence
- **Verified — CL-F04:** Web admission imports worker-application implementation modules directly. [apps/stock/web-api/src/services/canonical-research.service.ts:31](../../../../apps/stock/web-api/src/services/canonical-research.service.ts#L31).
- **Verified — CL-F04:** Result reading imports the orchestrator reporting implementation. [apps/stock/web-api/src/services/backtest-v2.service.ts:37](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L37).
- **Verified — CL-F04:** V2 validation mixes reusable normalization/hashing with a legacy conversion dependency. [apps/stock/orchestrator/src/data/historical-dataset-v2.ts:1](../../../../apps/stock/orchestrator/src/data/historical-dataset-v2.ts#L1).
## Implementation scope
- Introduce one focused libs/research workspace, @stock-bot/research, using the existing libs/* workspace pattern. Publish explicit browser-safe dataset-contract, server dataset-validation and pure result-analysis subpaths.
- Move only reusable V2 normalization/validation/hash and canonical statistical-report code. Keep provider IO, legacy source adaptation, worker supervision, build-file inspection and sandbox execution in application adapters.
- Keep thin compatibility re-exports at existing imports during migration; establish one implementation, not duplicate helpers. Do not relocate every historical contract or create a package per concept.
- Replace the API imports of these moved pure helpers and add import/bundle boundaries. Existing stock-config contract subpaths may remain dependencies when they load no configuration manager or application runtime.
Likely existing files/modules:
- `apps/stock/orchestrator/src/data/historical-dataset-v2.ts`
- `apps/stock/orchestrator/src/backtest/canonical-result.ts`
- `apps/stock/web-api/src/services/canonical-research.service.ts`
- `apps/stock/web-api/src/services/backtest-v2.service.ts`
- `apps/stock/web-api/src/services/dataset-preparation.service.ts`
- `apps/stock/web-api/src/services/validation-preview.ts`
- `apps/stock/web-api/src/services/chronological-validation.service.ts`
- `scripts/test/architecture.test.ts`
- `tsconfig.check.json`
Proposed new files/modules (names may be adjusted within this scope):
- `libs/research/package.json`
- `libs/research/tsconfig.json`
- `libs/research/src/dataset-contracts.ts`
- `libs/research/src/datasets.ts`
- `libs/research/src/results.ts`
## Exclusions
- No NAPI/Rust financial changes, new API routes, generic plugin/DI framework or relocation of provider adapters.
- No persisted schema/hash changes, edited historical artifact bytes, new feature caching, DSL or performance work.
## Dependencies and ownership
Implementation prerequisites: [D01](D01.md), [F08](F08.md), [R05](R05.md).
Write locks: `research-domain-package`, `dataset-domain`, `research-architecture-tests`.
Parallel execution: Code-ready against completed D01/F08/R05. Independent of the DI stories. Serialize exact API file edits with CL08 and dataset-client edits with CL06; CL06/CL08 depend on this boundary.
## Acceptance criteria
1. There is one implementation of moved V2 and report behavior; the old entrypoints are compatibility facades rather than copies.
2. The new library has no imports of apps/*/src implementation paths, service containers, databases, native bindings or application entrypoints.
3. The dataset-contract subpath bundles for the browser without node:crypto, filesystem access or native code; server hashing stays outside that entrypoint.
4. Existing dataset hash fixtures, acceptance/rejection cases and canonical analytics outputs remain identical.
5. The web API uses the shared package for moved helpers. Native-worker bundling and original-result reading still pass; old retained artifacts are preserved.
## Mandatory verification
Build the changed package and worker artifacts in the assigned checkout before integration tests. Preserve existing retained artifact fixtures rather than rebaselining economic output.
```sh
bun run build
bun test scripts/test/architecture.test.ts test/integration/historical-dataset-v2.test.ts test/integration/canonical-result.test.ts
bun test test/integration/canonical-sma.test.ts test/integration/retained-strategy-worker.test.ts
bun run typecheck
```
Required regression cases: browser-safe imports, one validation implementation, golden dataset hashes, metadata round trips, canonical analytics equivalence and retained-worker execution.
## Risks and definition of done
Hash property order, module-local prepared-object caches and worker build identities can change accidentally during moves. Preserve semantic outputs and retained executable bytes; new current builds must not overwrite original reproduction artifacts.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,74 +0,0 @@
# CL06 — Use shared dataset response schemas and eligibility checks in the workbench
Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: Shared contracts and frontend validation.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a researcher, I want the browser and API to interpret dataset responses consistently, so valid datasets do not fail because independent schema copies drift.
Expected benefit: Removes a large inline manifest schema and repeated eligibility rules from the backtest client.
## Verified evidence
- **Verified — CL-F05:** The client defines a second substantial dataset manifest schema and preparation-response validation. [apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts:113](../../../../apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts#L113).
- **Verified — CL-F05:** The server defines overlapping calendar, series, bounds and corporate-action structures. [apps/stock/orchestrator/src/data/historical-dataset-v2.ts:34](../../../../apps/stock/orchestrator/src/data/historical-dataset-v2.ts#L34).
- **Verified — CL-F05:** Workbench dataset eligibility is enforced separately at admission. [apps/stock/web-api/src/services/canonical-research.service.ts:51](../../../../apps/stock/web-api/src/services/canonical-research.service.ts#L51).
## Implementation scope
- Reuse the CL05 browser-safe structural schemas in dataset catalog/preparation response parsing.
- Centralize workbench-specific structural eligibility checks used by response consistency checks and admission, without broadening the single-asset/single-series policy.
- Keep expected-request/hash identity checks at the client boundary and full dataset-byte/hash validation at execution. Shared shape validation must not pretend to authenticate dataset content.
- Preserve existing prepared/stored-source response contracts, explicit unavailable reasons and immutable retained inputs.
Likely existing files/modules:
- `apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts`
- `apps/stock/web-api/src/services/canonical-research.service.ts`
- `apps/stock/config/src/contracts/canonical-research.ts`
- `test/integration/dataset-source-preparation-ui.test.tsx`
- `test/integration/canonical-workbench.test.tsx`
Prerequisite output: `libs/research/src/dataset-contracts.ts` is proposed by CL05 and must exist before this story begins; it is not present at this audit baseline.
## Exclusions
- No new datasets UI, automatic calendar assumptions, changed content hashes or wider execution eligibility.
- No browser hashing of full datasets, client-authoritative eligibility or weakened worker checks.
## Dependencies and ownership
Implementation prerequisites: [CL05](CL05.md).
Write locks: `dataset-response-contracts`, `web-backtest-api`.
Parallel execution: After CL05. Disjoint from CL07, which initially excludes backtestApiV2.ts; reserve this client file explicitly.
## Acceptance criteria
1. Calendar/series/bounds/action response structures have one shared schema definition used by the server and browser.
2. Valid server preparation and catalog fixtures are accepted by the browser; malformed or mismatched identities still fail.
3. Eligibility and unavailable-reason consistency match between UI response parsing and server admission for supported and unsupported fixtures.
4. A browser build of this client contains no native/file/database or Node hashing dependencies.
5. Stored snapshots, normalized bars, v1/v2 hash fixtures and exact run provenance remain unchanged.
## Mandatory verification
Use existing workspace builds. Tests requiring PostgreSQL/Redis must use explicitly disposable safety fixtures.
```sh
bun test test/integration/dataset-source-preparation-ui.test.tsx test/integration/canonical-workbench.test.tsx
bun test test/integration/dataset-source-preparation.test.ts test/integration/historical-dataset-v2.test.ts
bun test scripts/test/architecture.test.ts
bun run typecheck
```
Required regression cases: eligible/unsupported series, missing calendars/actions, malformed fields, corrupt response hashes, expected-request mismatch and browser dependency boundaries.
## Risks and definition of done
Manifest validation and full content integrity are different boundaries. Consolidate shared structures without dropping contextual checks or treating a catalog entry as proof that retained bars are valid.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,75 +0,0 @@
# CL07 — Share JSON transport handling across experiment and validation clients
Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: Frontend HTTP contracts and retry semantics.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a frontend maintainer, I want one small transport helper for repeated experiment request handling, so error and cancellation behavior stays consistent.
Expected benefit: Removes duplicated request/JSON/status handling without combining independent domain workflows.
## Verified evidence
- **Verified — CL-F06:** Experiment requests implement fetch, abort handling, JSON decoding, expected-status checks and uncertainty classification. [apps/stock/web-app/src/features/experiments/services/experimentApi.ts:44](../../../../apps/stock/web-app/src/features/experiments/services/experimentApi.ts#L44).
- **Verified — CL-F06:** Chronological validation repeats the same transport sequence with a different domain parser/error type. [apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts:29](../../../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts#L29).
## Implementation scope
- Extract a small browser JSON request helper and apply it first to ordinary/cost experiment, durable chronological-validation and walk-forward clients.
- Keep endpoint schemas, request identity comparisons and operation-specific error messages beside each domain client. Preserve cancellation as cancellation and existing ambiguous-acceptance classifications.
- Keep browser cookie transport separate from ResearchClient bearer credentials; reuse shared response parsers already present.
- Avoid hidden retries, generalized request managers, new state libraries or a policy-heavy client framework.
Likely existing files/modules:
- `apps/stock/web-app/src/lib/api.ts`
- `apps/stock/web-app/src/features/experiments/services/experimentApi.ts`
- `apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts`
- `apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts`
Proposed new files/modules (names may be adjusted within this scope):
- `apps/stock/web-app/src/lib/requestJson.ts`
- `test/integration/research-http-transport.test.ts`
## Exclusions
- No backtestApiV2.ts migration in this story; CL06 owns its dataset parser cleanup.
- No auth weakening, new automatic retries, endpoint/receipt changes, or mandatory conversion of every HTTP client.
## Dependencies and ownership
Implementation prerequisites: None.
Write locks: `web-experiment-transport`.
Parallel execution: Ready independently. It can run with CL05/CL06 and frontend component stories only when actual client/test files are disjoint.
## Acceptance criteria
1. The selected clients share fetch/JSON/status plumbing while retaining their public method and error contracts.
2. Aborted reads remain distinguishable from failed writes; no retry occurs unless explicitly requested by the caller.
3. Lost responses, malformed accepted responses and server failures preserve the current uncertain-submission behavior and receipt inputs.
4. Unexpected success statuses, invalid envelopes and wrong response identities still reject.
5. Browser requests include cookies; research-agent tokens are neither introduced into the browser nor routed through this helper.
## Mandatory verification
research-http-transport.test.ts is a proposed new test file. Substitute only HTTP responses; exercise the production helper and existing domain clients.
```sh
bun test test/integration/research-http-transport.test.ts
bun test test/integration/experiments-ui.test.tsx test/integration/chronological-validation-durable-ui.test.tsx test/integration/walk-forward-ui.test.tsx
bun test test/integration/experiment-retries-ui.test.tsx test/integration/cost-sensitivity-ui.test.tsx
bun run typecheck
```
Required regression cases: abort, network loss, invalid JSON, wrong 2xx status, 4xx/5xx domain errors, identity mismatch, cookie forwarding and absence of implicit POST retries.
## Risks and definition of done
A generic helper can erase distinctions between uncertain acceptance and definitive rejection. Keep those policies explicit in the domain client and preserve existing race/retry tests.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,76 +0,0 @@
# CL08 — Split backtest template, run and reproduction responsibilities behind the existing service
Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: TypeScript application services and PostgreSQL transactions.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a backend developer, I want coherent backtest application modules, so changing reproduction or run admission does not require navigating a thousand-line service.
Expected benefit: Reduces the number of unrelated behaviors sharing one class while preserving existing API and transaction contracts.
## Verified evidence
- **Verified — CL-F07:** BacktestServiceV2 combines template CRUD, run admission, controls, results, reproduction and row mapping in 1,071 lines at the audit baseline. [apps/stock/web-api/src/services/backtest-v2.service.ts:167](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L167).
## Implementation scope
- Keep BacktestServiceV2 as a compatible facade while extracting focused template operations, run submission/control operations and reproduction/result readers within the same application.
- Move logic with its existing transaction boundaries, identity checks and error types. Pass the existing query/transaction client through helpers; do not open nested pool transactions.
- Use the shared CL05 report/domain helpers. Keep schema mappings explicit and avoid a new generic repository/service layer for each table.
- Preserve idempotent receipt lookup before current eligibility checks and keep run/outbox insertion atomic.
Likely existing files/modules:
- `apps/stock/web-api/src/services/backtest-v2.service.ts`
- `apps/stock/web-api/src/services/run-reproduction.ts`
- `apps/stock/web-api/src/services/reproduction-comparison.ts`
- `apps/stock/web-api/src/routes/backtests-v2.routes.ts`
Proposed new files/modules (names may be adjusted within this scope):
- `apps/stock/web-api/src/services/backtests/templates.ts`
- `apps/stock/web-api/src/services/backtests/runs.ts`
- `apps/stock/web-api/src/services/backtests/reproduction.ts`
- `apps/stock/web-api/src/services/backtests/results.ts`
## Exclusions
- No schema migration, endpoint redesign, new simulator, financial calculations or receipt-key changes.
- No cleanup of legacy execution branches in this extraction; CL12 follows it.
## Dependencies and ownership
Implementation prerequisites: [CL05](CL05.md).
Write locks: `web-backtest-service`, `web-run-reproduction`.
Parallel execution: After CL05. Must not overlap CL12 or another backtest service owner. Can run with disjoint frontend work.
## Acceptance criteria
1. Existing service callers and routes retain method signatures, HTTP behavior and persisted result shapes.
2. Templates, admission/controls and reproduction/results have focused implementation modules; the facade does not duplicate extracted logic.
3. Same-key retries after edits/archive or eligibility changes recover the original admitted request; conflicting key reuse still fails.
4. Run and dispatch writes remain atomic; single-connection transactions do not acquire another pool client.
5. Reproduction pins retained original inputs/builds, and result reading still verifies provenance and reports missing canonical data explicitly.
## Mandatory verification
PostgreSQL tests require disposable stock_bot_safety* and Redis DB15 fixtures under the existing harness; never run them on development research or paper state. Extend existing admission/reproduction transaction tests.
```sh
bun test test/integration/run-reproduction-api.test.ts test/integration/reproduction-comparison.test.ts test/integration/canonical-durable-runner.test.ts
bun test test/integration/canonical-workbench.test.tsx test/integration/backtest-run-controls.test.tsx
bun run test:postgres
bun run typecheck
```
Required regression cases: receipt replay/conflicts, concurrent submission, archive races, cancellation, one-connection transaction behavior, result corruption and unavailable original builds.
## Risks and definition of done
Splitting code can accidentally move a check outside a lock or create nested transactions. Review operation order and test actual concurrent SQL behavior, not just mocked method calls.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,73 +0,0 @@
# CL09 — Separate strategy metadata, version inspection and publication UI
Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: React strategy workflows.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a strategy developer, I want version inspection, parameter editing and publication to be understandable independent workflows, so changes to one do not disturb the others.
Expected benefit: Reduces the responsibilities and coupled state in StrategyDetailPage without changing strategy authoring semantics.
## Verified evidence
- **Verified — CL-F07:** One 796-line file contains metadata editing, version selection, parameters, publication, cloning, history and comparison. [apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx:20](../../../../apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx#L20).
## Implementation scope
- Extract focused version inspection/comparison, metadata, and publication/clone panels or hooks as justified by their state ownership.
- Keep the route component responsible for selected strategy/version identity and composing panels. Reuse existing CandidatePublication, BuiltinReview and parameter components.
- Preserve exact clone/publication receipts, dirty-draft protection, parent/version identity checks and stale-response rejection.
- Use explicit local action states where they replace coupled Boolean flags; do not add a global state framework.
Likely existing files/modules:
- `apps/stock/web-app/src/features/strategies/StrategyDetailPage.tsx`
- `apps/stock/web-app/src/features/strategies/components/`
- `apps/stock/web-app/src/features/strategies/services/candidatePublication.ts`
- `test/integration/strategy-workbench.test.tsx`
Proposed new files/modules (names may be adjusted within this scope):
- `apps/stock/web-app/src/features/strategies/components/StrategyVersionPanel.tsx`
- `apps/stock/web-app/src/features/strategies/hooks/useStrategyClone.ts`
## Exclusions
- No browser IDE, new strategy/package format, review-policy changes or activation controls.
- No redesign of the future AI research workspace or removal of version/evidence history.
## Dependencies and ownership
Implementation prerequisites: None.
Write locks: `web-strategy-detail`.
Parallel execution: Ready independently; disjoint from DI, CL06 and CL07. Reserve strategy detail/panel/test files against any other frontend owner.
## Acceptance criteria
1. The route composes focused components instead of defining the complete version comparison/publication workflow inline.
2. Changing routes/versions cannot apply an old response to a new selection or lose an unacknowledged receipt silently.
3. Metadata, parameter, clone and candidate drafts preserve their current unsaved-change and retry behavior.
4. Archived/read-only/missing-version states, clone recovery and immutable version links remain functional.
5. Existing catalog review and candidate-isolation distinctions remain visible and unchanged.
## Mandatory verification
Use existing workspace builds. Tests requiring PostgreSQL/Redis must use explicitly disposable safety fixtures.
```sh
bun test test/integration/strategy-workbench.test.tsx test/integration/candidate-publication-ui.test.tsx
bun test test/integration/canonical-workbench.test.tsx
bun run typecheck
```
Required regression cases: version navigation races, dirty draft confirmation, ambiguous clone/publication response, archived family, review failure and immutable version reopen.
## Risks and definition of done
Extracted panels can reset state by remounting or keep state under the wrong version. Preserve the deliberate keyed identity boundaries and ownership checks.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,75 +0,0 @@
# CL10 — Separate experiment modes and make draft/submission state explicit
Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: React experiment workflow state.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a researcher configuring experiments, I want parameter sweeps, cost studies and validation recipes to have clear action ownership, so switching modes cannot lose or duplicate work.
Expected benefit: Makes the 623-line ExperimentEditor easier to maintain while retaining its important receipt and race protections.
## Verified evidence
- **Verified — CL-F07:** The editor combines multiple experiment kinds, template loading, candidate state, preview revisions and mutually exclusive submission owners. [apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx:49](../../../../apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx#L49).
- **Verified — CL-F07:** Chronological and walk-forward preflight components share draft fields and submission ownership through the same parent. [apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx:589](../../../../apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx#L589).
## Implementation scope
- Extract focused template/candidate selection, ordinary/cost preview-submission, and validation recipe composition at coherent state boundaries.
- Represent each action as an explicit draft/preview/submitting/uncertain/accepted state where that replaces coupled refs and Booleans. Keep concurrency coordination local to this workspace.
- Retain a single coordinator for mutually exclusive submissions and exact frozen key/body custody after an ambiguous response.
- Keep current response parsers, reset-segment validation semantics, invalidation rules and unsaved-change behavior.
Likely existing files/modules:
- `apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx`
- `apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx`
- `apps/stock/web-app/src/features/experiments/components/WalkForwardPreflight.tsx`
- `test/integration/experiments-ui.test.tsx`
Proposed new files/modules (names may be adjusted within this scope):
- `apps/stock/web-app/src/features/experiments/hooks/useExperimentSubmission.ts`
- `apps/stock/web-app/src/features/experiments/components/ExperimentDraftForm.tsx`
## Exclusions
- No new optimizer, validation policy, data model or financial behavior.
- No HTTP client/transport edits owned by CL07 and no global workflow/state-machine framework.
## Dependencies and ownership
Implementation prerequisites: None.
Write locks: `web-experiment-editor`.
Parallel execution: Ready independently. Can run alongside CL07 only with disjoint authored client/test files and preserved public client contracts. Integration checks must cover their combination.
## Acceptance criteria
1. The parent composes coherent workflows and owns one explicit submission coordinator; it no longer manages all request and form transitions inline.
2. Changing template, candidate, grid or mode invalidates only the matching preview and cannot submit stale data.
3. An uncertain accepted request keeps its exact body/key and blocks conflicting ordinary/chronological/walk-forward submission until resolved or explicitly abandoned.
4. Late responses after navigation or newer edits cannot overwrite current preview, errors or receipts.
5. Saved experiment IDs, validation reports, failed-trial visibility and current comparison links remain unchanged.
## Mandatory verification
Use existing workspace builds. Tests requiring PostgreSQL/Redis must use explicitly disposable safety fixtures.
```sh
bun test test/integration/experiments-ui.test.tsx test/integration/cost-sensitivity-ui.test.tsx
bun test test/integration/chronological-validation-durable-ui.test.tsx test/integration/walk-forward-ui.test.tsx
bun test test/integration/experiment-retries-ui.test.tsx
bun run typecheck
```
Required regression cases: mode switching, edited-after-preview, candidate parameter changes, concurrent clicks, ambiguous response, exact receipt retry, navigation races and explicit discard.
## Risks and definition of done
A visually cleaner form can accidentally weaken mutual exclusion or regenerate a receipt. Preserve the current race tests and test transitions rather than only rendered snapshots.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,74 +0,0 @@
# CL11 — Separate backtest template loading, run monitoring and submission state
Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: React asynchronous state and durable-run UX.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a researcher, I want saved-template editing, run selection and job submission to remain independent, so navigation and retries behave predictably.
Expected benefit: Reduces the responsibilities of the 571-line backtest hook without discarding its existing correctness protections.
## Verified evidence
- **Verified — CL-F07:** The hook owns template CRUD, eligibility, selected-run request chains, polling, submission receipts and cancellation. [apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts:34](../../../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts#L34).
- **Verified — CL-F07:** A 645-line page composes template configuration, controls, run history and result presentation. [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:1](../../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L1).
## Implementation scope
- Extract focused template state, selected-run monitoring and submission/cancellation helpers behind the current useBacktestV2 facade.
- Keep one owner for the selected status-then-results request chain. Generation checks and AbortControllers must still reject stale responses.
- Keep template archival, browser monitoring stop and server job cancellation distinct. Preserve exact in-memory receipt custody through ambiguous submissions.
- Reduce page wiring only where this extraction makes it redundant; reuse current result/configuration components.
Likely existing files/modules:
- `apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts`
- `apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx`
- `test/integration/backtest-run-controls.test.tsx`
- `test/integration/canonical-workbench.test.tsx`
Proposed new files/modules (names may be adjusted within this scope):
- `apps/stock/web-app/src/features/backtest/hooks/useRunMonitoring.ts`
- `apps/stock/web-app/src/features/backtest/hooks/useRunSubmission.ts`
## Exclusions
- No browser-persistent receipt journal, new backend controls, pause/resume support or financial result reconstruction.
- No dataset/HTTP parser edits owned by CL06 and no general hook framework.
## Dependencies and ownership
Implementation prerequisites: None.
Write locks: `web-backtest-monitor`.
Parallel execution: Ready independently. Can run with CL08 because UI/client contracts remain stable. Serialize with other backtest page/hook owners; keep CL06 API-client edits separate.
## Acceptance criteria
1. useBacktestV2 retains its public return contract while delegating distinct lifetimes to focused helpers.
2. Only the selected run/backtest identity can update status, errors or results; changing the parent route fences earlier requests.
3. Polling, WebSocket refresh and cancellation acknowledgement share one serialized refresh chain without overlapping result requests.
4. Uncertain submissions reuse the original key/body even after template edits or archival; creating a new logical request remains explicit.
5. Leaving a page stops browser observation without cancelling server work. Completed/cancelled/failed/missing results stay distinct and reopen correctly.
## Mandatory verification
Use existing workspace builds. Tests requiring PostgreSQL/Redis must use explicitly disposable safety fixtures.
```sh
bun test test/integration/backtest-run-controls.test.tsx test/integration/canonical-workbench.test.tsx
bun test test/integration/run-reproduction-ui.test.tsx
bun run typecheck
```
Required regression cases: selected-run and parent navigation races, reload, late status/results, WebSocket invalidation during a poll, cancellation failure, archive while pending and exact receipt retry.
## Risks and definition of done
Moving refs between hooks can change their lifetime or create stale closures. Preserve identity ownership and existing interaction tests; do not replace this with several independent polling effects.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,73 +0,0 @@
# CL12 — Simplify retired execution seams while preserving historical reads
Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: Compatibility cleanup and execution boundaries.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a strategy developer, I want the supported execution path to be obvious, so obsolete APIs and impossible fallback branches do not look like alternative financial authorities.
Expected benefit: Removes confirmed-unreachable new-run code and sharpens supported-versus-compatibility boundaries without deleting useful history.
## Verified evidence
- **Verified — CL-F09:** New run admission rejects non-catalog requests before retaining legacy snapshot fallback branches later in the same method. [apps/stock/web-api/src/services/backtest-v2.service.ts:461](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L461).
- **Verified — CL-F09:** The legacy runBacktest entry exists only to reject execution. [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:70](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L70).
- **Verified — CL-F09:** Legacy and canonical native exports remain adjacent; this alone does not prove legacy exports are unused. [apps/stock/engine/index.mjs:28](../../../../apps/stock/engine/index.mjs#L28).
## Implementation scope
- Inventory the callers of touched legacy seams and classify each as supported execution, historical result compatibility, preserved research, or explicit retired-API rejection in the story handoff.
- Remove branches proved unreachable after canonical admission and stop carrying their legacy input requirements through current run helpers.
- Keep explicit retired-API responses small and truthful. Preserve their current HTTP/status behavior unless a separately approved API change is required.
- Extend existing architecture checks so canonical entrypoints cannot regain legacy accounting/fill fallback dependencies. Preserve compatibility result readers and retained artifacts.
Likely existing files/modules:
- `apps/stock/web-api/src/services/backtest-v2.service.ts`
- `apps/stock/web-api/src/services/backtest-result.ts`
- `apps/stock/orchestrator/src/backtest/BacktestRunner.ts`
- `apps/stock/orchestrator/src/backtest/execution-engine.ts`
- `apps/stock/orchestrator/src/api/rest/backtest.ts`
- `scripts/test/architecture.test.ts`
## Exclusions
- No mass deletion or rewrite of old strategies, calculation APIs, legacy Rust exports, short-trade examples, financial fixtures or stored results.
- No changes to historical request/result formats, economic policies, original reproduction artifacts or supported risk controls.
## Dependencies and ownership
Implementation prerequisites: [CL08](CL08.md).
Write locks: `web-backtest-service`, `legacy-execution-boundaries`.
Parallel execution: After CL08. One owner for the affected execution/API seams. This is not authority to remove unrelated code merely because static imports look absent.
## Acceptance criteria
1. Current run submission contains no fallback branch that its admission guard makes impossible.
2. Canonical entrypoint dependency checks forbid legacy financial execution; retired APIs still return their documented rejection rather than starting work.
3. Existing legacy result mapping and historical reads pass unchanged; callers of every removed branch are documented and verified.
4. Native financial output, strategy decisions, fees and equity remain identical on existing deterministic fixtures.
5. No preserved calculation capability, retained artifact or compatibility reader is removed without separate evidence and scope approval.
## Mandatory verification
Use existing workspace builds. Tests requiring PostgreSQL/Redis must use explicitly disposable safety fixtures.
```sh
bun test scripts/test/architecture.test.ts
bun test test/integration/canonical-durable-runner.test.ts test/integration/backtest-result-mapping.test.ts
bun test test/integration/canonical-sma.test.ts test/integration/strategy-runtime.test.ts
bun run typecheck
```
Required regression cases: retired entry rejection, canonical-only admission, historical result reads, no legacy fallback and unchanged economic fixtures.
## Risks and definition of done
Runtime exports and retained artifacts have consumers beyond simple source imports. Keep native exports and preserved algorithms out of this story; distinguish unreachable control flow from merely old code.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,72 +0,0 @@
# CL13 — Hide placeholder navigation while preserving useful product routes
Parent epic: E10. Priority/severity: P2 / Low. Complexity: S. Specialization: React navigation and product clarity.
Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest.
## User story and outcome
As a user, I want navigation to lead to functioning workflows, so unfinished pages do not imply capabilities the product does not have.
Expected benefit: Immediately reduces misleading navigation without committing to a new AI research interface.
## Verified evidence
- **Verified — CL-F10:** Portfolio, Analytics and Settings are top-level navigation items. [apps/stock/web-app/src/lib/constants.ts:32](../../../../apps/stock/web-app/src/lib/constants.ts#L32).
- **Verified — CL-F10:** Those destinations currently render Coming Soon placeholders. [apps/stock/web-app/src/app/App.tsx:34](../../../../apps/stock/web-app/src/app/App.tsx#L34).
## Implementation scope
- Remove placeholder destinations from primary navigation while keeping existing direct URLs readable with a clear unavailable message.
- Keep working strategy, backtest, experiment, research, market-data, system and paper-review navigation intact.
- Update current product documentation to match the visible menu and add focused route/navigation coverage.
- Do not relabel completed backtest analytics as a new standalone Analytics capability.
Likely existing files/modules:
- `apps/stock/web-app/src/lib/constants.ts`
- `apps/stock/web-app/src/app/App.tsx`
- `apps/stock/web-app/README.md`
- `docs/guide/README.md`
Proposed new files/modules (names may be adjusted within this scope):
- `test/integration/navigation.test.tsx`
## Exclusions
- No deletion of portfolio/analytics domain code or existing run/experiment analytics.
- No redesign of Research around chat, MCP, notebooks or an unapproved product workflow; no deployment activation changes.
## Dependencies and ownership
Implementation prerequisites: None.
Write locks: `web-navigation`.
Parallel execution: Ready independently but lower priority than the first cleanup wave. Reserve route/navigation files against any concurrent product work.
## Acceptance criteria
1. The primary menu contains no links to pages that only say Coming Soon.
2. Existing placeholder URLs remain explicit and safe to open; working deep links and authentication boundaries remain unchanged.
3. Implemented run/experiment analytics, research-agent access and paper-review pages remain discoverable.
4. Navigation tests cover desktop/mobile data sources or their shared navigation model and direct-route behavior.
## Mandatory verification
navigation.test.tsx is a proposed new test file. Test the shared navigation model and route output without provisioning application infrastructure.
```sh
bun test test/integration/navigation.test.tsx
bun test test/integration/canonical-workbench.test.tsx
bun run typecheck
```
Required regression cases: placeholder visibility, working link targets, retained deep links, authenticated routing and existing analytics access.
## Risks and definition of done
A menu cleanup can accidentally make a working capability inaccessible. Hide only verified placeholders and preserve existing route identities.
Done means the acceptance criteria and relevant checks pass, an independent review accepts the focused diff, and the integrator records exact test results and a commit/reference in the manifest. Preserve the compatibility and financial invariants in the cleanup execution contract.

View file

@ -1,61 +0,0 @@
# CL14 — Require canonical capabilities in durable research contracts
Parent epic: E11. Priority/severity: P1 / High. Complexity: M. Specialist: TypeScript contracts and durable research.
Scheduling and commit evidence: [manifest](../manifest.json). Scope baseline: `700ee09c`. Owner authorized planning, implementation and one commit per completed task on 2026-10-26; CL21 remains conditional. Follow [quality gates](../../QUALITY-GATES.md) and [agent instructions](../../agents/implementation.md).
## Outcome and evidence
execution-engine.ts:13 requires retired execution/playback but makes runCanonical optional. run-repository.ts:25 does the same for canonical claim/load/complete. BacktestRunner.ts:225,287,327 probes mandatory capabilities at runtime. RustBacktestAdapter.ts:35 storage and BacktestRunner.ts:60 engineName are unused.
The concrete benefit is a smaller supported execution surface with unchanged financial behavior. Findings are verified at the baseline; recheck caller/module evidence before edits. This does not imply active financial corruption.
## Scope
- Define required canonical engine/repository capabilities for the current runner. Preserve legacy interfaces where retained consumers actually need them.
- Remove unused storage and engineName constructor requirements and their caller/fixture plumbing.
- Remove only redundant optional-capability probes; preserve parsing of untrusted input, explicit unavailable-store errors, retired queue/HTTP rejection, and every lease/terminal-write rule.
- Keep legacy repository methods in place unless a tiny interface separation suffices; physical relocation is not required.
Likely files/modules:
- `apps/stock/orchestrator/src/backtest/execution-engine.ts`
- `apps/stock/orchestrator/src/backtest/run-repository.ts`
- `apps/stock/orchestrator/src/backtest/BacktestRunner.ts`
- `apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts`
- `apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts`
- `apps/stock/orchestrator/src/container.ts`
- `test/fixtures/canonical-runner.ts`
## Exclusions
No changes to financial semantics, SQL schema, lease policy, historical readers, native exports or persisted request/result shapes. Preserve retained strategy packages/datasets/results, useful algorithms, reviewed calculations, durable recovery and the existing .env files. No pushes, PRs or paper/live activation.
## Dependencies and ownership
Prerequisites: None; inspect existing integrated baseline rather than reopening earlier cleanup tasks.
Write locks: `canonical-runner-contract`, `orchestrator-composition`.
Parallelism: May run alongside CL15. Serialize actual container.ts edits with CL16; this is a file lock, not a semantic prerequisite.
## Acceptance criteria
1. Current runner cannot type-check against an engine/repository lacking required canonical methods.
2. Canonical success, cancellation, lease loss and unavailable storage retain their behavior; old queued requests cannot execute.
3. Existing historical writers/readers and retirement diagnostics remain available to their existing consumers.
## Mandatory verification
- bun run typecheck
- bun test test/integration/canonical-durable-runner.test.ts test/integration/backtest-workflow.test.ts test/integration/canonical-worker-lifecycle.test.ts test/integration/research-pool.test.ts test/integration/research-runtime-isolation.test.ts scripts/test/architecture.test.ts
- Disposable PostgreSQL: test/postgres/canonical-durable-backtest.test.ts
Use isolated worktrees/build outputs and disposable safety databases/Redis only. Never rebaseline financial fixtures to hide changed behavior. Integrator runs repository checks on the combined source. Performance work remains deferred; no speed claims are part of acceptance.
## Risks and definition of done
Weakening fail-closed boundaries or dropping compatibility methods while narrowing types.
Done requires scoped tests, independent reviewer acceptance, integration verification, and a focused commit. The manifest owns status and evidence; implementers do not edit it. Root records each completed commit in the next bookkeeping update; the task completion commit includes its tests/reviewer evidence, avoiding self-referential hashes. Unrelated prior CL01–CL13 review status remains unchanged.

View file

@ -1,67 +0,0 @@
# CL15 — Retire abandoned Rust architecture scaffolding
Parent epic: E11. Priority/severity: P1 / High. Complexity: M. Specialist: Rust module graph and compatibility.
Scheduling and commit evidence: [manifest](../manifest.json). Scope baseline: `700ee09c`. Owner authorized planning, implementation and one commit per completed task on 2026-10-26; CL21 remains conditional. Follow [quality gates](../../QUALITY-GATES.md) and [agent instructions](../../agents/implementation.md).
## Outcome and evidence
lib.rs:5 compiles adapters; adapters/mod.rs:32 fabricates price-100 fills without calling its wrapped handler, :80 reports arbitrary orders Filled. Repository references are confined to scaffold and stale MIGRATION.md. Cargo/lib.rs and module declarations do not include the alternate architecture files.
The concrete benefit is a smaller supported execution surface with unchanged financial behavior. Findings are verified at the baseline; recheck caller/module evidence before edits. This does not imply active financial corruption.
## Scope
- Recheck module graph and repository callers; record a concise deletion/preservation inventory.
- Remove unused placeholder adapter framework and truly obsolete duplicate architecture entrypoints/backups.
- Inspect uncompiled metrics/results/framework for unique useful algorithms; preserve any such code in an explicitly retained location with honest status rather than silently deleting capability.
- Replace misleading migration guidance with current canonical versus retained-compatibility map. Keep compiled legacy constructors, indicators, analytics and meaningful regression tests.
Likely files/modules:
- `apps/stock/engine/src/lib.rs`
- `apps/stock/engine/src/adapters/`
- `apps/stock/engine/src/lib_new.rs`
- `apps/stock/engine/src/lib_simplified.rs`
- `apps/stock/engine/src/test_lib.rs`
- `apps/stock/engine/src/api_new/`
- `apps/stock/engine/src/domain.bak/`
- `apps/stock/engine/src/events.bak/`
- `apps/stock/engine/src/modes.bak/`
- `apps/stock/engine/src/backtest/results.rs`
- `apps/stock/engine/src/backtest/metrics_calculator.rs`
- `apps/stock/engine/src/strategies/framework/`
- `apps/stock/engine/MIGRATION.md`
## Exclusions
No blanket legacy API deletion, rewriting algorithms, adding a new framework, loader/provenance changes or financial-core edits. Preserve retained strategy packages/datasets/results, useful algorithms, reviewed calculations, durable recovery and the existing .env files. No pushes, PRs or paper/live activation.
## Dependencies and ownership
Prerequisites: None; inspect existing integrated baseline rather than reopening earlier cleanup tasks.
Write locks: `native-module-graph`.
Parallelism: Independent of TS contract/lifecycle work. Serialize Rust module and native build output with CL18.
## Acceptance criteria
1. No compiled adapter can manufacture placeholder fills; no repository consumers lose supported APIs.
2. Every removed file is classified by module/caller evidence; unique useful calculations remain discoverable.
3. Native ESM/CJS constructors and canonical reports retain existing behavior; current docs no longer recommend abandoned scaffolding.
## Mandatory verification
- cargo test -p engine --lib --offline
- Build native addon from this checkout; bun test scripts/test/native-bindings.test.ts test/integration/native-terminal-equity.test.ts test/integration/native-market-data.test.ts
- bun test scripts/test/architecture.test.ts
Use isolated worktrees/build outputs and disposable safety databases/Redis only. Never rebaseline financial fixtures to hide changed behavior. Integrator runs repository checks on the combined source. Performance work remains deferred; no speed claims are part of acceptance.
## Risks and definition of done
Mistaking retained algorithms/public compatibility APIs for dead scaffolding; native rebuild/provenance required.
Done requires scoped tests, independent reviewer acceptance, integration verification, and a focused commit. The manifest owns status and evidence; implementers do not edit it. Root records each completed commit in the next bookkeeping update; the task completion commit includes its tests/reviewer evidence, avoiding self-referential hashes. Unrelated prior CL01–CL13 review status remains unchanged.

View file

@ -1,60 +0,0 @@
# CL16 — Give orchestrator composition an explicit shutdown owner
Parent epic: E11. Priority/severity: P1 / High. Complexity: M. Specialist: TypeScript lifecycle and failure recovery.
Scheduling and commit evidence: [manifest](../manifest.json). Scope baseline: `700ee09c`. Owner authorized planning, implementation and one commit per completed task on 2026-10-26; CL21 remains conditional. Follow [quality gates](../../QUALITY-GATES.md) and [agent instructions](../../agents/implementation.md).
## Outcome and evidence
simple-container.ts:46 initializes DB clients then :58 registers app services without enclosing rollback and returns only services at :68. index.ts:159 drains app work but not database/cache clients; termination uses process.exit. builder.ts:76 keeps lifecycle owner only locally.
The concrete benefit is a smaller supported execution surface with unchanged financial behavior. Findings are verified at the baseline; recheck caller/module evidence before edits. This does not imply active financial corruption.
## Scope
- Expose an explicit owned runtime/shutdown handle while preserving compatible createContainer callers where needed.
- Reuse existing lifecycle cleanup to roll back application-registration and HTTP-bind failures after successful shared-service startup.
- Stop admission, drain durable runner/paper/queue work, then close borrowed adapters exactly once. Preserve initiating errors and attempt cleanup even if another closer fails.
- Remove now-irrelevant ModeManager cleanup from the canonical entrypoint; avoid broad app lifecycle migration.
Likely files/modules:
- `apps/stock/orchestrator/src/simple-container.ts`
- `apps/stock/orchestrator/src/container.ts`
- `apps/stock/orchestrator/src/index.ts`
- `libs/core/di/src/container/builder.ts`
- `libs/core/di/src/utils/lifecycle.ts`
- `test/integration/service-startup-rollback.test.ts`
## Exclusions
No changes to paper activation, account recovery, financial semantics, job lease policy, other application startup flows or readiness feature O02. Preserve retained strategy packages/datasets/results, useful algorithms, reviewed calculations, durable recovery and the existing .env files. No pushes, PRs or paper/live activation.
## Dependencies and ownership
Prerequisites: None; inspect existing integrated baseline rather than reopening earlier cleanup tasks.
Write locks: `orchestrator-composition`, `di-container`, `di-service-lifecycle`.
Parallelism: Can be prepared independently; serialize container.ts with CL14 and shared DI edits with any other owner.
## Acceptance criteria
1. Registration failure, HTTP bind failure, normal shutdown and repeated shutdown each close every owned resource once.
2. Runner terminal writes finish before PostgreSQL closure; one cleanup failure cannot skip remaining resources or mask original startup error.
3. Successful startup behavior, explicit paper composition and research isolation remain unchanged.
## Mandatory verification
- bun test libs/core/di/test/lifecycle.test.ts test/integration/service-startup-rollback.test.ts test/integration/paper-composition.test.ts test/integration/research-runtime-isolation.test.ts test/integration/canonical-worker-lifecycle.test.ts
- Add controlled orchestrator composition/startup tests for all acceptance failures; no development DB
- Build changed DI workspace; bun run typecheck
Use isolated worktrees/build outputs and disposable safety databases/Redis only. Never rebaseline financial fixtures to hide changed behavior. Integrator runs repository checks on the combined source. Performance work remains deferred; no speed claims are part of acceptance.
## Risks and definition of done
Double shutdown, early database closure, swallowed failures, unowned late initialization.
Done requires scoped tests, independent reviewer acceptance, integration verification, and a focused commit. The manifest owns status and evidence; implementers do not edit it. Root records each completed commit in the next bookkeeping update; the task completion commit includes its tests/reviewer evidence, avoiding self-referential hashes. Unrelated prior CL01–CL13 review status remains unchanged.

View file

@ -1,58 +0,0 @@
# CL17 — Separate historical reads from unused storage writes
Parent epic: E11. Priority/severity: P2 / Medium. Complexity: M. Specialist: TypeScript market data and provider normalization.
Scheduling and commit evidence: [manifest](../manifest.json). Scope baseline: `700ee09c`. Owner authorized planning, implementation and one commit per completed task on 2026-10-26; CL21 remains conditional. Follow [quality gates](../../QUALITY-GATES.md) and [agent instructions](../../agents/implementation.md).
## Outcome and evidence
StorageService.ts:71-193 combines mode initialization, DDL and two writers with no repository callers; historical capabilities/read/normalization start at :196/:250/:373. Current web dataset preparation uses only historical read capability.
The concrete benefit is a smaller supported execution surface with unchanged financial behavior. Findings are verified at the baseline; recheck caller/module evidence before edits. This does not imply active financial corruption.
## Scope
- Recheck callers; remove unused writers or explicitly isolate required compatibility behavior.
- Keep the existing historical facade and move concrete provider decoding/common validation into small cohesive functions only where it improves the data flow.
- Remove unnecessary PostgreSQL/mode ownership from the current historical reader; adapt retained examples only as necessary.
- Preserve provider selection, no fallback on missing/error, explicit synthetic opt-in, date semantics and all data-quality gates.
Likely files/modules:
- `apps/stock/orchestrator/src/services/StorageService.ts`
- `apps/stock/orchestrator/src/data/`
- `apps/stock/web-api/src/services/stored-dataset-preparation.ts`
- `test/integration/intraday-storage.test.ts`
## Exclusions
No new provider framework, source cleansing, null-volume coercion, cache, throughput optimization, DB migration or changes to adjustment/calendar policy. Preserve retained strategy packages/datasets/results, useful algorithms, reviewed calculations, durable recovery and the existing .env files. No pushes, PRs or paper/live activation.
## Dependencies and ownership
Prerequisites: [CL14](CL14.md)
Write locks: `historical-storage`.
Parallelism: After CL14; independent of native boundary and strategy diagnostic cleanup.
## Acceptance criteria
1. Current historical reader has no unused market/performance writes or ad hoc DDL responsibilities.
2. Existing provider routing, cancellation, malformed-row rejection and duplicate/timestamp/identity handling remain unchanged.
3. Frozen V1/V2 fixtures retain exact hashes and result eligibility; useful synthetic/legacy examples still work.
## Mandatory verification
- bun test test/integration/intraday-storage.test.ts test/integration/historical-dataset-v2.test.ts test/integration/ingestion-backtest.test.ts test/integration/stored-dataset-preparation.test.ts
- bun run typecheck
- Disposable PostgreSQL: test/postgres/stored-dataset-preparation.test.ts if persistence-facing behavior/imports change
Use isolated worktrees/build outputs and disposable safety databases/Redis only. Never rebaseline financial fixtures to hide changed behavior. Integrator runs repository checks on the combined source. Performance work remains deferred; no speed claims are part of acceptance.
## Risks and definition of done
Accidentally changing normalization, hash inputs, explicit provider precedence or legacy initialization.
Done requires scoped tests, independent reviewer acceptance, integration verification, and a focused commit. The manifest owns status and evidence; implementers do not edit it. Root records each completed commit in the next bookkeeping update; the task completion commit includes its tests/reviewer evidence, avoiding self-referential hashes. Unrelated prior CL01–CL13 review status remains unchanged.

View file

@ -1,59 +0,0 @@
# CL18 — Share strict native parsing and financial view projection
Parent epic: E11. Priority/severity: P2 / Medium. Complexity: M. Specialist: Rust canonical transport contracts.
Scheduling and commit evidence: [manifest](../manifest.json). Scope baseline: `700ee09c`. Owner authorized planning, implementation and one commit per completed task on 2026-10-26; CL21 remains conditional. Follow [quality gates](../../QUALITY-GATES.md) and [agent instructions](../../agents/implementation.md).
## Outcome and evidence
api/replay.rs:78 and api/paper.rs:53 duplicate keys_match; replay.rs:297 and paper.rs:66 duplicate the canonical financial view.
The concrete benefit is a smaller supported execution surface with unchanged financial behavior. Findings are verified at the baseline; recheck caller/module evidence before edits. This does not imply active financial corruption.
## Scope
- Extract small pure helpers shared by native replay and paper adapters; keep host identities/envelopes separate.
- Preserve strict recursive unknown/missing field checks including explicit required null fields.
- Preserve paper intermediate journal pre-transaction admissionRevision and final post-transaction revision.
- Retain one financial kernel; no new serializer framework or TS arithmetic.
Likely files/modules:
- `apps/stock/engine/src/api/replay.rs`
- `apps/stock/engine/src/api/paper.rs`
- `apps/stock/engine/src/api/mod.rs`
- `apps/stock/engine/src/financial/mod.rs`
- `scripts/test/native-bindings.test.ts`
## Exclusions
No wire shape/version/checkpoint changes, event order changes, economic policy or generic API framework. Preserve retained strategy packages/datasets/results, useful algorithms, reviewed calculations, durable recovery and the existing .env files. No pushes, PRs or paper/live activation.
## Dependencies and ownership
Prerequisites: [CL15](CL15.md)
Write locks: `native-canonical-api`.
Parallelism: After CL15; no simultaneous native build or canonical Rust contract owner.
## Acceptance criteria
1. Equivalent canonical states expose identical financial-view fields through both hosts.
2. Nested unknown/missing/null contract negatives remain rejected identically.
3. Paper retry journals and every intermediate/final revision are unchanged; existing exact replay/checkpoint fixtures pass.
## Mandatory verification
- cargo test -p engine --lib --offline
- Build native addon; bun test scripts/test/native-bindings.test.ts test/integration/native-replay.test.ts test/integration/native-replay-report.test.ts
- Add focused view parity and strict nested/null fixtures where existing tests do not establish parity
Use isolated worktrees/build outputs and disposable safety databases/Redis only. Never rebaseline financial fixtures to hide changed behavior. Integrator runs repository checks on the combined source. Performance work remains deferred; no speed claims are part of acceptance.
## Risks and definition of done
Weakening required nullable fields or changing journal projection revision/order.
Done requires scoped tests, independent reviewer acceptance, integration verification, and a focused commit. The manifest owns status and evidence; implementers do not edit it. Root records each completed commit in the next bookkeeping update; the task completion commit includes its tests/reviewer evidence, avoiding self-referential hashes. Unrelated prior CL01–CL13 review status remains unchanged.

View file

@ -1,61 +0,0 @@
# CL19 — Share pure strategy bookkeeping and event ordering
Parent epic: E11. Priority/severity: P2 / Medium. Complexity: M. Specialist: TypeScript strategy and durable paper parity.
Scheduling and commit evidence: [manifest](../manifest.json). Scope baseline: `700ee09c`. Owner authorized planning, implementation and one commit per completed task on 2026-10-26; CL21 remains conditional. Follow [quality gates](../../QUALITY-GATES.md) and [agent instructions](../../agents/implementation.md).
## Outcome and evidence
strategy-controller.ts:60/:186 and CanonicalPaperExecution.ts:74/:330 duplicate diagnostics/feedback. feed.ts:48 and canonical-paper.ts:199 duplicate event comparator. Canonical paper imports canonicalJson from legacy strategy-recovery.ts:6.
The concrete benefit is a smaller supported execution surface with unchanged financial behavior. Findings are verified at the baseline; recheck caller/module evidence before edits. This does not imply active financial corruption.
## Scope
- Share pure initial-diagnostic and owner-scoped admission-feedback helpers without combining controllers.
- Use one event-key comparator with existing timestamp/phase/UTF-8/source ordering.
- Move canonicalJson unchanged to a neutral local module with compatibility re-export; preserve exact historical bytes.
- Keep research state confirmation and paper SQL transaction/recovery rules separate.
Likely files/modules:
- `apps/stock/orchestrator/src/strategies/strategy-controller.ts`
- `apps/stock/orchestrator/src/strategies/strategy-decision.ts`
- `apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts`
- `apps/stock/orchestrator/src/execution/canonical-paper.ts`
- `apps/stock/orchestrator/src/execution/strategy-recovery.ts`
- `apps/stock/orchestrator/src/paper/feed.ts`
## Exclusions
No generic state-machine framework, state serialization policy changes, checkpoint/schema version changes or replacement of canonicalJson with stricter stateCopy. Preserve retained strategy packages/datasets/results, useful algorithms, reviewed calculations, durable recovery and the existing .env files. No pushes, PRs or paper/live activation.
## Dependencies and ownership
Prerequisites: None; inspect existing integrated baseline rather than reopening earlier cleanup tasks.
Write locks: `strategy-decision-helpers`, `canonical-paper-contract`.
Parallelism: Independent of CL14/CL15/CL16; reserve paper and strategy helper files.
## Acceptance criteria
1. Equivalent research/paper inputs retain identical state/RNG/owner feedback; malformed ownership fails before state commit.
2. Unicode and phase ties keep Rust-compatible ordering.
3. Historical canonicalJson fixtures remain byte identical; crash/retry/partial failures retain committed state.
## Mandatory verification
- bun test test/integration/strategy-runtime.test.ts test/integration/paper-feed.test.ts scripts/test/architecture.test.ts
- bun run typecheck
- Disposable PostgreSQL: test/postgres/canonical-paper.test.ts test/postgres/canonical-paper-crash.test.ts test/postgres/strategy-recovery.test.ts
- Add parity/order/serialization fixtures that exercise public behavior
Use isolated worktrees/build outputs and disposable safety databases/Redis only. Never rebaseline financial fixtures to hide changed behavior. Integrator runs repository checks on the combined source. Performance work remains deferred; no speed claims are part of acceptance.
## Risks and definition of done
Moving commit boundaries, changing ordering or fingerprint serialization, sharing mutable diagnostic objects.
Done requires scoped tests, independent reviewer acceptance, integration verification, and a focused commit. The manifest owns status and evidence; implementers do not edit it. Root records each completed commit in the next bookkeeping update; the task completion commit includes its tests/reviewer evidence, avoiding self-referential hashes. Unrelated prior CL01–CL13 review status remains unchanged.

View file

@ -1,58 +0,0 @@
# CL20 — Return validated retained results from the worker supervisor
Parent epic: E11. Priority/severity: P2 / Medium. Complexity: M. Specialist: TypeScript IPC and native worker lifecycle.
Scheduling and commit evidence: [manifest](../manifest.json). Scope baseline: `700ee09c`. Owner authorized planning, implementation and one commit per completed task on 2026-10-26; CL21 remains conditional. Follow [quality gates](../../QUALITY-GATES.md) and [agent instructions](../../agents/implementation.md).
## Outcome and evidence
NativeBacktestWorker.ts:132 parses a retained result but returns the untyped string at :161; RustBacktestAdapter.ts:85 parses it again.
The concrete benefit is a smaller supported execution surface with unchanged financial behavior. Findings are verified at the baseline; recheck caller/module evidence before edits. This does not imply active financial corruption.
## Scope
- Add a narrow typed retained execution entry or precise overload using the existing parser.
- Retain parsed result only after identity/policy/artifact checks and resolve only after successful close and candidate cleanup.
- Preserve trace callers/raw transport compatibility without a broad protocol redesign.
- Keep separate trust-boundary and persistence validations.
Likely files/modules:
- `apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts`
- `apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts`
- `apps/stock/orchestrator/src/backtest/native-worker-protocol.ts`
- `test/integration/retained-strategy-worker.test.ts`
## Exclusions
No serialization optimization, sandbox redesign, extra process/service, removal of boundary validation or premature success before worker exit. Preserve retained strategy packages/datasets/results, useful algorithms, reviewed calculations, durable recovery and the existing .env files. No pushes, PRs or paper/live activation.
## Dependencies and ownership
Prerequisites: [CL14](CL14.md)
Write locks: `native-worker-protocol`, `canonical-adapter`.
Parallelism: After CL14; separate from native Rust and historical storage edits.
## Acceptance criteria
1. Canonical adapter receives the already-validated typed envelope without reparsing.
2. Wrong identity/policy/artifact/analytics, nonzero exit after result, abort and cleanup failure cannot succeed.
3. Caller mutation cannot alter submitted/expected identity; trace/strategy callers retain their existing contracts.
## Mandatory verification
- bun test test/integration/retained-strategy-worker.test.ts test/integration/canonical-worker-lifecycle.test.ts test/integration/canonical-strategy-worker.test.ts test/integration/native-replay-report.test.ts
- bun run typecheck
- Existing result-before-error/close, malformed envelope, mutation, cancellation and candidate cleanup regressions; add only missing cases
Use isolated worktrees/build outputs and disposable safety databases/Redis only. Never rebaseline financial fixtures to hide changed behavior. Integrator runs repository checks on the combined source. Performance work remains deferred; no speed claims are part of acceptance.
## Risks and definition of done
Returning before child cleanup, accepting mutated expected input, dropping validation for another request kind.
Done requires scoped tests, independent reviewer acceptance, integration verification, and a focused commit. The manifest owns status and evidence; implementers do not edit it. Root records each completed commit in the next bookkeeping update; the task completion commit includes its tests/reviewer evidence, avoiding self-referential hashes. Unrelated prior CL01–CL13 review status remains unchanged.

View file

@ -1,59 +0,0 @@
# CL21 — Extract private deterministic replay preparation when needed
Parent epic: E11. Priority/severity: P3 / Low. Complexity: M. Specialist: Rust deterministic replay.
Scheduling and commit evidence: [manifest](../manifest.json). Scope baseline: `700ee09c`. Owner authorized planning, implementation and one commit per completed task on 2026-10-26; CL21 remains conditional. Follow [quality gates](../../QUALITY-GATES.md) and [agent instructions](../../agents/implementation.md).
## Outcome and evidence
financial/replay.rs:262-641 combines canonicalization, validation and schedule creation with stateful advance/submit/restore at :642 onward.
The concrete benefit is a smaller supported execution surface with unchanged financial behavior. Findings are verified at the baseline; recheck caller/module evidence before edits. This does not imply active financial corruption.
## Scope
- Only activate when an upcoming calendar/timeframe change benefits from this split and the owner resumes it.
- Extract private preparation/schedule functions; keep existing public types and one Replay state owner.
- Preserve exact event order, input binding, barriers, financial trace and checkpoint bytes.
Likely files/modules:
- `apps/stock/engine/src/financial/replay.rs`
- `apps/stock/engine/src/financial/replay_tests.rs`
## Exclusions
No immediate implementation, new traits/managers, event framework, algorithm changes or performance work. Preserve retained strategy packages/datasets/results, useful algorithms, reviewed calculations, durable recovery and the existing .env files. No pushes, PRs or paper/live activation.
## Dependencies and ownership
Prerequisites: None; inspect existing integrated baseline rather than reopening earlier cleanup tasks.
Write locks: `native-replay`.
Parallelism: Deferred; sole replay owner when activated.
## Acceptance criteria
1. Private extraction leaves all public contracts/economic traces/checkpoints unchanged.
2. Future-suffix, equal-time permutation and restore-before/after-every-event regressions pass.
3. No additional mutable financial handle or module dependency cycle.
## Mandatory verification
- cargo test -p engine --lib --offline
- Build native addon; bun test test/integration/native-replay.test.ts test/integration/native-replay-report.test.ts
- Exact event-order/checkpoint equality fixtures
Use isolated worktrees/build outputs and disposable safety databases/Redis only. Never rebaseline financial fixtures to hide changed behavior. Integrator runs repository checks on the combined source. This extraction is not performance work; no speed claims are part of its acceptance.
## Risks and definition of done
Changing economic event ordering during a cosmetic move; intentionally deferred until there is practical need.
Done requires scoped tests, independent reviewer acceptance, integration verification, and a focused commit. The manifest owns status and evidence; implementers do not edit it. Root records each completed commit in the next bookkeeping update; the task completion commit includes its tests/reviewer evidence, avoiding self-referential hashes. Unrelated prior CL01–CL13 review status remains unchanged.
## Conditional review — October 28, 2026
No-go for now: no concrete calendar/timeframe change needs a replay-preparation split. Cosmetic movement of validated financial replay adds regression exposure without delivering a current capability. Reopen alongside a concrete replay preparation change that benefits from a private extraction. Status remains **deferred**, not implemented or silently cancelled. The owner authorized judgment on all remaining conditions and explicitly resumed performance work. [Current review](../../conditional-review.md). Earlier audit findings above are historical evidence: F02–F07/S06 already resolved competing financial cores and the old insertion queue; they are not reasons to implement this extension now.

View file

@ -1,28 +0,0 @@
# CL22 — Own queue transports without deleting pending payloads
Parent: E13. Priority: P1. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Shutdown preserves pending payloads, opens batch caches lazily, closes all owned handles once, and creates no observer workers.
Affected modules: libs/core/queue/src/queue-manager.ts. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Queue lifecycle/cache ownership regressions; disposable Redis payload survival. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Queue library tsc build passed; independent root queue-lifecycle and cache-ownership suites passed (see /tmp/stock-bot-cl22-root.log). Scoped lint/format passed. Pending payload ownership, drain behavior, and connection cleanup covered without service mutation.
## Accepted verification
Independent review reproduced premature worker drain at2s. Follow-up removes false-success2s/5s queue deadlines; actual Queue.close is idempotent and retains workers/transports until completion. Deferred-worker regression crosses both old deadlines; real Redis DB15 smoke preserves queued payloads through observer/producer shutdown and subsequent consumption. Root queue build and focused tests passed; service-level exit deadline remains authoritative.

View file

@ -1,24 +0,0 @@
# CL23 — Reject retired backtest creation before persistence
Parent: E13. Priority: P1. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Retired creates write nothing; catalog validation and historical reads remain compatible; obsolete auto-start cannot hide failure.
Affected modules: apps/stock/web-api/src/services/backtest.service.ts; routes/backtest.routes.ts; services/backtests/templates.ts. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Retired API/catalog regressions; v2 save/submit and retained readers. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Independent root retired-backtest-api, catalog-backtest-contract and backtest-result-mapping suites: 16 passed, 125 assertions. Scoped lint/format passed. Regression verifies no writes on retired V1/implicit autostart, explicit save-only behavior and preserved historical read/cancellation.

View file

@ -1,24 +0,0 @@
# CL24 — Remove prototype dashboard from normal navigation
Parent: E13. Priority: P1. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Default and old dashboard URLs lead to existing backtests; normal navigation has no random portfolio/fabricated summary.
Affected modules: apps/stock/web-app/src/app/App.tsx; features/dashboard; lib/constants.ts. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Navigation/render regression and final browser workflows. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Root reviewed route compatibility, removed demo-only consumers and real App rendering. Focused home/navigation tests passed; scoped lint/format passed. Final browser gate pending combined source.

View file

@ -1,28 +0,0 @@
# CL25 — Share validated product response contracts
Parent: E13. Priority: P1. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Shared run/template/catalog/research wire schemas; consistent current date; compatible clients reuse requestJson without automatic write retry.
Affected modules: apps/stock/config/src/contracts; web-api/services/backtests; web-app/features/*/services. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Response roundtrips; malformed/wrong identity/abort/lost acknowledgement; types and browser. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Shared response wire schemas and server type aliases; root mapping/date/invalid-response/run-control tests 59 passed (388 assertions), agent complete focused UI/transport/reproduction set 358 passed. Scoped lint/format passed. Preserves historical optional records and submission receipt/idempotency guards.
## Accepted verification
Chromium caught a valid historical SQL-null configuration rejected by the new schema. Read contracts now preserve null and canonical setup/detail access is guarded; no stored records rewritten. Source typecheck and108 focused tests835 assertions passed; final Chromium27 workflows971 assertions passed, including historical unavailable-results and run-error recovery. Error assertions follow real server/transport responses.

View file

@ -1,24 +0,0 @@
# CL26 — Replace private application imports with explicit shared modules
Parent: E13. Priority: P1. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
API imports no orchestrator private source; metadata verification cannot execute code; artifact inspection resolves lazily; build graph tracks shared inputs.
Affected modules: libs/research; apps/stock/config; web-api; orchestrator; scripts/test/architecture.test.ts. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Import/Turbo graph; dataset/candidate/paper admission; artifact identity; browser-safe contracts. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Moved existing shared server helpers to explicit trading-runtime subpaths, shared financial wire contracts to config, split metadata verifier from executable loader, and made artifact paths lazy. Config/runtime/API/orchestrator builds and full source typecheck passed. Architecture/Turbo/browser gates: 30 passed (7363 assertions); shared admission/storage/feed tests passed; isolated retained worker final15 passed after preserving rejection diagnostics. Native finance unchanged.

View file

@ -1,24 +0,0 @@
# CL27 — Initialize enabled ingestion handlers once per container
Parent: E13. Priority: P1. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Await container-owned registries; initialize only enabled executing instances; no async constructor fallbacks or half-initialized handlers.
Affected modules: apps/stock/data-ingestion/src/handlers; types.ts; libs/core/di/src/scanner. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Two-container isolation, disabled providers, failure/order, instance identity, schedules. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Root rebuilt DI and independently ran ingestion-handler-initialization: 6 passed, 27 assertions. Enabled-instance identity, two-container isolation, failure propagation, operations waiting for init, unchanged schedules and duplicate registration covered. Scoped lint/format passed.

View file

@ -1,24 +0,0 @@
# CL28 — Compose research services with explicit collaborators
Parent: E13. Priority: P2. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Compose focused collaborators once; no recursive full service graphs; caller-owned transactions.
Affected modules: apps/stock/web-api/src/services; routes. Root reserves actual files before delegation.
Dependencies: CL26.
## Verification
Service/API and PostgreSQL research/validation tests. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
One application composition graph with narrow collaborators and caller-owned transactions; independent review no blockers. Focused API45 passed547 assertions; root combined composition/capability5 passed1091 assertions. Disposable PG research/validation/walk-forward/paper/durable gates69 passed602 assertions plus catalog/durable-validation17 passed186 assertions. Scoped lint/format passed.

View file

@ -1,24 +0,0 @@
# CL29 — Share transactional experiment run and dispatch insertion
Parent: E13. Priority: P2. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
One private insertion helper for two experiment loops; explicit existing transaction; locking, quotas, receipts and holdouts remain with caller.
Affected modules: web-api/services/experiments.service.ts; chronological-validation.service.ts. Root reserves actual files before delegation.
Dependencies: CL28.
## Verification
PostgreSQL duplicate keys, numbering, rollback, holdout isolation. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Shared insertion helper preserves exact run/outbox SQL payload and order under caller-owned transaction; UUIDs, numbering, locks, quotas, receipts and holdout choice stay with callers. Focused26 tests351 assertions passed; independent SQL review no blockers. Complete repository check passed; full disposable PostgreSQL/Redis287 tests2949 assertions passed, including duplicate keys, second-dispatch rollback and heldout admission.

View file

@ -1,24 +0,0 @@
# CL30 — Separate research UI workflow state from rendering
Parent: E13. Priority: P2. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Feature-local workflow hooks and pure form/ack helpers; neutral shared dirty/style utilities; no universal mutation framework.
Affected modules: web-app/features/backtest/components/CanonicalSetup.tsx; ResearchEntry.tsx; SaveFindingDialog.tsx; shared hooks/styles. Root reserves actual files before delegation.
Dependencies: CL25.
## Verification
Late response, dirty draft, acknowledgement, double-submit, archive/finding regressions; browser. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Independent workspace/finding UI suites: 203 passed, 1306 assertions; agent full relevant UI set344 passed, 2143 assertions. Full source typecheck and scoped lint/format passed. Extracted feature-owned read/draft/write hooks; neutral styles and unsaved warning imports replace cross-feature dependencies; custody and uncertainty behavior preserved.

View file

@ -1,24 +0,0 @@
# CL31 — Publish a stable strategy authoring contract
Parent: E13. Priority: P2. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Public type-only authoring subpath; compatibility re-export; private controllers/native handles remain private.
Affected modules: libs/research; orchestrator/contracts/canonical-strategy.ts; examples; packaging tests. Root reserves actual files before delegation.
Dependencies: CL26.
## Verification
Standalone example compilation; packaging; canonical strategy and state regressions. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Independent public-author/runtime suite:25 passed,363 assertions; standalone compilation uses no repository aliases or orchestrator/native implementation types. Source and packaged strategies produce identical native traces/checkpoints; contract compilation and scoped lint/format passed. Old contract path is a type-only compatibility export.

View file

@ -1,24 +0,0 @@
# CL32 — Separate paper safety enforcement from readiness projection
Parent: E13. Priority: P2. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Pure readiness projection distinct from explicitly named expiry enforcement; preserve current latches/transactions and document accurately.
Affected modules: orchestrator/paper/CanonicalPaperRuntime.ts; routes/create-routes.ts. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Stale active/fresh inactive, storage failure/rollback, stale execution refusal; paper/monitoring regressions. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Independent pure projection/runtime suite 4 passed, 22 assertions; disposable PostgreSQL paper-runtime suite 22 passed, 143 assertions. Verified atomic expiry latch, rollback on storage failure, no implicit reactivation, stale generation and restart recovery. Scoped lint/format passed.

View file

@ -1,24 +0,0 @@
# CL33 — Isolate legacy repository writers from production capabilities
Parent: E13. Priority: P2. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Canonical concrete repository exposes supported writes only; isolated compatibility writers retain shared fencing; historical readers preserved.
Affected modules: orchestrator/backtest/PostgresBacktestRunRepository.ts; run-repository.ts; types.ts; legacy fixtures. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Canonical/legacy PostgreSQL durable/recovery tests; production import checks. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Canonical concrete/unavailable repositories expose supported writes only; legacy adapter reuses exact fencing helpers and unchanged method bodies. Root capability/composition5 passed1091 assertions. Disposable PG durable/canonical/retention/catalog tests passed in69+17-test gates; source and contract typechecks pass. Historical readers and supported runtime behavior preserved.

View file

@ -1,24 +0,0 @@
# CL34 — Normalize provider symbols and remove unused scaffolding
Parent: E13. Priority: P2. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Pure typed symbol adapters; preserve verified mappings; remove no-op pool configuration and unused QM wrappers after import inventory.
Affected modules: data-pipeline/repositories/PipelineSyncRepository.ts; symbols operations; container-setup.ts; ingestion/qm/shared. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Provider variant fixtures; PostgreSQL pipeline mapping/safety; types/imports. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Independent provider normalization suite: 6 passed, 10 assertions. Disposable PostgreSQL pipeline safety: 8 passed, 28 assertions, including verified mapping preservation, unverified update and replay identity. Scoped lint/format passed; active QM session manager preserved.

View file

@ -1,24 +0,0 @@
# CL35 — Make optional Python analytics composition honest and testable
Parent: E13. Priority: P2. Scheduling: [manifest](../manifest.json).
## Scope and acceptance
Actual app imports without endpoint/app cycle; lazy optional dependencies and observed capability health; honest unavailable endpoints.
Affected modules: apps/stock/analytics/src/api; apps/stock/analytics/test. Root reserves actual files before delegation.
Dependencies: None.
## Verification
Actual app import/startup and existing analytics API tests; missing dependency diagnostic. Focused review/tests precede the task commit; final combined build/types/lint/integration/PostgreSQL/browser gates follow. Preserve financial semantics, retained data/results, recovery, reviewed calculations and historical readers.
## Exclusions
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
## Accepted verification
Actual FastAPI app/lifespan and optional capability tests: 11 passed. Missing scientific/multipart dependencies do not prevent unrelated routes; unavailable initialization returns503, health observes state. Successful optimizer/model paths tested with stubs; load-to-list output shape corrected and covered. No heavy scientific packages installed.

View file

@ -1,67 +0,0 @@
# D01 — Introduce availability-aware dataset v2
Parent epic: E3. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: TypeScript trading infrastructure.
Scheduling source of truth: [manifest entry D01](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **DAT-01 — Verified:** Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. [libs/core/types/src/historical-data.ts:90](../../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L177).
- **DAT-03 — Verified:** Missing VWAP is replaced with typical price; reported volume and provider-adjusted prices are not a complete corporate-action execution model. [apps/stock/orchestrator/src/data/historical-dataset.ts:230](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L230); [libs/core/types/src/historical-data.ts:98](../../../../libs/core/types/src/historical-data.ts#L98).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
## Intended behavior and implementation scope
Add interval start/end, availableAt, venue/calendar revision and source sequence to frozen events; preserve missing VWAP as missing. Keep v1 snapshots immutable. Convert daily session labels only with an explicit versioned calendar; fail closed for unknown venue/time semantics. Include per-series identity/timeframe so a run can select exactly one execution feed per instrument and separate feature-only series.
Measurable benefit: Defines point-in-time truth before new replay logic.
Absorb D03 in the same manifest version: record universe/as-of and corporate-action coverage, distinguish signal-adjusted from raw execution prices and retain limitations. Do not build an action feed or a correctness-gate evidence subsystem. Known unsupported action ranges reject executable policy; unknown coverage stays explicitly exploratory, never silently verified.
### Sixth-wave scope clarification
Implement a separate additive v2 normalizer; leave the existing v1 loader, persisted snapshots, SQL, APIs and runtime unchanged. Callers supply source/revision-labelled UTC session tables with an IANA time zone; never infer an exchange from a symbol suffix or weekdays. Initially accept only full-duration intraday bars contained within a session; partial-session bars are unsupported. Explicit availability and interval-end assumptions remain distinct and hash-retained.
Verify the original hash before converting v1 and retain it as the parent hash. Converted VWAP is unknown because v1 cannot distinguish provider VWAP from a synthesized value. Unknown universe/action coverage stays exploratory, including after executable-policy validation; validation is not research certification. Trade-end bars remain available for terminal marking, while later replay enforces the half-open decision window. Prefix tests here prove normalization stability, not the future F06 replay gate.
## Exclusions
No unrelated refactor, new service or broker activation.
## Likely files and ownership
- libs/core/types/src/historical-data.ts
- apps/stock/orchestrator/src/data/historical-dataset.ts
- apps/stock/orchestrator/src/services/StorageService.ts
Write locks: dataset-contract. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
No code prerequisite. Global execution approval and write-lock acquisition still required.
Architecture decisions: ADR-003. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- A new manifest/hash is produced for every conversion; v1 hashes still verify.
- US daily bars become available at actual session end, including DST and half days; invalid/duplicate conflicts reject.
- Warmup and trade ranges are separate, with no invented VWAP or interpolation.
## Mandatory tests
- dataset_v1_compatibility, dataset_v2_hash, DST_half_day, missing_vwap, conflicting_duplicate.
- Future-suffix mutation does not change prior observable prefixes.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,67 +0,0 @@
# D02 — Connect supported intraday storage to research datasets
Parent epic: E3. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: TypeScript trading infrastructure.
Scheduling source of truth: [manifest entry D02](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **DAT-04 — Verified:** Historical storage selects QuestDB or daily MongoDB; the Mongo path explicitly rejects intraday requests. Ingestion-to-research routing requires an executable provider/interval capability check. [apps/stock/orchestrator/src/services/StorageService.ts:287](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L287); [apps/stock/orchestrator/src/services/StorageService.ts:299](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L299).
## Intended behavior and implementation scope
Trace the actual intraday collection/schema, add the smallest provider adapter or correct routing, and expose an explicit provider/interval coverage capability. Keep a single normalized dataset admission path; do not migrate all storage systems.
Measurable benefit: Makes supported intraday requests usable and honest.
### Verified ingestion evidence and seventh-wave boundary
Before implementation, inspected `apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts`: `fetchIntraday` looks up the listing, uses `eodExchange || Exchange`, copies provider Unix-second `timestamp`, `datetime`, `gmtoffset` and OHLCV, then upserts `eodIntraday1M`, `eodIntraday5M` or `eodIntraday1H` keyed by timestamp + `eodSearchCode` (lines 486–585 at base `b4af840`). The research reader currently chooses QuestDB first, otherwise only daily `eodPrices`.
Retain the common `getHistoricalBars` admission path. Add the existing EOD intraday mapping, explicit provider selection/capabilities and typed unavailable/unsupported errors. Capabilities describe connected stores and supported intervals, not proven range coverage. Preserve default QuestDB priority and never switch provider on an empty range/error. Explicit provider requests never fall back to daily or synthetic data. Validate whole Unix seconds and listing identity; Unix timestamps are already UTC and must not be shifted by `gmtoffset`. QM's adjusted/unpinned interval records remain unsupported.
Tests invoke the actual EOD writer with replaced HTTP/Mongo transport, then the real storage reader and v1/v2 dataset normalizers with explicit retained calendar/action metadata. This proves adapter composition, not database-server conformance or F06 replay. No optional v2 loader, active-runtime cutover or storage migration is required here.
Provider check (2026-10-22): [EODHD's intraday documentation](https://eodhd.com/financial-apis/intraday-historical-data-api) identifies the timestamp as UTC bar start and prices as unadjusted for subsequent corporate actions. It also describes delayed finalization after market close and possible historical corrections. Retrieval therefore does **not** establish point-in-time publication availability. Interval-end availability remains an explicit simulation assumption, never provider evidence; frozen content hashes retain the actual retrieved revision. Provider choice is initially a storage API parameter, not a new web/run-configuration control.
## Exclusions
No unrelated refactor, new service or broker activation.
## Likely files and ownership
- apps/stock/orchestrator/src/services/StorageService.ts
- apps/stock/data-ingestion/src/
- test/integration/ingestion-backtest.test.ts
Write locks: storage-adapters. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [D01](D01.md) integrated.
No additional economic-policy approval is needed for this narrowly scoped task.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- A disposable ingested 5m fixture is retrieved through the research path with unchanged timestamps/OHLC/count.
- Unavailable ranges/providers return typed errors, never daily data or synthetic fallbacks.
- Record the verified ingestion collection/adapter in the task evidence before changing code.
## Mandatory tests
- ingest_5m_freeze_replay, unsupported_interval, missing_range, provider_priority.
- Hash the ingested normalized fixture and compare retrieval.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,5 +0,0 @@
# D03 — Merged into D01
This ID is retained for traceability and must not be claimed or implemented separately.
Its required behavior, fixtures and tests are owned by [D01](D01.md). See [skeptical review](../../REVIEW.md) for the effort reduction and [manifest](../manifest.json) for canonical scheduling metadata.

View file

@ -1,66 +0,0 @@
# D04 — Provide prefix-safe shared feature calculation
Parent epic: E3. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Quantitative feature engineering.
Scheduling source of truth: [manifest entry D04](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315).
- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
## Intended behavior and implementation scope
Add a small feature request/result contract keyed by dataset hash, instrument, timeframe, parameters and implementation version. Reuse reviewed calculations; one experiment-local calculation per identical feature request. Prefix-gate precomputed outputs; no distributed feature service or persistent cache framework. Fitted/model features also key by artifact hash, fit-window identity and availability policy; they must not reuse a transform fitted on another partition.
Measurable benefit: Avoids duplicate work and feature leakage without a framework.
## Exclusions
No unrelated refactor, new service or broker activation.
## Likely files and ownership
- libs/calculations/
- apps/stock/engine/src/indicators/
- apps/stock/orchestrator/src/data/
- test/integration/strategy-contracts.test.ts
Write locks: feature-contract. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [S01](S01.md), [P01](P01.md) integrated.
No additional economic-policy approval is needed for this narrowly scoped task.
Deferred: Only after profiling demonstrates repeated identical feature work; use reviewed incremental calculations directly first.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Regime and strategy consumers requesting the same SMA/volatility share results within a run.
- Batch and incremental values match reviewed warmup/NaN semantics; a future data mutation cannot affect earlier features.
- Float feature outputs never become authoritative monetary calculations.
## Mandatory tests
- batch_incremental_parity, prefix_equivalence, shared_request_counter, warmup_alignment.
- Run calculations migration-preservation and numerical suites.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Conditional review — October 28, 2026
No-go for now: in the instrumented 15/252 baseline, reviewed SMA calculation took 7–10 ms across three sessions; copying/freezing took roughly 2.0–2.3 seconds. A shared feature cache does not address the measured cost. Reopen only for measured repeated identical feature work across actual consumers, preserving prefix and fit-window identity. Status remains **deferred**, not implemented or silently cancelled. The owner authorized judgment on all remaining conditions and explicitly resumed performance work. [Current review](../../conditional-review.md). Earlier audit findings above are historical evidence: F02–F07/S06 already resolved competing financial cores and the old insertion queue; they are not reasons to implement this extension now.

View file

@ -1,65 +0,0 @@
# F01 — Define the minimal financial contract and economic fixtures
Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Rust financial contract owner.
Scheduling source of truth: [manifest entry F01](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114).
- **FIN-03 — Verified:** Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. [apps/stock/engine/src/risk/mod.rs:89](../../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../../apps/stock/orchestrator/src/execution/model.ts#L234).
- **FIN-04 — Verified:** Native fills notify every strategy. TypeScript realized P&L uses aggregate symbol cost basis, not per-strategy cost basis. [apps/stock/engine/src/backtest/engine.rs:489](../../../../apps/stock/engine/src/backtest/engine.rs#L489); [apps/stock/orchestrator/src/execution/model.ts:108](../../../../apps/stock/orchestrator/src/execution/model.ts#L108).
## Intended behavior and implementation scope
Define only the contracts consumed by the first financial vertical slice: scalar posting rules, owner IDs, account risk-session boundary, commands/effects, snapshot version and stable decision identity. Use a maintained checked decimal implementation, not bespoke arithmetic. Absorb C05: add small hand-derived JSON/table fixtures beside their consumers, without a reference simulator or an expected-failure test campaign. Freeze the TS/Rust command/context shape before consumers implement it.
### Sixth-wave scope clarification
The additive contract separates strategy intents from engine-internal fill/mark/session commands. The snapshot is an economic projection, **not** a complete recoverable session. Full observation contexts, sessions and native bindings remain F06/F07 work; this task must not introduce a second executable engine.
The maintained decimal wrapper provides checked ingress, fixed-8 posting, addition and subtraction. Generic multiplication/division are intentionally absent: intermediate rounding needs operation-specific F02 tests, especially proportional basis release. Remaining-basis and command-conflict fixtures are hand-derived F02 specifications, not claims of implemented ledger or deduplication behavior. TypeScript validates wire shapes and canonical decimal strings only; it does no financial arithmetic.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/engine/src/financial/ (new small modules)
- apps/stock/engine/src/api/
- libs/core/types/src/financial-engine.ts (new)
- test/fixtures/economics/ (small new fixture set)
Write locks: financial-contract. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md.
## Dependencies and blockers
No code prerequisite. Global execution approval and write-lock acquisition still required.
Architecture decisions: ADR-002, ADR-003, ADR-004. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Financial postings use 8 decimal places with explicit round-half-away-from-zero at ties (matching current TS half-up behavior); reject overflow/non-finite/excess-precision external commands. Float observations/features are not converted into money strings on every native crossing.
- Authoritative basis is remaining cost amount, not rounded average price. Fixture buys3 shares for total5; partial/final disposals release exactly5 basis in total.
- Stable protocol snapshot/command serialization and unknown-version rejection pass small Rust/TS contract fixtures; scope is one supported version, not a compatibility-negotiation framework.
- Each regression fixture lists economic assumptions, hand calculation and owning task. Each implementation task adds its own passing regression coverage; do not merge a blanket failing suite.
## Mandatory tests
- Rust/TS fixture parse parity, rounding_ties_positive_negative, overflow_rejected, basis_residual_spec, command_id_conflict_spec.
- Use existing binding smoke tests to confirm Bun/addon compatibility; no temporary simulator or new FFI framework.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,70 +0,0 @@
# F02 — Implement one owner-aware financial ledger
Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Rust accounting.
Scheduling source of truth: [manifest entry F02](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-02 — Verified:** Native forced liquidation occurs after the last equity mark; reported final value reads that earlier mark, omitting terminal costs. [apps/stock/engine/src/backtest/engine.rs:135](../../../../apps/stock/engine/src/backtest/engine.rs#L135); [apps/stock/engine/src/backtest/simple_results.rs:308](../../../../apps/stock/engine/src/backtest/simple_results.rs#L308).
- **FIN-03 — Verified:** Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. [apps/stock/engine/src/risk/mod.rs:89](../../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../../apps/stock/orchestrator/src/execution/model.ts#L234).
- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114).
- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151).
## Intended behavior and implementation scope
Implement one owner-keyed ledger from its first version; absorb F03 rather than building aggregate cost basis and replacing it later. Adapt existing Rust position calculations. Store owned quantity and remaining cost amount; derive average price and account aggregates. For a partial disposal, round the proportional released basis at posting precision; final disposal releases the exact residual. Fees are separate postings. Use one internal apply(state,command) kernel for resident research and staged durable transactions.
### Seventh-wave implementation boundary
F01 is committed in `b4af840`. Keep this ledger additive: no replacement of active legacy position/accounting code, native binding, SQL transaction integration or paper migration. ADR-005 remains unapproved; F02 provides the in-memory transition/checkpoint seam, not its durable adapter.
- A ledger checkpoint is distinct from F01's economic projection. It retains genesis, books including closed-position realized P&L, cash/fees, marks, risk-session identity, revision and ordered accepted receipts/aliases. Restore verifies by replay and canonical state comparison. It is not an order/replay/strategy/RNG session snapshot.
- Exact multiplication and proportional release use maintained arithmetic with a single final half-away posting boundary, not precision-losing decimal intermediates. Account valuation sums owner-level marked postings; missing marks reject valuation instead of inventing zero or cost-based prices.
- Invalid commands fail atomically without changing balances, books, marks or receipts. Basic cash funding includes fees. Reservation and portfolio risk policies remain F04, including recording accepted risk-rejection outcomes.
- Identical command retry returns its original receipt even after later transitions. Identical fill under a new command ID aliases that receipt, explicitly marked replayed: compare event time and the entire canonical fill body, excluding only command ID. Different fill content or reuse of a fee ID by another fill rejects. Never emit duplicate economic deltas.
- Normal transitions stage only affected state; checkpoint serialization/replay is explicit. Record repeatable scoped transition and checkpoint/restore measurements without claiming end-to-end research throughput.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/engine/src/financial/ledger.rs (new)
- apps/stock/engine/src/financial/ownership.rs (only if separate module improves cohesion)
- apps/stock/engine/src/positions/mod.rs
Write locks: financial-contract, rust-ledger. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md.
## Dependencies and blockers
Implementation requires [F01](F01.md) integrated.
Architecture decisions: ADR-002. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Cash + marked holdings = equity; initial capital + net cashflows + realized gross P&L + unrealized P&L - fees = equity at declared posting precision.
- A buys10@100, B buys10@200, A sells10@200 => A gross realized1000, B retains10@200. Only A receives A's fill; wrong-owner disposal rejects.
- Total basis5 for quantity3 is not reconstructed as5.00000001 from display average. All partial/final disposals release exactly5.
- Duplicate identical fills are idempotent; conflicting ID payload fails; snapshot restore/replay yields identical canonical economic postings.
- Resident transitions do not serialize/clone the entire account every observation. Durable staging uses the same kernel and emits required ordered effect views.
## Mandatory tests
- owner_basis_A_B, basis_residual_partial_final, owner_quantity_sum, wrong_owner_disposal, per_fill_fee_once, conflicting_fill_id, snapshot_restore_parity.
- Seeded randomized valid transition sequences reconcile; terminal mark retains open positions without inventing a fill.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,5 +0,0 @@
# F03 — Merged into F02
This ID is retained for traceability and must not be claimed or implemented separately.
Its required behavior, fixtures and tests are owned by [F02](F02.md). See [skeptical review](../../REVIEW.md) for the effort reduction and [manifest](../manifest.json) for canonical scheduling metadata.

View file

@ -1,69 +0,0 @@
# F04 — Enforce cash reservations and portfolio risk centrally
Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Rust financial risk.
Scheduling source of truth: [manifest entry F04](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-03 — Verified:** Native order risk lacks a cash/fee reservation check. TypeScript compares gross exposure with pre-fee equity, so a fully funded buy can leave negative cash. [apps/stock/engine/src/risk/mod.rs:89](../../../../apps/stock/engine/src/risk/mod.rs#L89); [apps/stock/orchestrator/src/execution/model.ts:234](../../../../apps/stock/orchestrator/src/execution/model.ts#L234).
- **FIN-06 — Verified:** Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure. [apps/stock/engine/src/backtest/engine.rs:374](../../../../apps/stock/engine/src/backtest/engine.rs#L374); [apps/stock/engine/src/backtest/engine.rs:414](../../../../apps/stock/engine/src/backtest/engine.rs#L414).
## Intended behavior and implementation scope
Implement canonical cash-long-only funding, pending fee-inclusive reservations, fill-time affordability and existing per-order/symbol/gross limits. Accept explicit account RiskSessionBoundary commands from the F01 contract; do not infer a day from UTC or independently roll for every venue. Marked daily-loss and drawdown checks use canonical marks. Session rollover resets only daily baseline; peak equity and drawdown halt persist until authorized reset.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Execution policy clarifications
The approved ADRs remain unchanged. The initial additive implementation pins these explicit configuration semantics; no default production thresholds or active-account migration are introduced:
- Quantity units for order/position limits; base-currency amounts for symbol/gross exposure, daily loss and explicitly named maximum drawdown amount. Commission is an immutable Rust rate in [0, 1], calculated from exact quantity × price × rate and rounded once at eight places.
- Pending buys reserve fee-inclusive cash at the canonical mark (market) or max(mark, limit). Pending sells reserve owner inventory, never anticipated buying power; their fill proceeds fund fees. Pending sells do not offset buy exposure. Actual fills recheck other commitments and the remainder, including split-fill rounding. Unaffordable remainder rejects/releases without resizing or borrowing.
- Increasing risk requires fresh non-future canonical marks across held and pending assets, using explicit engine event time and a configured maximum mark age. Reductions still enforce inventory/funding/order-size rules. Daily and drawdown halts latch on marked loss; explicit account boundaries reset only daily state, including when retained marks are old. Same-session repetition cannot rebase, and future/backdated boundaries reject.
- A private-owned Ledger facade is the only canonical risk entry point. Normalized explicit-order and target-derived admission share one policy; actual target expansion, mode enforcement, matching, venue expiry scheduling and replay remain F05/F06. Resource-release hooks are not a second matcher.
- Operator reset is a separate host-held capability with recorded reason/baseline, absent from strategy inputs. This is API authority separation, not authentication or an untrusted-code sandbox. F07 must expose only the risk-governed facade; later host/auth adapters must enforce their own authority.
- Checkpoints validate reservations, risk state and recorded outcomes by deterministic reconstruction. They do not authenticate an attacker-modified history and are not full replay/strategy/RNG or SQL recovery snapshots. Normal transitions must not copy/replay the entire retained history.
## Likely files and ownership
- apps/stock/engine/src/risk/mod.rs (reference only during additive implementation)
- apps/stock/engine/src/financial/risk.rs (new)
- apps/stock/engine/src/financial/ledger.rs
Write locks: rust-ledger, risk-policy. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [F02](F02.md) integrated.
Architecture decisions: ADR-002, ADR-003. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- No accepted order/fill creates negative available cash or an unsupported short.
- Pending/partial orders reserve resources once and release on cancellation/rejection/expiry.
- Stale marks block risk increases; marked losses halt increases even without realized trades; reductions remain possible.
## Mandatory tests
- competing_reservations, adverse_gap_reject_remainder, stale_other_symbol, marked_loss_halt, explicit_risk_session_boundary.
- drawdown_halt_survives_rollover_restore, unauthorized_reset_denied, alternate_venue_does_not_reset_account_day.
- Property test raw order and target paths cannot bypass the same policy.
- Partial-fill quantum rounding, zero-cash funded sell, pending sells do not credit buy exposure, stale/future other pending symbol, wrong-owner sell/cancel, accepted/rejected command replay and conflicting reuse, same-session no-rebase, future/backdated boundary rejection, restored reservation tamper and overflow atomicity.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,76 +0,0 @@
# F05 — Unify matching and order lifecycle on the ledger
Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Rust execution semantics.
Scheduling source of truth: [manifest entry F05](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-01 — Verified:** Both execution paths can act on a completed bar and fill against its current close; this is not a defensible default bar-close policy. [apps/stock/engine/src/backtest/engine.rs:249](../../../../apps/stock/engine/src/backtest/engine.rs#L249); [apps/stock/orchestrator/src/services/ExecutionService.ts:224](../../../../apps/stock/orchestrator/src/services/ExecutionService.ts#L224).
- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114).
- **FIN-06 — Verified:** Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure. [apps/stock/engine/src/backtest/engine.rs:374](../../../../apps/stock/engine/src/backtest/engine.rs#L374); [apps/stock/engine/src/backtest/engine.rs:414](../../../../apps/stock/engine/src/backtest/engine.rs#L414).
- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151).
## Intended behavior and implementation scope
Implement pure matcher/order-transition functions over explicit execution events; replay scheduling belongs to F06. Market/limit orders use declared spread/slippage and available liquidity, with no future-bar fields. Retain DAY/GTC/IOC/FOK semantics needed by the existing paper path; unsupported stop/OCO types reject. Target mode and explicit-order mode are mutually exclusive for one strategy instance in v1. Repeated absolute targets account for owned holdings and outstanding commitments; replacements cancel only owned orders.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Execution policy clarifications
The initial component remains additive and Rust-only, privately owning F04 RiskAccount; no mutable risk/ledger escape hatch, parallel accounting, legacy engine or NAPI cutover. F06 derives and schedules events/calendars; F07/S01 supply actual strategy barriers. This task consumes explicit host inputs and proves component behavior.
- Event eligibility uses availability time, phase, instrument and source sequence plus the pinned execution-series identity. Reject prior/observed execution keys; adjacent next-open at the same timestamp may be eligible under zero latency. Configured latency delays eligibility. No retroactive decision insertion into consumed execution phases. Open events cannot carry future OHLCV. A bar has one shared capacity pool across sides/owners; quotes have explicit bid/ask capacity. Only accepted fills consume it.
- Physical quote time is separate from delivery/availability time. Preserve it on marks and require it to be at or after order readiness: late delivery cannot fill an order that did not yet exist. Ineligible old quotes do not consume IOC/FOK opportunities. Explicit open time must match its execution key; F06 must skip/reject missed opens rather than freshen them.
- Deduplicate physical opens by instrument/open time and quotes by instrument/observation time/source sequence, independently of delivery key. Exact-key retries return receipts; changed-key redelivery of the same physical event rejects without minting capacity. Do not assume source sequences increase chronologically; distinct quotes sharing a millisecond remain possible.
- Pin relative half-spread and slippage rates in [0, 1). For bar opens, derive fixed-eight-place executable bid/ask first; then apply adverse slippage at another declared posting boundary. Quotes already include spread. Limits must cross the executable quote before slippage; qualifying prices are clamped to the limit, never filled through it. Quote financial marks use an exact once-rounded midpoint. F04 alone computes fees and funding.
- DAY binds an explicit open venue session and expires at its close; account risk-session reset is separate. IOC/FOK use their first eligible opportunity: IOC cancels remainder; FOK fills the whole remainder once or cancels without fills/fees. Unknown/zero liquidity cannot fill. GTC survives venue closure; run termination cancels without invented liquidation.
- Registered strategy mode is fixed. Each listed target is an absolute owner quantity; omitted instruments are unchanged, duplicate entries reject, and explicit zero closes that instrument. Holdings plus signed outstanding commitments determine unchanged targets. Changed targets cancel only that owner's instrument commitments before recomputing; if replacement risk rejects, cancellation remains a recorded outcome.
- Owners use stable configured identity order and each decision preserves its explicit intent/target array priority. Sparse target updates are not an atomic portfolio rebalance: earlier entries can reserve cash before later entries release commitments. No anticipated sell proceeds or hidden release-all reordering.
- Preflight structural errors across the entire submitted batch/event before mutation. Generated IDs encode tuples unambiguously. Exact repeated events/decisions return original receipts without refilling capacity or replaying effects; conflicting identity reuse rejects. Checkpoints retain order state, priority, identity/cursor/session state and F04 state.
- Decision admission uses one coordinator revision for the shared portfolio/order/reservation view. This token is distinct from the nested economic-only FinancialSnapshot ledger revision; F07 must expose the coordinator token for submitting a batch. No wire shape or TypeScript financial arithmetic changes here.
- A later internal numeric failure after successful subtransitions is a terminal failed-attempt receipt containing the ordered committed prefix, not a retryable generic error or successful event. All further mutations refuse; restore preserves failure. F06/F07 must discard failed attempts and never publish successful results. This keeps individual F04 transitions atomic without whole-account/history cloning or a second rollback engine.
## Likely files and ownership
- apps/stock/engine/src/financial/matching.rs (new)
- apps/stock/engine/src/backtest/engine.rs (reference only during additive implementation)
Write locks: rust-matching, financial-contract. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [F04](F04.md) integrated.
Architecture decisions: ADR-003. Agents may not independently amend their policies.
Feature activation/release gates: [F06](F06.md). These do not block implementing or integrating this component against its own tests.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Given an already-eligible execution event, market/limit price protection, volume sharing, partial fill, rejection/cancellation and expiry are deterministic.
- IOC cancels remainder; FOK either fills fully or does not fill/charge; DAY accepts only in-session; target-generated GTC survives a session boundary.
- Same owner/instrument repeated target after partial fill does not duplicate quantity; mixed target/explicit mode rejects; another owner's order cannot be cancelled.
- Pure eligibility tests reject prior/same observed event keys. Full next-open ordering is an F06 release gate, not a hidden F05 implementation requirement.
## Mandatory tests
- matcher_gap_limit, shared_volume_capacity, partial_cancel, IOC_remainder, FOK_atomicity, DAY_expiry, target_GTC_replace.
- unchanged_target_no_duplicate, mixed_intent_mode_rejected, wrong_owner_cancel, ineligible_event_key_rejected.
- Adjacent-open/positive-latency eligibility, same quote/key conflict, pinned execution series, unknown/zero capacity, risk rejection preserves shared capacity, later invalid batch member is atomic, terminal numeric failure records prefix and survives restore, partial-fill/target replay and omitted-target semantics.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,71 +0,0 @@
# F06 — Implement deterministic replay once, with linear historical traversal
Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Rust deterministic replay.
Scheduling source of truth: [manifest entry F06](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-01 — Verified:** Both execution paths can act on a completed bar and fill against its current close; this is not a defensible default bar-close policy. [apps/stock/engine/src/backtest/engine.rs:249](../../../../apps/stock/engine/src/backtest/engine.rs#L249); [apps/stock/orchestrator/src/services/ExecutionService.ts:224](../../../../apps/stock/orchestrator/src/services/ExecutionService.ts#L224).
- **DAT-01 — Verified:** Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. [libs/core/types/src/historical-data.ts:90](../../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L177).
- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194).
## Intended behavior and implementation scope
Implement the replay cursor once: sorted immutable events with stable availability/phase/instrument/sequence ordering; add a small pending-event queue only where required. Absorb P02's nonquadratic load and disabled-by-default hot-loop trade logging. Generate open-only execution events from one designated execution series; feature-only frames do not add liquidity or undeclared decision triggers. Publish completed observations, evaluate declared decision barriers, then next-interval opens under recorded zero/nonzero latency policy.
Consume F05's explicit event contract without reconstructing a second matcher: quote observation time is not delivery time, and eligibility requires an order to be ready by physical quote time. Open time must equal its execution key; skip/reject missed opens, never relabel them as newly occurring. Decision admission uses the coordinator's shared portfolio/order revision, distinct from the nested economic ledger revision. Terminal F05 failures retain diagnostic prefixes but must fail/discard the replay attempt, never produce successful performance results.
## Execution handoff clarifications
- Add an internal prepared-input cursor over MatchingAccount, not a second public session API or a legacy-runtime cutover. D01 currently has bar datasets only: reject quote-mode replay input until a quote dataset contract exists. Existing F05 quote tests remain relevant matcher evidence, not a claim of quote replay support.
- Accept typed prepared bars with canonical decimals and retained session boundaries. Document that F07 must verify/adapt the frozen D01 snapshot; do not duplicate the TS normalizer/hash algorithm. Validate executable-series/config agreement, raw execution prices, bounds and eligibility; retain exploratory limitations. Bind checkpoints to the exact prepared input/config, not only a caller-supplied dataset label.
- Initialize using true venue open times, including the preceding open for a mid-session warmup/start. Never restamp missed opens. Publish late observations without regressing authoritative mark time; capacity uses the physically latest completed available execution-series volume, not latest arrival or future volume.
- Resolve feature-series sequence ties with stable series identity. Only declared cadence triggers decisions; due owners share one immutable context/revision. Warmup cannot trade; observations at tradeEnd may mark only; later observations are unavailable.
- Internal barrier/cursor/checkpoint and fixed decision-trace replay belong here. Public NAPI session protocol, frozen dataset transport, TS strategy state/RNG and strategy recomputation belong to F07/S01. Prefer offset-based observation prefixes to copying all history on every advance.
- Sorting may be O(n log n); traversal is linear plus matching/risk work. Measure 1k/10k/100k release workloads with economics equality and explicit load/replay timing. This is a canonical Rust component measurement, not TS callback or end-to-end research throughput.
- Existing F04/F05 policy evaluates risk after each mark. Equal-time cross-asset marks are applied in deterministic instrument order, not atomically: an intermediate portfolio value can latch a loss/drawdown halt even when the final same-time valuation recovers. Pin this behavior with a permutation regression and disclose it as a modeling limitation. Do not implement an F06-local risk bypass or silently introduce atomic marking; changing that economic policy requires coordinated approval and fixtures.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/engine/src/backtest/engine.rs
- apps/stock/engine/src/backtest/mod.rs
- apps/stock/engine/src/financial/replay.rs (new)
Write locks: rust-replay. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [F05](F05.md), [D01](D01.md), [P01](P01.md) integrated.
Architecture decisions: ADR-003. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Permuting file arrival order does not change economic results after canonical event ordering.
- Daily observations remain unavailable before session close; different symbols retain their actual quote timestamps.
- Multi-timeframe context includes only completed available bars and marks missing/stale inputs explicitly.
## Mandatory tests
- adjacent_open_zero_latency, positive_latency_skips_open, future_ohlcv_does_not_change_open_fill, daily_close_target_survives_to_open.
- feature_timeframe_does_not_duplicate_liquidity, equal_timestamp_symbol_permutation, warmup_cannot_trade, stale_mark_timestamp_preserved.
- Replay/restore trace equality. Extend P01 with1k/10k/100k release-build load/replay scaling; preserve economics before accepting faster runs.
- Delayed older observations do not regress marks/capacity; mid-session starts retain true session boundaries; terminal observations are mark-only; equal-time feature-series sequence ties are stable; altered input/config checkpoint restore rejects.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,78 +0,0 @@
# F07 — Expose bounded Rust step sessions through existing NAPI workers
Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Rust/TypeScript integration.
Scheduling source of truth: [manifest entry F07](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114).
- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
## Intended behavior and implementation scope
Expose a small pull session (load/create/advance/submit/finalize/dispose) in the existing worker, backed by the same financial kernel. advance returns a tagged union: progress, decision batch, or complete. For a decision batch, all due strategies receive the same immutable financial view; collect all decisions before ordered admission. The submission token is F05/F06's coordinator admission revision, not the nested ledger snapshot revision (reservations and order state can change without an economic posting). Use one native test strategy/intent trace for conformance, not a port of every Rust built-in. Per-session dataset load once; cross-trial residency is P03.
F06 consumes internal typed prepared bars/session tables, not an independently authenticated D01 snapshot. This adapter must verify the frozen v2 dataset with the existing normalizer/hash verifier, preserve its hash/eligibility/limitations, convert numeric fields through canonical decimal ingress, and map exact calendars/execution series/bounds into F06. Do not trust a supplied hash label alone or reconstruct a competing normalizer. Quote replay stays unsupported until its dataset contract is explicitly added. Retain prefix-only strategy contexts; do not expose native full-dataset/checkpoint host handles to strategy callbacks.
Expose recorded model limitations, including F06's explicitly unsupported abutting venue sessions and F04/F05's sequential equal-time portfolio marks (intermediate valuations can latch risk halts). An event budget bounds event count, not wall time or the cost of an individual matching transition. These are not promises of atomic multi-asset valuation, arbitrary-calendar support or constant-latency cancellation.
## Execution handoff clarifications
- Add a separate NAPI FinancialReplaySession and a fixed-intent-trace request variant in the existing worker. Keep the legacy run request and durable runner default unchanged. The trace path is for conformance/debugging, not a declarative strategy language or S01 strategy runtime.
- Verify frozen D01 inputs inside the worker before native creation; native prepared input remains a trusted host boundary, not independent proof of a supplied dataset hash. Convert represented numeric values to plain decimal strings, expanding scientific notation and rejecting precision/range loss rather than silently rounding.
- Pin a strict version/session/dataset envelope and validate response identities. Emit prefix observation deltas and one shared financial/order/risk view; never pass full prepared data/checkpoints to a callback or clone retained checkpoints in the hot loop. A small read-only F06 range accessor is permitted; replay and risk semantics are not changed.
- Permit a test-only include of the new adapter from the financial test module: the crate excludes its API module from ordinary unit builds. Exercise the production host/direct-Replay parity without enabling unrelated legacy NAPI wrappers or changing production module direction. The thin exported wrapper delegates one-to-one to that host and is separately tested through the built addon.
- The conformance loop may evaluate fixture callbacks in varied order, but submits the complete due-owner batch once. Callback failure fails/disposes the attempt; no partial submission or later successful finalization. Production strategy state/RNG, artifact imports and durable canonical cutover remain S01/R05.
- Preserve existing process supervision: one process/request, hard cancellation, wait for close after a result, rejection after abort, failed worker reuse and stale attempt protection. Run existing runner cancellation/lease regressions, including the disposable PostgreSQL suite at integration.
- Extend the existing P01 harness with actual session preparation/load, advance/submit call timings and counts, context/delta bytes and finalization. Calls include real Rust/serialization work; do not label them empty crossings or end-to-end strategy throughput.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Likely files and ownership
- apps/stock/engine/src/api/replay.rs (additive session; existing backtest API unchanged)
- apps/stock/engine/src/financial/replay.rs (read-only published-observation range accessor only)
- apps/stock/orchestrator/src/backtest/native-replay.ts
- apps/stock/orchestrator/src/contracts/native-replay.ts (schema-only boundary)
- apps/stock/orchestrator/src/backtest/native-worker.ts
- apps/stock/orchestrator/src/backtest/native-worker-protocol.ts
- apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts
- scripts/benchmark-research.ts and focused native/worker fixtures
Write locks: native-public-api, worker-protocol. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [F06](F06.md), [C02](C02.md) integrated.
Architecture decisions: ADR-004. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- TS caller handles every step variant; it never assumes each advance returns a decision. Progress/cancel boundaries remain bounded.
- All due decisions reference one barrier revision. Reversing callback evaluation order cannot change output when contexts/states are unchanged; final admission uses declared owner priority.
- No partial barrier is committed if a decision throws. Rust returns per-intent accepted/rejected outcomes; business rejection is not a rollback of the observed decision event.
- Native conformance intent trace and TS fixture use identical financial transitions. Native built-in production strategy parity is not required.
- Worker crash/cancel/lease loss cannot publish successful stale results; snapshot/ID/version mismatches reject.
## Mandatory tests
- step_tagged_union, immutable_barrier_revision, reverse_callback_order, decision_exception_aborts_barrier, rejected_intent_is_committed_outcome.
- Existing native-worker/runner cancellation and lease tests; extend P01 with step and context-byte timings.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,135 +0,0 @@
# F08 — Publish canonical metrics and versioned result projections
Parent epic: E2. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Quant analytics/Rust integration.
Scheduling source of truth: [manifest entry F08](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-07 — Verified:** Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. [apps/stock/engine/src/backtest/simple_results.rs:374](../../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../../apps/stock/engine/src/backtest/simple_results.rs#L542).
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
- **Verified reusable analytics:** [reviewed return statistics](../../../../libs/calculations/src/analytics/return-statistics.ts#L24) already separate statistical reporting from financial execution.
## Intended behavior and implementation scope
F09 now supplies the independently deliverable compact terminal/owned-fill projection. F08 consumes it and adds historical sampling/statistical reporting; do not duplicate its native transport work. F09 is not completion of this story.
Use canonical Rust ledger postings, owned fills, occupied intervals and session-ending marks as the sole financial inputs. Reuse reviewed TypeScript statistical functions in `libs/calculations/src/analytics/` for return ratios and reports; do not port them to Rust merely for language uniformity. Add a small adapter for the engine-declared session calendar rather than blindly regrouping every venue by UTC date.
Version economics and metrics independently. Define sampling, annualization, benchmark and risk-free conventions in the result policy. Missing benchmark/risk-free inputs must not silently become invented measurements. Undefined or unsupported metrics are null with reasons. Add a reusable canonical analytics DTO alongside the existing result types; R05 owns persisted/public-result cutover. Do not coerce owned financial facts into incompatible legacy position/round-trip fields or rewrite old rows.
Measurable benefit: comparable, independently checked rankings without a second ledger or a needless analytics rewrite.
Before implementation, pin reporting-only conventions in the handoff: account boundaries currently execute before equal-time observations and are not automatically close-equity samples; partial final sessions must be explicit; exposure needs a declared elapsed/venue-time denominator; the reviewed statistics currently assume 252 periods and default to 2% risk-free, so the adapter must pass a supported explicit policy and diagnose omitted inputs. These choices must not alter financial event ordering or risk semantics. Fills are not round trips.
## Exclusions
No accounting/fill recomputation in TypeScript, statistical library rewrite, forced native port, new service, or silent reinterpretation of historical results. Native analytics remain an option only if measured as a bottleneck.
## Likely files and ownership
- apps/stock/engine/src/financial/result.rs and replay reporting hooks (canonical outputs; legacy simple_results.rs remains separate)
- apps/stock/orchestrator/src/backtest/native-result.ts
- apps/stock/orchestrator/src/backtest/BacktestReport.ts
- libs/calculations/src/analytics/return-statistics.ts
- libs/calculations/src/analytics/equity.ts (review existing UTC grouping; use explicit session marks)
- libs/core/types/src/backtest-run.ts
Write locks: result-contract, native-public-api, replay-reporting, canonical-analytics, calculation-statistics. One owner controls the Rust/native reporting contract. A separate analytics owner may implement disjoint shared types/calculations/adapter files after root pins the contract; consume the exact accepted schema before integration. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [F06](F06.md) and [F09](F09.md) integrated.
Architecture decisions: ADR-002, ADR-003. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Fees/P&L/equity/trades reconcile to Rust outputs; session returns include the final session and use the declared risk-session/calendar policy.
- Sharpe uses periodic excess-return mean/std; Sortino uses downside deviation relative to the declared target; zero-variance/undefined cases are null with reasons.
- Exposure uses the union of occupied intervals; open positions count; attribution distinguishes fills and round trips.
- Reviewed calculation functions are reused where their conventions match. Any deliberate difference has a versioned policy and independent arithmetic fixture, not an unexplained second formula.
- The additive canonical analytics DTO preserves nullable/unsupported metrics and fill ownership without invoking legacy percentage conversion. Existing result mapping and frontend fixtures remain unchanged and pass. Persisted canonical rows/public DTO conversion remain R05; this story does not enable canonical web runs.
- Preserve the sequential equal-time marking policy and its material risk limitation in result provenance: intermediate valuations may latch halts despite a recovered synchronized value. Do not report such traces as atomically marked portfolio risk. Before canonical multi-asset default cutover, apply R05's explicit owner policy-review gate; component F06 acceptance does not satisfy it.
## Mandatory tests
- two_session_marks, constant_negative_returns, zero_variance, overlapping_positions, open_position_exposure.
- Existing result mapping and frontend metric unit fixtures; documented independent arithmetic cross-check.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Execution contract — 2026-10-23
Owner instruction: commit accepted F09/P07 and continue the backlog. F09/P07 are committed in `e3bd722`; F08 is the next code/ADR-ready story. These are reporting conventions, not changes to approved financial/risk policy.
### Native financial reporting owner
- Keep `Replay.events`, event indexes/IDs, `ReplayConfig`, `ReplayCheckpoint`, all financial receipts and existing trace/projection wire output unchanged. Add a small private reporting accumulator; restore already replays the retained decisions and must rebuild identical reporting facts without a new checkpoint schema.
- Periods follow the initial account risk session plus declared risk boundaries. Clip to `[tradeStart, tradeEnd]`; never infer UTC or asset venue days. At each boundary, sample the preceding period after **all** equal-time Observation events, before Decision/Execution. Risk reset still occurs in its existing earlier phase. Initial equity comes from Rust, and terminal equity is always retained.
- First periods clipped by tradeStart have `partialStart`; final periods without a declared closing boundary at tradeEnd have `partialEnd`. An exact terminal boundary emits one preceding period, not a zero-length new period. Retain partial returns/history but exclude them from full-period statistics. Last available marks remain explicit; do not claim freshness or atomic portfolio risk.
- Exposure is the union of account occupancy intervals over elapsed calendar time, including overnight/weekends. Observe actual non-replayed committed fills, then use existing `Ledger::owned_quantities().next().is_some()`; no quantity reconstruction. Merge adjacent intervals, omit zero-length intervals, and clip open holdings at tradeEnd for measurement only. No synthetic closing fill. Encode `occupiedMs`/`elapsedMs` as canonical nonnegative integer strings to preserve durations spanning the supported timestamp domain.
- Sampling failures must not reorder or mutate financial transitions or overwrite a financial failure. Report access rejects incomplete/failed/disposed or unavailable reporting state.
- Add native `report(identityJson)` beside unchanged `finalize()`/`project()`. Wire output is `format: "report"`, `reportingVersion: 1`, `projectionVersion: 1`, `financialVersion: 1`, the existing provenance/view/limitations and financial `projection`, plus `reporting` below. Keep reporting outside strategy contexts.
```ts
reporting: {
calendarId: string;
calendarRevision: string;
tradeStart: number;
tradeEnd: number;
initialEquity: FinancialDecimal;
sampling: 'account-boundary-after-observations-v1';
exposureBasis: 'elapsed-calendar-time';
sessions: {
session: RiskSessionIdentity;
periodStart: number;
periodEnd: number;
partialStart: boolean;
partialEnd: boolean;
equity: FinancialDecimal;
}[];
occupiedIntervals: { start: number; end: number }[];
occupiedMs: string;
elapsedMs: string;
}
```
- Extend the same TS native session/conformance/worker path with explicit `resultFormat: "report"`, strict parsing and captured format/identity/policy guards. Old omitted/trace/projection behavior and hashes stay stable. Root accepts the schema before the analytics consumer integrates it.
### TypeScript analytics owner
- Add application-independent `CanonicalBacktestAnalytics`/policy types adjacent to `BacktestRunResult`, without widening/reinterpreting the legacy DTO. One orchestrator adapter composes `{ financial: ReplayReportResult, analytics: CanonicalBacktestAnalytics }`.
- Adapter input requires policy version 1, positive finite `periodsPerYear`, explicit finite `annualRiskFreeRate` or `null`, and `benchmark: null`. Benchmark-dependent metrics are unavailable in v1; reject unsupported benchmark input. Output policy also records the fixed conventions, calendar identity and units. These are recorded conventions, not new configurable switches.
- Compute ratios from authoritative equity samples only. Include every session return, including partial terminal periods, with eligibility flags. Use only complete periods with defined positive baselines for periodic statistics; do not silently discard undefined full-period returns to create a different sequence.
- Reuse reviewed `returnStatistics`, equity/drawdown helpers and primitives. Extend `returnStatistics` minimally with explicit periods/year and nullable risk-free input, preserving old defaults for existing callers. Missing risk-free input leaves volatility/tail statistics available but target-dependent ratios/downside deviation null. Sample standard deviation uses n−1; downside RMS uses all n observations relative to annualRiskFreeRate/periodsPerYear. Exactly constant finite input has zero deviation; no arbitrary epsilon.
- Drawdown is explicitly session-end/terminal-sampled, not maximum intraday drawdown. Total return uses initial-to-terminal equity; CAGR may use actual elapsed calendar time with the fixed 365-day-year convention, including partial endpoints. This does not treat a partial period as a complete session. Zero/nonpositive baselines and nonfinite/undefined results produce null with reasons.
- Reuse a narrowly extracted drawdown-only helper instead of invoking unused UTC Date grouping, since native safe-integer timestamps exceed JavaScript Date's range. Positive initial equity and elapsed time with terminal equity zero has CAGR −1; negative terminal equity remains unsupported. Pin both edge cases with independent tests. Policy must state that marks are last available and per-session freshness is not certified.
- Report `fillCount` separately. Round-trip count/win rate/profit factor/average win/loss are unsupported/null; no inferred trade grouping, position marks, average cost or financial postings. Preserve exact Rust financial facts in the composed report.
- Keep legacy `BacktestReport`, normalization, stored-row mapping and UI unchanged. R05 will consume this additive contract during its separately gated persistence/public-result migration. Existing compatibility tests must pass.
### Required additional validation
- Rust: boundary sample after observations versus unchanged earlier risk reset; equal-time sequential risk halt still latched; first/final partial periods and exact terminal-boundary deduplication; exposure overlap/open positions/same-time owner handoff; no trade/stale marks; restore after every event including within observation groups; unchanged financial checkpoint/trace/project results.
- TS/native: report format/identity/calendar/terminal-value validation; worker format/cancellation/failure guards; two sessions 100 → 110 → 99 yield +10%/−10%; partial returns retained but not annualized as full sessions; missing rates/benchmark; constant negative and nonbinary constant returns; unsupported round trips remain null; genuine zero exposure survives the additive adapter.
- Run existing calculation, mapping and frontend metric/provenance fixtures, full repository checks and scoped strict test TypeScript. Worker changes require disposable PostgreSQL/Redis recovery gates. Measure reporting overhead against the accepted compact path with identical economic hashes; no timing assertions, new cache/DSL, journal deletion, or unrelated hot-loop optimization.
## Reviewed implementation handoff — 2026-10-23
Implemented in `financial/reporting.rs` and replay hooks, native `FinancialReplaySession.report()`, the existing TS native/worker contract, additive `CanonicalBacktestAnalytics` types and `backtest/canonical-result.ts`. Existing reviewed calculations supply statistical reporting; no legacy DTO or default runner cutover.
Independent review, exact owner-source integration, repository gates, disposable recovery and release-format comparisons passed. Full check initially found an incomplete decision trace in the new integration fixture; the corrected test explicitly submits every due hold and passes. See [wave handoff](../../ROADMAP.md#thirteenth-wave-execution--2026-10-23) and the canonical manifest validation record for commands, counts, hashes, initial unfavorable timings and the unchanged-artifact control. New implementation remains uncommitted.
R05 must consume the additive contract without filling unsupported round-trip/benchmark statistics or legacy position fields with invented values. S01 does not need another reporting contract. Long-session statistical throughput remains unmeasured; the six benchmark fixtures each contain one partial account period.

View file

@ -1,48 +0,0 @@
# F09 — Return compact canonical replay projections
Parent epic: E2. Priority/severity: P1 / High. Complexity: M. Specialist: Rust/TypeScript financial integration.
Story: As a researcher, I can obtain authoritative terminal holdings, P&L and actual fills without serializing the complete nested execution journal, while retaining full diagnostics when needed.
Scheduling and ownership: [manifest F09](../manifest.json). This is the independently deliverable projection portion of F08, not a replacement for its historical metrics.
## Evidence and root cause
- **PER-01 / KEEP-02 — Verified:** [full native finalization](../../../../apps/stock/engine/src/api/replay.rs#L165) exports every nested matching receipt through a JSON value tree. The recorded F07 release workload emits 66.7MB/103.6MB at 10k total bars; finalization averages 0.963s/1.377s, approximately 35–39% of trial time. This is conformance output, not useful minimal research output.
- **FIN-05 — Verified:** [Ledger::valuation](../../../../apps/stock/engine/src/financial/ledger.rs#L674), [FinancialEffect](../../../../apps/stock/engine/src/financial/contract.rs#L327) and existing ledger receipts already contain authoritative terminal values, realized basis/P&L, actual fees and ownership. Recomputing these in TypeScript would create competing financial authority.
## Scope and pinned contract
- Add a small Rust projection module. Emit the existing terminal snapshot/view, checked Ledger valuation and owner contributions, plus flattened actual fills copied from committed commands/effects in authoritative order. Retain IDs, event time, owner/decision/order/fill, side/quantity/price, fee, cash/quantity deltas, released basis and realized gross P&L. Fills are not completed round trips.
- `cashDelta` preserves the ledger effect's gross notional movement; the fee is a separate posting, not an additional fee already included in that delta. Valuation owner contributions include reserve capital and can be negative. Schema coherence checks compare the returned cash/equity strings with the existing view without reproducing accounting arithmetic.
- Iterate borrowed ledger receipts once, skipping replay-labelled aliases. A read-only ledger receipt accessor and serialization derives for existing valuation types are allowed. No checkpoint cloning, ledger reconstruction, replay or financial arithmetic duplication to produce output. Preserve internal receipts, idempotency indexes and restore behavior.
- Add native `project(identityJson)` beside the unchanged full diagnostic `finalize(identityJson)`. Compact output has `format: "projection"`, `projectionVersion: 1`, `financialVersion: 1`, the same identity/status/manifest/policy/view/limitations, and `projection: { valuation, fills }`; it has no nested `receipts`. Use typed serialization with borrowed metadata where practical.
- TS adds a strict projection parser and typed `NativeReplaySession.project()`. The existing conformance loop may select `resultFormat: "projection" | "trace"`; old omitted-format calls and the existing diagnostic parser retain their trace behavior. No second loop. New compact consumers explicitly select projection; active legacy/durable defaults do not change.
- The existing fixed-trace worker request may carry the optional format; the parent captures expected format with identity/policy and rejects mismatched responses. Both formats share completion, failure, disposal and cancellation guards.
- Extend observational metrics with finalization native-call time (including Rust work/serialization), JSON decode time, schema-validation time and disposal time. Keep these outside economic outputs and deterministic hashes; do not call them pure crossing measurements. Expose unavailable internal Rust/GC splits honestly.
## Exclusions
No session-close equity curve, return ratios, Sharpe/Sortino, exposure percentage, round-trip win rate, invented defaults or legacy DTO coercion: these remain F08. No journal deletion/compaction, new accounting, risk/timing changes, new persistence/service, pagination, DSL, cache or default engine/paper/live cutover.
## Files and ownership
- `apps/stock/engine/src/financial/result.rs` and tests; `ledger.rs` read-only accessor/valuation serialization; module registration.
- `apps/stock/engine/src/api/replay.rs` and generated binding verification.
- `apps/stock/orchestrator/src/contracts/native-replay.ts`, `backtest/native-replay.ts`, existing worker supervisor/dispatch as needed.
- Focused native/projection/worker fixtures and tests. Benchmark files belong to P07; root coordinates final paired comparisons.
Write locks: financial-projection, native-public-api, worker-protocol, result-contract. One owner. Dependencies: F07; approved ADR-002/003/004. P07 baseline work is independent; benchmark integration uses the frozen projection contract, not concurrent reinterpretation.
## Acceptance and mandatory tests
1. `compact_full_financial_parity`: terminal snapshot/valuation/flattened fills agree with the retained full trace and independent hand-calculated fixtures; all amounts remain canonical decimal strings.
2. `projection_aliases_once`, `partial_fill_projection`, `two_owner_projection`: duplicate command/fill aliases do not duplicate output, partial fills remain distinct, owner attribution and fees reconcile, including final residual basis. No-trade output has zero fills and honest terminal values.
3. `projection_is_read_only`: repeated project/finalize calls preserve state/checkpoints and original diagnostic output; restored sessions produce the same projection. Full-trace fixture hashes remain unchanged.
4. `projection_terminal_guard`, `projection_identity_policy_format`: incomplete/failed/disposed sessions cannot return successful compact output; malformed identities, policies and requested formats reject, including worker races/cancellation and post-result abort.
5. Strict TS/schema/architecture/native gates pass. No receipt/future-data leakage into strategy contexts; no broadening of worker-only native reachability.
6. Paired release measurements on the same frozen dataset/config/decisions show identical financial projection hashes and reduced output bytes/finalization cost. Preserve full trace as an explicit diagnostic oracle. Record actual before/after; no timing threshold in CI and no promised speedup. P07 supplies representative workload variants.
Regression risk: alias double counting, effect-to-fee mispairing, silently changed output semantics or a successful result from failed state. Review G1/G2 independently; retain existing F07 regressions and disposable worker/runner durability gates. Rollback is additive API deployment, not weaker financial policies.
Definition of done: reviewed source, exact integrated test/benchmark evidence and canonical manifest handoff. No commit/push/PR without separate authorization.

View file

@ -1,55 +0,0 @@
# O01 — Serialize additive schema migrations safely
Parent epic: E9. Priority/severity: P1 / High. Relative complexity: S. Recommended specialization: PostgreSQL/backend infrastructure.
Scheduling source of truth: [manifest entry O01](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **OPS-01 — Verified:** Migration runner uses an explicit safe allowlist; adding SQL alone will not run it. Concurrent migration admission lacks an advisory lock. [apps/stock/web-api/src/migrations/migration-runner.ts:42](../../../../apps/stock/web-api/src/migrations/migration-runner.ts#L42); [apps/stock/web-api/src/migrations/migration-runner.ts:57](../../../../apps/stock/web-api/src/migrations/migration-runner.ts#L57).
## Intended behavior and implementation scope
Preserve the explicit reviewed additive allowlist. On one PostgreSQL transaction client, acquire a transaction-scoped advisory lock BEFORE migration table initialization, migration discovery/check, SQL apply and recording. Do not lock via an arbitrary pooled query or add a migration framework. Integrator allocates additive filenames; applied scripts remain immutable.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- apps/stock/web-api/src/migrations/migration-runner.ts
- database/postgres/init/
- test/postgres/ (migration tests)
Write locks: sql-migrations. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
No code prerequisite. Global execution approval and write-lock acquisition still required.
No additional economic-policy approval is needed for this narrowly scoped task.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Two API startups apply each new migration once without duplicate object errors.
- Upgrade from current schema preserves runs, datasets, execution ledger and checkpoints.
- Destructive init scripts cannot enter startup migration discovery.
## Mandatory tests
- two_concurrent_startups_same_client_lock, precheck_inside_lock, migration_failure_rollback, destructive_init_excluded.
- bun run test:postgres on disposable fixtures only; existing migrations/data retained.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,76 +0,0 @@
# O02 — Expose truthful research and paper readiness diagnostics
Parent epic: E9. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Infrastructure/observability.
Scheduling source of truth: [manifest entry O02](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **OPS-02 — Needs Investigation:** Paper/live operational readiness is not demonstrated end-to-end. Live is deliberately disabled; preserve that gate until feed, reconciliation and broker-specific recovery are verified. [apps/stock/orchestrator/src/core/ModeManager.ts:33](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L33); [apps/stock/orchestrator/src/container.ts:152](../../../../apps/stock/orchestrator/src/container.ts#L152).
- **WEB-02 — Verified:** Detail exposes native-unsupported pause/resume controls, omits cancel wiring, and overlapping polling/selection can apply stale responses. [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:379](../../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L379); [apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts:160](../../../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts#L160).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
## Intended behavior and implementation scope
Report actual worker/queue/lease, engine version/capability, dataset load failure, paper feed freshness and recovery/halt state. Replace unmeasured zeros/always-healthy assumptions with unknown/unavailable. Attach run/attempt/strategy IDs to diagnostics; avoid a new telemetry stack.
Measurable benefit: Makes failures diagnosable from the primary product.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- apps/stock/web-api/src/routes/monitoring.routes.ts
- apps/stock/web-api/src/services/
- apps/stock/orchestrator/src/api/rest/
- apps/stock/web-app/src/features/monitoring/
Write locks: readiness-api. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [S04](S04.md) integrated.
No additional economic-policy approval is needed for this narrowly scoped task.
Deferred: Optional cross-service monitoring expansion; required run diagnostics belong to W01/F07 and paper readiness to S04.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Missing orchestrator/native worker/DB or stale feed cannot report ready.
- Run failure includes phase and actionable cause, with secrets excluded.
- Research availability and paper readiness are separate indicators; live-disabled is explicit.
## Mandatory tests
- dependency_unavailable_readiness, stale_feed_status, failed_attempt_diagnostics, no_secret_logs.
- API/UI tests show unknown versus measured zero and retryable error.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: Extend current health/monitoring and run diagnostics contracts; no separate monitoring API silo.
- Backend/data dependencies: Persisted attempts and real service probes; no additional time-series platform.
- Loading/error/empty behavior: Unknown, degraded, stale and disconnected states; actionable retry; do not display fake healthy cards.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Activated scope — October 28, 2026
Owner authorized judgment on all remaining conditions. Implement a read-only composite snapshot on the existing monitoring API, using the actual research queue, SQL attempts/leases, existing pool/runner state, artifact identity and existing paper readiness. Missing observations remain unavailable/unknown. A readable native binary or a BullMQ worker is **not proof of native execution**: report `unverified-until-run`, rather than launching synthetic jobs or adding a health-probe worker protocol. Research status remains unknown when prerequisites are observed but execution has not been probed. This is a deliberate truthful limitation, not a ready signal.
The UI shows observation time, explicit refresh/loading/error/retry, local run/attempt/strategy phase, expired leases, paper freshness/recovery/halt and live-disabled. Existing deployment-specific readiness remains authoritative; no activation or recovery is performed by monitoring. Capture the runner's actual phase in its existing fenced failure string and reuse logger redaction, without migrations or a second execution history.
Correct unavailable cache/queue/service/metric values; include the research queue and avoid observer-created workers. Remove the hardcoded Redis diagnostic route. Original WEB-02 controls/polling defects and OPS-02 legacy composition paths above are historical: W01/S04/S06 already addressed those paths. No broker, live capability, financial policy or worker lifecycle change. Root self-review and repository/recovery regressions are used in this solo continuation; no independent agent review is claimed.

View file

@ -1,58 +0,0 @@
# P01 — Measure existing research paths before extending the benchmark
Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Performance/infrastructure engineering.
Scheduling source of truth: [manifest entry P01](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194).
- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
## Intended behavior and implementation scope
Extend the current dataset benchmark with one small harness for paths that actually exist: process/addon startup, dataset preparation, native load/run/result parse and repeated parameter trials. No new observability framework or fabricated callback timing. Mark unavailable counters/phases explicitly; F07/S01/P03/P04/A02 extend the same harness as capabilities arrive.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- scripts/benchmark-dataset.ts
- scripts/benchmark-research.ts (new)
- test/fixtures/ (benchmark datasets)
Write locks: benchmark-harness. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
No code prerequisite. Global execution approval and write-lock acquisition still required.
No additional economic-policy approval is needed for this narrowly scoped task.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Single/multi-asset native fixtures and parameter trials record source/native binary/runtime/host/seed hashes and raw timings.
- Separate fresh-process/unprepared data from reused input objects; do not call one-shot repeated loads resident warm throughput.
- Report wall time, observed bar/trial rates, result bytes and RSS; DB/queue/allocation counters are unavailable until instrumented, not zero.
- Fixed fixture/economic hashes match repeated runs under the same policy; current known economic defects are limitations, not benchmark truth.
## Mandatory tests
- Tiny harness self-test and1k/10k/100k optional scaling; runtime versions/build hash verified.
- No timing-flaky CI gate. Unsupported multi-strategy ownership/callback paths are labelled unavailable until canonical tasks land.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.

View file

@ -1,5 +0,0 @@
# P02 — Merged into F06
This ID is retained for traceability and must not be claimed or implemented separately.
Its required behavior, fixtures and tests are owned by [F06](F06.md). See [skeptical review](../../REVIEW.md) for the effort reduction and [manifest](../manifest.json) for canonical scheduling metadata.

View file

@ -1,64 +0,0 @@
# P03 — Reuse validated datasets within bounded native workers
Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Performance/infrastructure engineering.
Scheduling source of truth: [manifest entry P03](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
## Intended behavior and implementation scope
Load/hash/validate one dataset per worker and create isolated trial sessions over it. Measure object/JSON versus typed columnar buffers; adopt typed buffers only with a demonstrated transfer/allocation benefit. Keep ownership/lifetime explicit and invalidate by dataset/feature version.
Measurable benefit: Reduces repeated preparation before adding a DSL.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- apps/stock/orchestrator/src/backtest/native-worker-protocol.ts
- apps/stock/orchestrator/src/backtest/native-worker.ts
- apps/stock/engine/src/api/backtest.rs
Write locks: worker-protocol, native-public-api. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [F07](F07.md), [P01](P01.md) integrated.
Architecture decisions: ADR-004, ADR-008. Agents may not independently amend their policies.
Deferred: Only after measured repeated dataset admission is a material sweep cost; not a prerequisite for parallel trials.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- N trials sharing a dataset incur one dataset admission per worker, not per trial.
- Disposing a trial clears mutable strategy/account state but retains immutable data; worker disposal releases buffers.
- Output hashes match uncached runs and sequential trials cannot contaminate one another.
## Mandatory tests
- resident_dataset_hit_counter, trial_state_reset, incompatible_version_miss, dispose_memory_plateau.
- P01 warmed sweep time/RSS and serialization-byte comparison.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Conditional review — October 28, 2026
No-go for now: current measurements are direct warmed sessions, not repeated durable admission profiles. Reusing resident workers would change the proven one-process/one-request cancellation and isolation lifecycle without an attributable sweep benefit. Reopen with a representative durable batch profile that isolates dataset admission/transfer and a bounded lifecycle proposal. Status remains **deferred**, not implemented or silently cancelled. The owner authorized judgment on all remaining conditions and explicitly resumed performance work. [Current review](../../conditional-review.md). Earlier audit findings above are historical evidence: F02–F07/S06 already resolved competing financial cores and the old insertion queue; they are not reasons to implement this extension now.

View file

@ -1,60 +0,0 @@
# P04 — Schedule deterministic batches across a bounded worker pool
Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Performance/infrastructure engineering.
Scheduling source of truth: [manifest entry P04](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
## Intended behavior and implementation scope
Use existing isolated one-shot workers and durable claims to run independent trials concurrently at a configurable1/2/4 process limit. Resident dataset reuse is optional P03, not a dependency. Each trial gets deterministic seed/identity and separate mutable state; admission/backpressure honors cancellation/leases. No parallel event processing inside one portfolio.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts
- apps/stock/orchestrator/src/backtest/BacktestRunner.ts
- apps/stock/web-api/src/services/BacktestDispatcher.ts
Write locks: worker-pool, web-backtest-dispatch. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [F07](F07.md), [R06](R06.md), [C06](C06.md), [P01](P01.md) integrated.
Architecture decisions: ADR-008. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Concurrency1/2/4 produces identical per-trial economic hashes and completion-independent ranking.
- A worker crash retries only affected durable attempts; batch cancellation drains or kills workers with no stale result commit.
- Pool concurrency is configurable; no assumption that all available CPUs improve throughput.
## Mandatory tests
- parallel_hash_parity, worker_crash_retry, cancellation_under_load, lease_fencing_pool.
- P01 trials/s, efficiency T1/(p*Tp), tail latency and RSS at1/2/4 workers.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Accepted implementation — 2026-10-24
Completed and independently reviewed. The [final wave record](../../ROADMAP.md#thirty-eighth-wave-final-acceptance--2026-10-24) and canonical manifest contain the implementation commit, actual regression/SQL/browser proofs, measurement identities and remaining limitations. Completion does not activate real trading or waive conditional architecture gates.

View file

@ -1,69 +0,0 @@
# P05 — Separate result summaries from paged detail payloads
Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Performance/infrastructure engineering.
Scheduling source of truth: [manifest entry P05](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194).
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
## Intended behavior and implementation scope
Deferred until measured detail payload/query/rendering costs justify it. R06 already provides summary projections. This task may add stable paged trade/position detail and display-only downsampling; keep full exports and retained authoritative results. Do not normalize all storage or add an artifact service by default.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- apps/stock/web-api/src/services/backtest-v2.service.ts
- apps/stock/web-api/src/routes/backtests-v2.routes.ts
- apps/stock/web-app/src/features/backtest/
- apps/stock/web-app/src/features/experiments/
Write locks: result-contract, web-backtest-service, web-experiments. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [R06](R06.md), [P01](P01.md) integrated.
No additional economic-policy approval is needed for this narrowly scoped task.
Deferred: Only after measured trade-detail payload/query/render cost; simple summary projections ship in R06.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Experiment list retrieves summaries without full OHLC/trade blobs.
- Detail pagination/export preserves every trade in stable sequence; changing display density does not alter reported metrics.
- Report API bytes, query latency and rendering time before/after on the large-trade workload.
## Mandatory tests
- paged_trade_reassembly_hash, stable_cursor, summary_matches_full_result, complete_export.
- Browser loading/error/empty/pagination test and P01 result-store/load timings.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: GET run summary/provenance plus /trades?cursor and display-series projections; full export remains available.
- Backend/data dependencies: Existing results first; add normalized detail storage only after query profiling and separate approval if scope expands.
- Loading/error/empty behavior: Summary available while detail loads; retry individual page; explicit no trades/end of list; no fake zero risk.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Conditional review — October 28, 2026
No-go for now: experiments already select compact summaries without trade/OHLC blobs; full retained exports exist. No measured detail-query/transfer/render bottleneck was supplied or established by callback measurements. Reopen for a real slow detail workload, preserving complete stable-sequence export. Status remains **deferred**, not implemented or silently cancelled. The owner authorized judgment on all remaining conditions and explicitly resumed performance work. [Current review](../../conditional-review.md). Earlier audit findings above are historical evidence: F02–F07/S06 already resolved competing financial cores and the old insertion queue; they are not reasons to implement this extension now.

View file

@ -1,62 +0,0 @@
# P06 — Conditionally add a minimal Rust-executed strategy plan
Parent epic: E7. Priority/severity: P2 / Medium. Relative complexity: M. Recommended specialization: Rust/TS performance compiler boundary.
Scheduling source of truth: [manifest entry P06](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114).
- **PER-01 — Verified:** EventQueue insertion scans prior events; native run is synchronous/one-shot and returns full JSON. Actual end-to-end bottleneck distribution still needs controlled measurements. [apps/stock/engine/src/backtest/mod.rs:138](../../../../apps/stock/engine/src/backtest/mod.rs#L138); [apps/stock/engine/src/api/backtest.rs:194](../../../../apps/stock/engine/src/api/backtest.rs#L194).
## Intended behavior and implementation scope
Deferred. First inspect actual warmed trial profiles after the TS path works. Owner may authorize a time-boxed prototype of a tiny typed feature/comparison/target plan only if projected end-to-end benefit and maintenance savings justify it. The same Rust financial kernel is mandatory; do not use arbitrary fixed percentage/speed thresholds as automatic permission.
## Exclusions
No speculative distributed infrastructure or weakened correctness gates.
## Likely files and ownership
- apps/stock/orchestrator/src/backtest/strategy-plan.ts
- apps/stock/engine/src/strategies/
- apps/stock/engine/src/financial/
Write locks: strategy-contract, native-public-api. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [P04](P04.md), [S01](S01.md) integrated.
Architecture decisions: ADR-008. Agents may not independently amend their policies.
Deferred: Owner go/no-go after representative profiling and explicit prototype budget; no fixed 20%/1.5x magic thresholds.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Owner records baseline, suspected bottleneck, bounded prototype budget and required end-to-end improvement BEFORE implementation; absence of that decision means stay deferred.
- Prototype compares identical supported TS/declarative decision and economic traces on representative workloads; report Amdahl limit, wall time, memory and maintenance cost.
- Go/no-go either accepts the small supported subset or stops it; no implicit universal DSL work.
## Mandatory tests
- ts_plan_differential, invalid_plan_validation, state_reset, no_risk_bypass.
- P01 full workload speed/memory comparison, not a no-op microbenchmark alone.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Performance measurements can hide semantic changes; require economic hash equivalence.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Conditional review — October 28, 2026
No-go for now: one Rust financial kernel already serves TypeScript callbacks. Local state-handling optimization provides a measured gain without a second strategy representation. Current evidence does not justify the cost and restricted expressiveness of a DSL. Reopen only with representative callback-bound screening demand, a small supported subset and explicit bounded prototype budget. Status remains **deferred**, not implemented or silently cancelled. The owner authorized judgment on all remaining conditions and explicitly resumed performance work. [Current review](../../conditional-review.md). Earlier audit findings above are historical evidence: F02–F07/S06 already resolved competing financial cores and the old insertion queue; they are not reasons to implement this extension now.

View file

@ -1,42 +0,0 @@
# P07 — Profile representative canonical replay workloads
Parent epic: E7. Priority/severity: P1 / High. Complexity: M. Specialist: performance/test infrastructure.
Story: As a platform developer, I can distinguish replay, financial turnover, result transport and diagnostic overhead before choosing the next optimization.
Scheduling and ownership: [manifest P07](../manifest.json). Extend P01's existing harness; do not create another benchmark framework.
## Evidence and root cause
- **PER-01 — Verified:** the F07 [turnover profile](../../../../scripts/benchmark-replay.ts#L100) alternates positions at every barrier. At 10k total bars it creates 9,999/19,980 fills; 2.65–3.61s is not the cost of merely reading bars.
- In the original F07 measurement, finalization consumed approximately 35–39%; fixture decisions less than 2%; native creation approximately 3%. Before F09, the [adapter](../../../../apps/stock/orchestrator/src/backtest/native-replay.ts#L184) combined native work and JSON validation, without a separate disposal timer. These measurements did not establish a pure NAPI overhead, Rust bottleneck, or need for a DSL.
## Scope
- Extend `scripts/benchmark-replay.ts`, `scripts/benchmark-research.ts` and their tests only. Reuse frozen fixture generation, source/addon/host/runtime hashes and cold-process/fresh-session structure.
- Add `none` (same callbacks/cadence, no targets), `sparse` (one opening and one closing fill per owner/asset), and `turnover` (existing alternating unit targets) profiles. Preserve existing invocation behavior; expose explicit CLI profile/format selection and an opt-in 100k size. No new application input limits.
- Measure verified dataset preparation, native load, actual advance/submit/decision/finalization/disposal phases, emitted bytes, observed fills/decisions/calls, wall time and process RSS. Consume optional finalization subphase metrics only after the contract owner publishes them. Do not infer internal Rust/GC time from an unexplained residual.
- Independent integer-based fixture oracles remain test/benchmark-only. Repeated runs/reversed callback evaluation must preserve economic output. Full trace keeps exact normalized-result hash validation; compact/full comparisons use the same canonical financial projection, not unlike wire-envelope hashes.
- Baseline profiles work against committed F07 independently. Paired compact runs are enabled only after F09's contract is frozen/accepted by root; do not edit adapter/schema/native files to make the benchmark fit. Record the exact source/artifact for each baseline/candidate.
- Run selected 10k and explicitly requested 100k workloads sequentially. Report unavailable measurements/resource failures honestly rather than silently trimming data/traces. Full-history 100k diagnostic output can be large; no throughput claim for cases not run.
## Exclusions
No financial semantic change, arbitrary hot-loop refactor, native dataset cache, shared feature framework, worker pool, DSL, new service, web paging or journal deletion. Select a concrete next optimization from evidence; implementation beyond F09 requires a scoped follow-up.
## Dependencies, locks and parallelism
Code prerequisites: F07 and P01. No new economic policy or ADR-008 approval is needed for measurements alone. P03/P04/P06 remain gated. Write lock: benchmark-harness, with the three explicit files above. Safe parallel work with F09's separate core/adapter files. Compact comparison is a conditional integration gate requiring F09; baseline compilation/tests must not depend on unmerged native APIs.
## Acceptance and mandatory tests
1. `profile_none`, `profile_sparse`, `profile_turnover` pin deterministic call/fill/fee/basis/terminal-equity expectations, including multiple owners/assets and retained session gaps.
2. `benchmark_profile_arguments` rejects unsupported flags/combinations; existing P01/F07 invocation and tiny tests still work.
3. `profile_identity_mismatch` rejects changed dataset/policy/strategy/native result identity; profile/result format is included in provenance. Different profiles are never compared as equivalent economics.
4. `compact_trace_projection_parity` and reversed callback order agree on authoritative projection; diagnostics remain complete and independently testable.
5. No fake zero/unavailable timings, no timing-flaky assertions. Print raw repeated rows and a concise breakdown with timing boundaries/build profile. Distinguish first process/setup from reused prepared JS inputs and fresh native sessions.
6. Integrated evidence documents measured candidate effects, remaining unattributed costs and the smallest justified next action. No unsupported 10x/100x claim.
Regression risk: benchmark oracle mistakes, comparing different policies/profiles, or profiling work inside a purported engine-only timer. Mandatory focused tooling/native fixtures, strict TypeScript and scoped lint; financial/result owner reviews oracle/parity independently. No native rebuild concurrent with another agent's artifact review.
Definition of done: reproducible script/tests, baseline and accepted-candidate measurements, independent review and root manifest handoff. Missing resource-dependent large runs must be explicit; not a pass. No commits/pushes/PRs without authorization.

View file

@ -1,46 +0,0 @@
# P08 — Reduce measured TypeScript strategy decision overhead
Parent epic: E7. Priority/severity: P1 / High. Complexity: M. Specialist: TypeScript performance and deterministic runtime engineering.
Story: As a researcher, I can run realistic window-based TypeScript strategies without repeatedly paying avoidable state-validation or copying costs.
Scheduling source of truth: [manifest P08](../manifest.json). **Resumed by the owner, 2026-10-28.** Profile and measure before optimization. Exact proposed application scope: `strategies/strategy-decision.ts` strict JSON copying; benchmark tooling in `scripts/benchmark-research.ts` and private `scripts/benchmark-sma.ts`, with focused tests. No SMA arithmetic/state-schema changes or native/durable boundary changes.
## Evidence and root cause
**PER-02 — Verified aggregate cost; individual causes need profiling.** S02's release comparison replays exactly the same financial decisions and IDs. For 10,000 total bars, recorded decisions versus SMA callbacks took 1,091→1,467 ms (5/15, one owner) and 1,018→2,351 ms (15/252, one owner). With ten assets/ten owners, 15/252 took 594→1,681 ms. All 48 timed sessions preserve complete financial hashes; repeat/reversed-owner runs preserve diagnostics. These are warmed synthetic workloads, not durable-job throughput or pure callback/NAPI measurements.
Potential contributors are the [host staging boundary](../../../../apps/stock/orchestrator/src/strategies/strategy-decision.ts#L154), strict JSON copying/freezing, [per-callback SMA state parsing](../../../../apps/stock/orchestrator/src/strategies/canonical-sma.ts#L90), bounded history and [reviewed trailing calculations](../../../../libs/calculations/src/indicators/window-statistics.ts#L50). The aggregate difference does not attribute cost among them. Larger windows also change decisions and fills; compare each strategy with its own exact recorded control, not the two periods as identical economics.
Raw evidence/harness/source identity: `manifest.json` → `fifteenth_wave_validation.performance`; [roadmap](../../ROADMAP.md#fifteenth-wave-execution--2026-10-23). Retained local harness: `/tmp/stock-bot-wave15.zi3GmP/sma-benchmark.ts`.
## Scope and exclusions
1. Extend the existing research benchmark entrypoint with the S02 paired strategy/recorded workload; incorporate the useful temporary harness logic into existing tooling, not another benchmark framework. Preserve cold import/preparation versus warmed-session boundaries, source/addon hashes, raw samples, counts and exact comparisons.
2. Profile actual calculation, schema parsing, state copy/freezing, host admission feedback and allocations. Measure instrumentation separately; a residual is not a named subsystem cost.
3. Implement the smallest evidenced local optimization in `backtest/strategy-runtime.ts`, `strategies/canonical-sma.ts` or their private helpers. Avoid changing public contracts. Publish a proposed exact file scope before editing shared runtime/strategy files.
4. Preserve strict JSON state validation, detached immutable contexts, per-owner isolation, staged commit-after-native-ack, failure diagnostics, scoped RNG, whole-attempt retry, reviewed crossover arithmetic, financial decisions and result provenance. Do not special-case away validation for trusted built-ins or change strategy semantics to make the benchmark faster.
No Rust financial changes, DSL, worker pool, resident dataset/feature framework, shared mutable checkpoints, public/default cutover, weakened validation, arbitrary input limits or general cleanup. Incremental indicator arithmetic or a new state contract needs a separately reviewed proposal; neither is assumed necessary.
## Dependencies, ownership and parallelism
Code prerequisites: S02 accepted/integrated, P07 complete. No additional policy approval for profiling/local semantics-preserving optimization. One owner holds strategy-contract, strategy-builtins and benchmark-harness locks for the minimal patch; disjoint review may run in parallel. Do not overlap S03/S05 or another worker using those actual files. Root alone updates task state. No native rebuild during measurements or artifact review.
## Acceptance and mandatory tests
- `sma_benchmark_modes` validates selection/period/topology arguments, labels ten-assets/two-owners as eight untraded assets, and reports actual decisions/fills rather than inferring equal work from bar count.
- `sma_recorded_decision_parity` compares identical captured decision IDs and complete financial outputs for 5/15 and 15/252, with 1/1, 10/2 and 10/10 asset/owner shapes. Fresh retries and reversed program order preserve diagnostic/RNG/state hashes. Retain raw repeated measurements and the exact baseline/candidate artifacts.
- Profile identifies the removed cost. Counterbalance baseline/candidate runs on the same host/release addon and configurations; show repeatable end-to-end improvement larger than observed run-to-run variation on both 15/252 owner-dense workloads, with the smaller workloads checked for regression. Do not claim an optimization from changed economics, instrumentation overhead or host drift. If no safe local improvement is demonstrated, hand off the blocker/proposal rather than mark implementation complete.
- Preserve all `canonical-sma`, `strategy-runtime`, `native-replay`, worker and runtime tooling regression tests. Add a focused regression for each changed state/validation path, including retained mutable references, malformed JSON, callback failure after prior owners staged, native rejection and malformed/ambiguous admission feedback as relevant. Accessors must not execute; prototype/cycle/symbol/sparse/non-finite/negative-zero rejection and future-information isolation remain intact. No unstable wall-time assertions in unit tests.
- Strict TypeScript for new test/tooling sources, scoped lint/format, full `bun run check`, final release verification and G2 recovery if worker/durable boundaries change. Root records invariant and measurement self-review for this solo continuation; independent review is not claimed.
Risks: accidental mutable aliasing, skipped validation, changed floating-point crossover arithmetic, committing partial owner state, misleading benchmark attribution. Revert a failed optimization without weakening economic policy or deleting reviewed helpers. Definition of done: focused reviewed patch, passing gates and repeatable exact-economics measurements; root acceptance and explicit commit authorization remain separate.
## Implementation and measurement — October 28, 2026
The existing benchmark command now accepts `--sma` and `--sma --measure`; its private helper retains exact decision tapes, economic/provenance/diagnostic hashes, reversed-owner retries and all six shapes. Strict JSON copying now optionally freezes copied containers during the same traversal; it still checks every descriptor and detaches every alias. No SMA schema, crossover arithmetic, native contract or durable transaction changed.
[Raw measurements](../../measurements/p08-state-copy.json) retain a full ABBA matrix (eight samples per variant/mode/shape) and a separate CPU-2 BAAB confirmation. Full-matrix 15/252 medians: one owner 2,188→2,079 ms (noisy overlap), ten owners 1,534→1,386 ms. Do not advertise the noisy single-owner median as a reliable universal gain. The interleaved confirmation has four samples per variant/shape: one owner 2,422→1,845 ms, ten owners 1,541→1,343 ms; candidate and baseline sample ranges do not overlap in either. Recorded decisions, financial output, diagnostic state/RNG and all configuration hashes match across variants. These are warmed synthetic sessions, not cold jobs, database/queue throughput or pure NAPI crossing timings. No concurrent test/build ran during either retained comparison.
Separate instrumentation identifies copy/freezing as the removed work; it includes timer overhead and makes no allocation-count claim. Small-window full-matrix medians show no measured regression beyond variation. Root self-review checks mutation rejection, owner isolation and commit-after-ack; independent review is not claimed in this solo continuation. Full verification and final release checks are recorded in the manifest once passed.

View file

@ -1,95 +0,0 @@
# R01 — Persist immutable strategy versions and parameter schemas
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product.
Scheduling source of truth: [manifest entry R01](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315).
## Intended behavior and implementation scope
Add strategies and append-only strategy_versions; seed registered built-ins with source/bundle hash, parameter schema, checkpoint contract and review status. Store executable artifact bytes or an immutable retained artifact reference, dependency lock and source revision. Draft metadata can change; published executable versions cannot.
Measurable benefit: Pins executable strategy identity before adding experiments.
Project/hypothesis linkage is optional and must not require R03 tables or placeholder records. Add nullable foreign-key links only when both entity tables exist, in a coordinated additive migration; standalone versions/experiments work first.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- database/postgres/init/ (new migration)
- apps/stock/web-api/src/routes/ (strategy endpoints)
- apps/stock/web-api/src/services/ (strategy service)
- apps/stock/orchestrator/src/strategies/StrategyRegistry.ts
- libs/core/types/src/strategy-version.ts (new)
Write locks: sql-migrations, strategy-catalog-api. Root coordinates shared contracts; backend and packaging agents reserve disjoint actual files. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [O01](O01.md) integrated.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Version parameters reject through the catalog validation API using the retained schema and exact registered built-in validators. R01 exposes no enqueue path: every catalog version is explicitly non-runnable until R05 (trusted built-ins) or A02 (arbitrary candidates). Existing legacy requests carrying catalog version IDs reject rather than silently execute current name-based code.
- An idempotency key plus content fingerprint makes identical publish retries return the same version; changed content with the same key returns409. An intentional new revision gets a new ID and lineage even if content matches.
- Published source/schema/checkpoint/dependency content is immutable and retained. Review/approval is separately audited metadata, not a mutation of executable content.
- Registration never executes candidate code in the API; arbitrary untrusted execution stays unavailable until A02.
## Mandatory tests
- strategy_version_immutability_postgres, schema_validation, artifact_hash_mismatch, clone_lineage.
- Registry aliases and old definition compatibility.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: GET/POST /api/v2/strategies; GET/POST /strategies/:id/versions; GET /strategy-versions/:id; POST clone. Parameters use a versioned JSON schema subset.
- Backend/data dependencies: New strategy/version tables; existing strategy registry; source-artifact storage retained with version.
- Loading/error/empty behavior: API typed validation errors,404 and409; UI arrives in R02.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Execution contract — 2026-10-23
- Three additive tables only: editable/archiveable strategies, immutable strategy_versions with retained package JSONB and numbered lineage, append-only operator review events. No R03 placeholders, artifact store or delete cascade. SQL rejects version/review UPDATE/DELETE.
- Package v1 retains self-contained bundled JavaScript, exact Bun lock bytes, SHA256 hashes, source revision/dirty state, compiler identity, parameter schema and API/checkpoint identity. The bundle is authoritative executable content; source metadata does not imply original TS retention or full experiment reproducibility.
- Canonical SMA/MR schemas and aliases move to the existing pure stock-config subpath with compatibility reexports. JSON form schema is a small scalar subset; exact Zod cross-field validation remains authoritative. No uploaded validator or code executes in API.
- Offline packaging builds the two reviewed repository programs with workspace source resolution and no external runtime imports. A separate explicit local seed command registers these built-ins; HTTP publication always creates candidate origin. New/cloned versions start unreviewed. Operator approval/revocation appends audited events, never modifies executable content or enables execution.
- Publish and clone use actor/key receipts plus canonical content fingerprints. Read receipt before mutable parent state, lock parent for ordinal/archive decisions, recheck receipt, insert atomically; changed payload with same key conflicts. New key yields intentional new identity even for identical bytes. Clone retains parent lineage and clears registration/review.
- Catalog mutations require credential-backed operator/service identity; reviews require operator. The development bypass is not authorship proof. Existing routes preserve their prior authentication behavior.
- Metadata list/detail omits artifact/lock content; explicit artifact retrieval retains exact bytes. Version validation returns normalized parameters and `runnable:false`. No UI (R02), retained-artifact execution (R05), untrusted execution (A02), strategy financial changes or performance work.
## Validated handoff — 2026-10-23
Catalog APIs, additive migration 16, pure version/parameter contracts, offline built-in packaging and explicit local seeding are integrated and independently reviewed. Metadata is editable/archiveable; versions/reviews are immutable. Publish/clone receipts, stable built-in families, parent lineage, role checks and exact artifact checksums have real PostgreSQL coverage. New/cloned/rebuilt versions start unreviewed, and all versions remain non-runnable.
Local commands (not run against development data in this wave):
- `bun run scripts/package-builtin-strategies.ts --out /tmp/builtin-strategies.json` packages both trusted repository programs without database access.
- After normal migration startup has applied 16, set `STRATEGY_CATALOG_DATABASE_URL` explicitly and run `bun run scripts/seed-builtin-strategies.ts --seed`. It compiles the local built-ins itself, reuses their catalog families, retains package/lock bytes and leaves new versions pending review. It accepts no arbitrary artifact input and performs no schema migration or strategy execution.
HTTP metadata: `/api/v2/strategies`, `/strategies/:id/versions`, `/strategy-versions/:id`; full bytes use `/:id/artifact`; clone/review/parameter validation use `/:id/clone`, `/:id/reviews`, `/:id/validate`. Publication/clone require `Idempotency-Key`. Catalog mutations require actual operator/service credentials, even when other development routes permit loopback bypass; only operator may review. API-supplied names/flags cannot self-register trusted code.
Validation: 93 tooling, 509 integration, 150 Rust (four manual ignored), 122 PostgreSQL/Redis and six browser workflows passed, plus source/contracts/build/lint/strict changed-test types. Final release native regressions passed 65 tests. Exact sequencing, hashes, commands and raw logs are canonical in `manifest.json` → `twentieth_wave_validation`. R10 and R02 follow; no current engine switch, candidate execution, trading activation or performance work.
Accepted and committed as `4a2e5ad` following the owner’s “commit and continue with backlog” instruction. R10 subsequently protects existing backtest history; R02 is the next product task.

View file

@ -1,93 +0,0 @@
# R02 — Deliver strategy catalog and version-aware backtest setup
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product.
Scheduling source of truth: [manifest entry R02](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315).
## Intended behavior and implementation scope
Replace only the strategy placeholder with catalog/detail/version views; allow metadata edits, clone, parameter editing and read-only source/version diff. Add version selection and supported capability filtering to existing backtest form. First release authors code in repository or submits an artifact; no browser IDE.
Measurable benefit: Makes strategy work a coherent product flow.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- apps/stock/web-app/src/app/App.tsx
- apps/stock/web-app/src/features/strategies/ (new)
- apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx
- apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx
- apps/stock/web-app/src/components/
- apps/stock/web-api/src/services/backtest-v2.service.ts
- libs/core/types/src/backtest-run.ts
Write locks: web-backtest-detail, web-strategies. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [R01](R01.md), [W03](W03.md) integrated.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Feature activation/release gates: [W04](W04.md). These do not block implementing or integrating this component against its own tests.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- User can create/clone metadata, choose immutable version and schema-valid parameters, then open the existing run flow.
- Unavailable native/custom strategy choices are not offered as runnable.
- Version detail links deployment/backtest history when available; absent histories show empty states.
- Catalog browsing, metadata, version comparison and parameter forms can ship after R01. Persist version selection, but disable version-based submission until R05 verifies and executes retained artifacts. Never map canonical catalog versions to legacy name-based strategies. Existing independent legacy runs remain visibly qualified.
## Mandatory tests
- catalog_navigation, parameter_form_validation, immutable_version_selection, clone_revision_diff.
- Browser strategy->backtest flow and schema/API contract tests.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: R01 catalog/version endpoints plus exact version ID and normalized parameters in saved backtest templates. R05 owns versioned run admission and immutable request snapshots; R02 creates no catalog run/outbox.
- Backend/data dependencies: R01 schema; current engine capability metadata. Unsupported version/runtime combinations fail before submit.
- Loading/error/empty behavior: Skeleton list/detail; no-strategies create CTA; schema error next to parameter; retry fetch; unsaved edit warning.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Wave22 execution contract
R10 committed `8cca0ee`; owner authorized R02. Reuse existing catalog APIs, React routes and backtest templates. Publish author code through existing repository/artifact APIs; no browser IDE or new compilation/runtime service. Read-only artifact comparison shows retained bundled JavaScript, schema and identities, not reconstructed original TypeScript.
Migration18 adds `strategy_version_id` (restrictive FK) and separate scalar `strategy_parameters`. The saved template uses `strategy: 'catalog'`; the version never becomes a legacy alias. Creation requires explicit `autoStart:false`. Save validates retained checksums, exact version parameters, data/execution settings and selected-dataset compatibility. Preserve omitted selection on partial updates; an explicit new version requires explicit parameters. Both legacy/catalog mode conversions are rejected; create another template instead. New selections reject archived families under their row lock; existing references remain readable and editable unless the template itself is archived.
V2 submission rejects before run/outbox insertion; V1 rejects catalog input before saving. Direct repository marker checks and the existing SQL run-admission trigger close alternate paths. Legacy receipt replay remains first. Keep the pure legacy parser's pre-strip rejection intact, including null version fields. Map trusted legacy DTOs explicitly instead of weakening that guard.
All versions remain non-runnable, including approved built-ins. The UI supports exact version selection, schema fields, server validation and saved setups with fresh submission disabled. Existing supported legacy strategies remain a separate qualified workflow. No inferred version/deployment histories from names; show absent integration honestly. Schema forms preserve optional omissions, false, zero, typed enums and decimal strings. Retained bundle text is never executed. Metadata/clone drafts preserve input and use explicit discard warnings; clone retries retain their original key/body.
## Validated handoff — 2026-10-23
Implemented the pinned Wave22 contract in 39 source/shared-contract/migration/test files. Catalog family metadata, immutable version selection, clone retries, exact schema validation, escaped bundle comparison and existing save/reopen/settings flows are integrated. API, repository and SQL gates keep all catalog versions non-runnable; legacy receipt ordering and supported legacy runs remain unchanged. Migration 18 retains version/parameters without creating catalog runs or request snapshots.
Review fixes include explicit empty-string versus omitted parameters, normalized value display, frozen clone source identity during navigation, catalog settings omitting legacy pacing, and authoritative archive/restore resets that invalidate stale parameter validation. Browser coverage proves exact saved values, immutable selection after new publication, clone lineage, safe bundle display, and zero runs/outbox. Each browser fixture has its own context/server/schema/queue within one suite-owned Chromium process after repeated driver teardown exposed pipe loss under Bun 1.2.17; no retry hides failures.
Validation: full repository checks passed (541 integration, 150 Rust, 93 tooling, 43 utility, 44 calculation plus build/types/contracts/lint/secrets); full PostgreSQL/Redis 137 tests/1052 assertions; all 8 browser workflows/117 assertions; strict new/modern test types and scoped lint/format/diff checks. Source hashes, commands, logs, independent review and stopped fixture IDs are in `manifest.json` → `twenty_second_wave_validation`. Release addon matches the prior wave; Rust financial source is unchanged.
Read-only source is retained bundled JavaScript, not original TypeScript. Code publication stays in repository/offline tooling or existing artifact APIs; no embedded editor/upload UI. Version-linked backtest/deployment histories remain unavailable. Unsaved warnings cover local discard actions/document unload, not a new global routing framework. Clone retry identity lasts within the mounted detail view. Current legacy economics remain explicitly qualified. R05 owns verified retained-artifact execution and full provenance; A02 gates candidates, and the multi-asset default policy remains unresolved. No R02 commit/push/PR, default cutover, trading activation or performance work.

View file

@ -1,97 +0,0 @@
# R03 — Add projects, hypotheses and evidence-linked findings APIs
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product.
Scheduling source of truth: [manifest entry R03](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
- **WEB-05 — Verified:** SQL deletion cascades from definitions to runs/results; evidence retention must be defined before research findings reference those results. [database/postgres/init/08-create-runs-table.sql:13](../../../../database/postgres/init/08-create-runs-table.sql#L13); [database/postgres/init/06-create-backtest-tables.sql:25](../../../../database/postgres/init/06-create-backtest-tables.sql#L25).
## Intended behavior and implementation scope
Add minimal project/hypothesis/note/finding metadata with human/AI authorship and immutable evidence references. Findings refer to runId + metricsVersion + metricPath (and optional immutable artifact ID); the API derives displayed measured values from retained results instead of maintaining another metric truth/validation subsystem. Narrative conclusions may be wrong and must remain distinguishable from referenced measurements.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- database/postgres/init/ (new migration)
- apps/stock/web-api/src/routes/ (research endpoints)
- apps/stock/web-api/src/services/ (research service)
- libs/core/types/src/research.ts (new)
Write locks: sql-migrations, research-api. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [R01](R01.md), [R10](R10.md) integrated.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- AI-created hypotheses/notes are labelled unvalidated until explicit validation evidence/review exists.
- Evidence references must resolve to retained run/artifact and known metric version/path; dangling references reject. No new simulator or narrative fact-checking subsystem.
- Archiving metadata does not delete cited runs; narrative changes create a revision while underlying results remain immutable.
## Mandatory tests
- hypothesis_vs_evidence, evidence_fk_integrity, authorship_audit, cited_metric_matches_run.
- Migration upgrade fixture retains existing runs/results.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: /api/v2/research-projects, /hypotheses, /analysis-artifacts with explicit evidence references and archive actions.
- Backend/data dependencies: New metadata tables; reuse existing run/result IDs and strategy/version IDs.
- Loading/error/empty behavior: Typed404/409/422, empty evidence lists and explicit unvalidated state; R04 supplies UI.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Implemented contract — 2026-10-23
R03 adds metadata APIs only; R04 owns the research workspace screens. Migration 20 introduces projects, hypotheses and their revisions, note/finding artifacts and their revisions, evidence references, and project/strategy membership. Existing runs, results, strategy versions, queues and financial engines are reused unchanged. The implementation is in `services/research.service.ts`, `services/research-evidence.ts`, `routes/research.routes.ts` and pure DTOs/schemas at `libs/core/types/src/research.ts` and `@stock-bot/stock-config/research`.
Every narrative revision remains `validationState: 'unvalidated'`. `evidenceState: 'referenced'` means citations exist, not that the conclusion is true. `submittedBy` comes from verified operator/service credentials; `contentOrigin: human | ai | unknown` is explicitly declared provenance. Operator submissions default to human, service submissions to unknown; a service cannot claim human authorship. Operator imports may be labelled AI. No model identity, AI credential system, approval workflow or trading authority is inferred.
Project edits require `expectedRevision`; actual strategy-link changes also advance it and record the actor. Hypothesis/artifact content changes append a complete immutable revision under the project/entity lock and require the current ordinal. A stale editor receives 409. Archive/restore preserves history and records the latest metadata actor/time. Archived projects reject child writes; archived records remain readable. A finding can link an exact hypothesis revision from the same project; later hypothesis edits/archive never rewrite that link or prevent independent revisions of an existing finding.
Findings require at least one reference; notes may have none. References contain `runId`, `metricsVersion`, `metricPath` and optionally a matching retained `strategyVersionId`. They have foreign keys to retained result/version rows and never store copied metric values. Only the known scalar paths in the shared schema are accepted. `canonical-analytics/v1` reads accepted F08 analytics; `legacy-display/v1` versions the existing compatibility reader, **not** a recorded legacy engine or financial policy. Completed runs/results are required. Null stays unavailable with its reason, zero stays zero, fractions are not rescaled, fills do not become round trips, and legacy/model limitations accompany measurements.
Reads use `BacktestServiceV2.getRunResults`; an optional query client lets evidence resolution share the active metadata transaction. This prevents a nested-pool deadlock with one connection. SQL rejects revision/reference update/delete/truncate, dangling references and later insertion into an old revision's evidence set. Reference creation is limited to its narrative revision's creation transaction, with a deferred nonempty-finding check. There is no second metric store or simulator.
### API for R04 and other authorized clients
All routes use `/api/v2`; list payloads may be empty and mutations require real credentials even when development authentication bypass is enabled. Each route sets `Cache-Control: no-store` without changing unrelated APIs.
| Resource | Operations |
| --- | --- |
| `/research-projects` | GET `{projects}`; POST `{title, description?}` → 201 `{project}` |
| `/research-projects/:id` | GET `{project}`; PATCH `{expectedRevision, title?, description?, archived?}` |
| `/research-projects/:id/strategies` | GET `{strategies}`; PUT/DELETE `/:strategyId` → 204, no body or `{}` |
| `/research-projects/:id/hypotheses` | GET `{hypotheses}`; POST `{title, proposition, validationCriteria?, contentOrigin?}` → 201 `{hypothesis}` |
| `/hypotheses/:id` | GET `{hypothesis}`; PATCH `{archived}` |
| `/hypotheses/:id/revisions` | GET ascending `{revisions}`; POST full new content + `expectedRevision` → 201 `{hypothesis}` |
| `/research-projects/:id/analysis-artifacts` | GET `{artifacts}`; POST `{kind, title, body, hypothesisRevisionId?, contentOrigin?, evidence?}` → 201 `{artifact}` |
| `/analysis-artifacts/:id` | GET `{artifact}`; PATCH `{archived}` |
| `/analysis-artifacts/:id/revisions` | GET ascending `{revisions}`; POST full narrative/evidence + `expectedRevision` → 201 `{artifact}` |
Project/hypothesis/artifact lists accept `includeArchived=true|false`. Missing resources return 404; stale revisions and archived writes 409; malformed bodies/unknown metric selectors 400; a valid reference incompatible with its retained result 422. Corrupt retained results return a sanitized 500 with internal diagnostics, not a false client-input error. No hard-delete, execution or validation-promotion endpoint exists. Initial metadata creation uses ordinary POST semantics; clients should not automatically retry an ambiguous creation response as though it had an idempotency receipt.
Mandatory cases are covered by `test/postgres/research-workspace.test.ts`, `test/integration/research-api.test.ts` and `test/integration/research-evidence.test.ts`. The PostgreSQL fixture includes a real retained native run, legacy conversion, exact revisions, direct-SQL guards, concurrent edits/archive, a one-connection pool and migration upgrade/reapply preservation. Combined validation and reviewed source hashes are recorded in the manifest's twenty-fourth-wave handoff. No production/development schema or catalog was changed during implementation.

View file

@ -1,82 +0,0 @@
# R04 — Deliver research workspace and save-findings flow
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product.
Scheduling source of truth: [manifest entry R04](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; The existing strategy catalog, immutable versions and retained canonical single-asset run path are integrated; this task adds the research workspace around them. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
- **WEB-04 — Historical finding, partially resolved by R01/R05:** Retained canonical runs now bind immutable strategy and engine inputs. Legacy projections can still use mutable definition fallbacks; the workspace must preserve each result kind and its evidence limitations. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
## Intended behavior and implementation scope
Add project overview, hypothesis notes, linked strategies/runs and Save finding from result view. Reuse DataTable/Card/Dialog and current navigation. Keep human conclusions separate from AI suggestions and measured evidence.
Measurable benefit: Provides the primary research workspace before advanced optimization.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- apps/stock/web-app/src/features/research/ (new)
- apps/stock/web-app/src/app/App.tsx
- apps/stock/web-app/src/lib/constants.ts
- apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx
Write locks: web-research, web-backtest-detail. Root coordinates separate workspace and save-finding UI owners; actual file assignments are recorded in the manifest. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [R03](R03.md), [W02](W02.md) integrated.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Feature activation/release gates: [W04](W04.md). These do not block implementing or integrating this component against its own tests.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Project -> strategy -> configure/run -> inspect -> save cited finding -> reopen project is navigable.
- Finding links open exact run/version; incomplete/legacy evidence displays limitations.
- Notes can be saved without claiming strategy validation.
## Mandatory tests
- research_project_to_finding_browser, missing_evidence_error, ai_authorship_badge, archived_project_read.
- Loading/error/empty state component tests.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: R03 project/hypothesis/artifact APIs and existing saved runs.
- Backend/data dependencies: R03 entities, existing run provenance, no requirement for full Rust cutover.
- Loading/error/empty behavior: Empty project guidance; saving/retry states preserve draft; stale evidence error; archived read-only state.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Implemented surface — 2026-10-24
- `/research` lists and creates projects; `/research/:projectId` edits metadata, links catalog strategies, and creates or browses hypotheses, notes and findings. Query selectors `hypothesis`/`artifact` plus optional immutable `revision` identify the displayed narrative.
- Revisions append with `expectedRevision`. A conflict preserves the draft and requires deliberate history review. Historical revisions and archived projects remain readable. Child writes are blocked when project authority cannot be verified.
- Completed matching backtest results offer **Save finding**. Choose an active project, optional exact hypothesis revision, declared content origin and allowlisted measurements. The browser sends reference identities only; R03 resolves values from retained results. Canonical strategy versions come from the original request; legacy results retain their qualifications.
- Evidence displays raw and formatted values, units, unavailable reasons, actual financial engine, dataset identity and exact run/version links. Declared AI/human origin is separate from authenticated submitter; citations never validate the narrative.
- Pending mutations reject duplicate clicks. Lost, malformed or server-error creation responses freeze the draft; users check saved records before explicitly starting another request. Reads and mutation callbacks reject obsolete navigation responses.
- Existing Card/Dialog, strategy parameter form styles, navigation, authentication and APIs are reused. No backend, database, financial or execution contract changed.
The browser acceptance extends the existing retained canonical execution fixture through project creation, an AI-labelled hypothesis, linked strategy selection, backtest setup/run, exact finding, revision history, reload and archived-project reading. It retains the hand-derived two-fill/equity/fee assertions and verifies that original results stay unchanged. Focused DOM tests exercise failure/empty/loading states, conflicts, unavailable evidence, ambiguous saves, archive races and stale replies.
Current integration state and exact checks are in `manifest.json` → `twenty_fifth_wave_validation`; this section does not independently change scheduling status. UI origins are declared labels, not authenticated AI identities; agent credentials/execution, experiment management and automated validation remain separate tasks.

View file

@ -1,148 +0,0 @@
# R05 — Freeze complete provenance and cut over durable canonical runs
Parent epic: E6. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Full-stack research product.
Scheduling source of truth: [manifest entry R05](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
- **FIN-05 — Updated after S01/S02/F08:** Canonical TypeScript decisions on Rust sessions and canonical reports already exist. The durable runner still calls the legacy `runBacktest` path; the canonical worker constructs the current built-in implementation by identity. R05 must connect retained executable identity and canonical results to durable admission, not introduce another strategy engine. [native-worker.ts:26](../../../../apps/stock/orchestrator/src/backtest/native-worker.ts#L26), [strategy-runtime.ts:224](../../../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts#L224), [canonical-result.ts:37](../../../../apps/stock/orchestrator/src/backtest/canonical-result.ts#L37), [BacktestRunner.ts:191](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L191).
## Intended behavior and implementation scope
Freeze strategy/model artifact IDs, parameters, seed, code/lockfile/build hashes and execution policies at submission. For canonical research, prepare and retain source data before submission, then atomically pin its exact verified hash with the immutable run request. A preparation query is not a run or frozen dataset. Expose read-only preparation, retained data and admitted run as separate actions. This explicitly supersedes the original proposal for preparation inside an admitted run; see the 2026-10-24 disposition below. Wire the canonical Rust session with existing registered TS strategies into the durable runner and versioned result DTO. Exact reproduction API/UI is R12.
Consume F08's additive canonical analytics/report contract here. Version the persisted/public projection so canonical fractions, genuine zero exposure and null reasons bypass legacy percentage conversion/placeholder suppression. Preserve owner books and distinguish fills from round trips. Additional position valuations needed by the UI must come from Rust or be explicitly unavailable; do not invent marks, average-price basis or unrealized P&L in TypeScript merely to satisfy the old DTO. Keep historical readers unchanged and prove reopen/render compatibility during this cutover.
R02 now saves catalog versions and validated parameters with execution blocked at API, repository and SQL boundaries. Replace those gates only for verified supported execution. Before parallel implementation, pin the executable artifact/build binding: a retained bundle hash must never certify execution of a different current `createBuiltinStrategy` implementation. Verify the exact executable identity before the first decision; mismatches fail closed without a legacy-name fallback. Start with a trusted built-in single-asset vertical slice, retaining candidate isolation and multi-asset policy gates. That milestone alone does not complete all R05 requirements or authorize default activation.
Measurable benefit: Creates reproducible, project-gated runs usable by humans and AI.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- apps/stock/orchestrator/src/backtest/BacktestRunner.ts
- apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts
- apps/stock/web-api/src/services/backtest-v2.service.ts
- libs/core/types/src/backtest-run.ts
Write locks: result-contract, web-backtest-service, web-backtest-detail. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [F08](F08.md), [S02](S02.md), [R01](R01.md), [R10](R10.md), [D01](D01.md), [W03](W03.md), [C06](C06.md) integrated.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Changing template, strategy source or provider history after dataset freezing cannot alter an admitted run. A source query alone is not labelled a frozen dataset.
- No canonical run is admitted before source data is retained and verified; artifact verification and atomic dataset binding precede decisions. Failed preparation creates no run. Retention retries reuse captured input/hash, while an explicitly requested fresh source preview may observe changed provider history.
- A retained-version/current-build mismatch rejects before execution; successful provenance identifies the executable that actually ran. Changing the current built-in implementation cannot silently change a retained version's behavior.
- New results declare financialEngine=rust and strategyExecution separately; correctness-gate evidence requires approved engine/data gates, not a UI flag.
- Before making canonical multi-asset research the default, obtain explicit owner disposition of sequential equal-time mark risk: either accept the disclosed versioned approximation or approve a coordinated atomic-mark policy/implementation with independent fixtures. F04/F05 currently evaluate each ordered mark; F06 demonstrates offsetting simultaneous moves can latch intermediate loss/drawdown halts. A passing deterministic replay suite alone does not resolve this material modeling issue. Single-asset component work and additive native integration need not wait for this decision.
## Mandatory tests
- mutate_template_after_submit, freeze_before_first_decision, frozen_seed_replay, provider_change_after_dataset_bind.
- retained_artifact_executable_binding, current_builtin_mismatch_rejected_before_decision, catalog_version_never_falls_back_to_legacy_name.
- Full durable runner restart/lease/cancel suite and result contract compatibility.
- Canonical reporting fractions/zero/null reasons, owner attribution and fill-versus-round-trip semantics survive persistence/reopen/UI rendering; existing legacy rows retain their prior interpretation.
- Multi-asset default activation rejects while the mark-policy disposition is absent; accepted policy/version/limitations are frozen in provenance, with offsetting-mark regression evidence.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: Preparation returns captured source input plus its normalized descriptor without creating a run. Retention verifies that input/hash; run/results expose the immutable request, retained dataset binding and provenance. Existing R12 owns exact reproduction.
- Backend/data dependencies: Existing request_snapshot/dataset_hash/results extended with retained provenance and engine correctness-gate evidence metadata.
- Loading/error/empty behavior: The preparation panel distinguishes reading, previewing, unavailable evidence, retaining and uncertain retention; exact captured retries preserve identity. Admitted runs keep the existing durable queued/running/terminal lifecycle. Preparation is not a run status. W02/R11 render retained evidence without fabricated provenance.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## First vertical slice — 2026-10-23
The additive slice connects the approved, server-seeded catalog built-ins to the existing durable runner and canonical Rust session. It supports one eligible retained v2 dataset, one series/asset/owner, explicit USD cash-funded long-only execution and reporting settings. HTTP-published or cloned candidates remain excluded even if reviewed. R05 is **not complete**: source-request preparation into eligible v2 data and broader cutover remain outstanding. No multi-asset/default activation is implied.
The pinned request is `canonical-research/v1` in `apps/stock/config/src/contracts/canonical-research.ts`. It retains the full checksummed executable package and dependency lock, normalized parameters, review receipt, dataset hash, seed, complete replay/financial/reporting policies and installed worker/native/runtime build identity. Admission and review/archive serialize on the strategy-family row; accepted receipt replay precedes current eligibility checks. Later edits or review revocation affect new submissions only. Account risk boundaries use actual retained calendar opens, including warmup and DST; daily bounds remain exact UTC instants.
The child imports the retained ESM bytes through a temporary Blob URL, verifies the package/build before strategy factory execution, and runs the existing deterministic TypeScript callback loop against Rust. The current built-in constructor is not a fallback. Durable claiming, heartbeat, cancellation/reaping, lease fencing and atomic result persistence are shared with legacy work. A build mismatch, corrupt dataset or runner without canonical capability fails with a durable diagnostic and no legacy/provider fallback.
Migration 19 adds `canonical_result` to existing results and strengthens admission/result identity guards; it preserves retention triggers. `canonical-result/v1` bypasses legacy percentage conversion and placeholder metrics. Existing required legacy JSON columns contain JSON null for canonical results. F08 remains the statistical evaluator; exact Rust financial facts, zeros, unavailable reasons, owner books and fills survive reopening. Reporting policy version 1 must keep its existing meaning; changed statistics require a new version and compatible retained readers.
### Operator workflow and deployment prerequisite
Use the R01 offline packaging/seeding workflow for repository built-ins, review a retained version in the web catalog, save a backtest, then open Settings → Configure canonical research. An explicitly prepared v2 dataset can be retained with:
```sh
RESEARCH_DATASET_DATABASE_URL=<database> bun run scripts/import-research-dataset.ts --file <v2-dataset.json>
```
The importer validates content/hash before connecting, never infers calendars/actions, does not migrate tables and never overwrites retained bytes. Normal startup migrations own the schema. The canonical picker validates retained content and shows unsupported entries as unavailable. All capital, cost, risk and statistical settings are explicit; legacy settings are not silently translated. Initial capital must fit the existing USD-cent template column, while engine quantities/notionals retain checked eight-place decimals.
Deploy the existing **native research runner (`useRustEngine: true`)**, bundled `orchestrator/dist/native-worker.js`, engine wrapper/addon and lockfile from the same build. Keep executable files immutable while jobs launch/run. Eligibility is an input/artifact preflight, not a worker health check. Accepted runs fail closed after an incompatible deployment; retaining/restoring historical executable builds and an exact reproduction workflow remain R12. No production database was seeded or migrated by this development wave.
### Remaining work and release gates
- Add explicit provider/source preparation only when it can supply v2 availability, calendar, action coverage and universe evidence; do not relabel v1 data eligible or infer missing facts. Freeze the immutable preparation request and bind the first verified dataset atomically before decisions.
- Preserve the current single-asset restriction until the simultaneous-mark policy is resolved. Candidate execution still requires A02 isolation; paper/live operation and default simulator retirement remain separately gated.
- R03 research projects/hypotheses/findings is independently ready and can deliver useful product work without opening these execution gates. R06 remains dependent on completed R05 scope; do not mark it ready from this partial milestone alone.
- No profiling, performance optimization, benchmark runs, DSL, second job engine, simulator or deployment framework was added.
Final validation and source identity are recorded in `manifest.json` → `twenty_third_wave_validation` and the roadmap handoff.
## Authorized source-export preparation slice — 2026-10-24
Implement explicit web upload of complete `HistoricalDatasetInputV2` source metadata/bars, read-only normalized preview and exact-hash retention into the existing immutable dataset store. Reuse `createDatasetV2`, importer custody and current canonical eligibility. Show source/calendar/action/universe declarations and availability assumptions without claiming independent provider certification. Preview writes nothing; retain does not save a template or start a run. Identical retry/concurrent requests converge on one content-addressed row. Unknown/ineligible or unsupported multiasset datasets remain unavailable for canonical execution.
Acceptance: malformed/missing metadata and invalid bars reject; preview hash drift rejects before persistence; corrupt retained rows fail without overwrite; API authorization/CSRF/no-store preserved; file/input/request changes fence stale UI state; exact retention can retry after lost responses; other setup edits survive. A real browser uploads source JSON, previews without writes, retains, selects, saves and runs the unchanged Rust next-open oracle, then reopens identical provenance. Existing importer CLI and v1 datasets remain intact.
This slice excludes v1 conversion, external provider access, inferred evidence, new migrations/schedulers, financial semantics and any default/multiasset/paper/live/AI activation. Full R05 remains partial for durable provider-query preparation and cutover. No performance measurements.
## Validated source-export handoff — 2026-10-24
The above slice is independently reviewed and `partial_validated_uncommitted` on `06039d1`. The web now previews and retains complete explicit source exports using the same normalizer/custody as existing research, then selects through canonical setup. Existing offline importer behavior and historical datasets remain intact; no SQL or engine source changed. Definitive rejection repair, exact uncertain retries, content corruption/concurrency, parent/late UI state and actual native economics pass. The web transport accepts source requests beyond its former 1 MiB cap; this is a functional correction, not a throughput measurement.
Final gates: repository check 1077 integration /150 Rust plus93 tooling/43 utility/44 calculation tests; PostgreSQL240/2157; Chromium16/590; strict affected-test types, all16-file lint/format/hash/DAG/diff checks. Independent agent overlays and root browser/transport changes are accepted. Four prior manual Rust cases remain ignored. Logs/hashes/limits are in `manifest.json` → `thirty_fifth_wave_validation` and the [roadmap handoff](../../ROADMAP.md#thirty-fifth-wave-handoff--2026-10-24). Both disposable containers were removed.
Full R05 stays `in_progress`: automatic provider-query preparation/first binding and default cutover are not delivered. No performance work or candidate/multiasset/paper/live/AI activation occurred. Changes await the next authorized commit.
## Accepted export and stored-source continuation — 2026-10-24
Wave35 export preparation is accepted and committed as `366bee8`. Continue with operator metadata plus existing stored EOD intraday bars; one asset/series, raw1m/5m/1h, interval-start and explicit interval-end assumption only. Read through the actual request-local StorageService adapter without initialize/runtime mutation or provider fallback. Return complete captured input plus existing descriptor; the existing Retain action uses those exact bytes/hash. Source edits after preview affect only a new preview.
**Deliberate simplification:** source preparation is completed before canonical admission. This replaces (does not claim to implement) the earlier pending-query run kind, preparing run phase and first-binding lifecycle. Existing admission already atomically freezes the full immutable request and verified retained hash; the worker checks them under its lease before executing. No second lifecycle is needed to satisfy reproducibility. Asynchronous preparation jobs require a demonstrated product need before reconsideration.
Acceptance adds metadata/scope validation before IO; exact EOD routing, source identity and range; deterministic adapter ordinal (not provider sequence); no invented availability or VWAP; abort before/after reads; valid unavailable evidence preserved; source changes after materialization cannot alter retention/retry or native execution; fresh reads can change identity. Provider connection, missing range, invalid metadata and malformed stored data have distinct failure paths. Actual browser coverage retains the export path, loads EOD via existing adapter, edits underlying rows, and proves stored identity/economics survive save/run/reopen without requery.
Full cutover/default activation remains incomplete, and S06 stays blocked. Daily/QuestDB preparation, v1 conversion, generalized query history, new SQL/runner states and performance work are excluded from this slice. Do not add optional adapters solely to avoid the remaining real owner policy decisions.
## Validated stored-source handoff — 2026-10-24
The stored EOD component is independently reviewed and `partial_validated_uncommitted` on `366bee8`. One raw1m/5m/1h EOD source with complete explicit metadata can be materialized through the existing adapter, inspected and retained before unchanged canonical admission. Existing export mode remains. Source mutations after preview change only a fresh preview; retention/retry and actual Rust execution preserve captured bytes and expected economics. Unsupported or unknown evidence cannot become an executable selection.
Final gates: fullcheck1126 integration/150 Rust (+93 tooling/43 utility/44 calculation); PostgreSQL242/2196; Chromium16/612; strict affected/new-test types and all11-file lint/format/hash/DAG/diff checks. Four preexisting Rust cases remain ignored. Both disposable containers removed. Exact evidence: `manifest.json` → `thirty_sixth_wave_validation`, [roadmap handoff](../../ROADMAP.md#thirty-sixth-wave-handoff--2026-10-24).
The before-admission disposition above replaces deferred preparation rather than claiming to implement it. Full R05 stays `in_progress` for wider cutover/default policy; S06 remains blocked. Daily/QuestDB/v1 adapters are optional, not mandatory work to postpone owner decisions. No performance or AI/paper/live activation. New changes await the next authorized commit.
## Accepted completion — 2026-10-24
Canonical single-asset research is now the default. New legacy admission and worker commands refuse with explicit diagnostics; old results remain readable. Full stored/export preparation precedes immutable admission. Unsupported multi-asset policy remains a capability gate, not an assertion that it was implemented.
Independent review and final repository/native/PostgreSQL/browser gates pass. Exact results and source identities: manifest `thirty_seventh_wave_validation` and the [handoff](../../ROADMAP.md#thirty-seventh-wave-handoff--2026-10-24). No real account migration or paper/live activation occurred.

View file

@ -1,98 +0,0 @@
# R06 — Create immutable experiments and bounded sweep expansion
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product.
Scheduling source of truth: [manifest entry R06](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
## Intended behavior and implementation scope
Expand immutable bounded experiment grids into existing durable runs with unique trial keys and one pinned dataset hash. Reuse outbox/lease/attempt machinery. A retry-failed action creates a new fenced attempt for the same immutable failed logical run, only when no terminal result exists; append prior attempt diagnostics before clearing the active error. Do not overwrite completed results or create a duplicate candidate/attempt framework. Provide a minimal SQL summary projection excluding OHLC/trade arrays now; P05 later owns only profiled large-detail optimization.
Project/hypothesis linkage is optional and must not require R03 tables or placeholder records. Add nullable foreign-key links only when both entity tables exist, in a coordinated additive migration; standalone versions/experiments work first.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- database/postgres/init/ (new migration)
- apps/stock/web-api/src/routes/ (experiment endpoints)
- apps/stock/web-api/src/services/ (experiment expansion)
- apps/stock/orchestrator/src/backtest/run-repository.ts
Write locks: sql-migrations, experiment-api. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
The retained-input component requires the accepted R05 durable-run/provenance slice plus R01/R10/F08/S02/D01/W03/C06/R12. The manifest records that narrower prerequisite; provider preparation and broader default cutover remain outside it. The failed-retry continuation satisfies the remaining acceptance below; final integration evidence is recorded in its validated handoff.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Repeated expansion has identical ordered candidate fingerprints and creates no duplicate logical runs.
- Failed retry preserves run inputs/trial key and prior error/attempt history; stale attempts cannot commit. Completed/cancelled stored results are not silently overwritten.
- Experiment summary lists all outcomes and metrics/provenance without reading/transmitting full trade/OHLC blobs.
- Batch cancellation stops new admission and requests active child cancellation; all candidates use the same frozen data for comparable windows.
## Mandatory tests
- deterministic_grid, duplicate_expand_race, retry_failed_preserves_attempt_history, stale_retry_fenced, completed_result_retry_rejected.
- summary_excludes_detail_payload, partial_batch_failure, cancel_batch, one_dataset_hash_for_all_trials; disposable DB/queue failure tests.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: POST/GET /api/v2/experiments; GET /experiments/:id/trials; POST cancel/retry; preview validates grid and returns count.
- Backend/data dependencies: Experiments table; nullable experiment_id/trial_key on runs; existing result storage.
- Loading/error/empty behavior: API distinguishes empty/unsubmitted, partial, cancelled and terminal states; never averages missing failed trials away.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Authorized component — 2026-10-24
Retained-input single-asset experiments depend on the accepted R05 runner/provenance component (`618fb9e`), not provider preparation or default cutover. One atomic bounded grid uses a current approved retained built-in, one eligible dataset and installed build, and fixed financial/reporting policy. Preview commits to exact inputs; submission receipts survive current eligibility changes. Existing runs/outbox/worker own execution. Failed retry was excluded from this first component; its continuation below supplies the remaining diagnostics/fencing acceptance.
### Pinned experiment contract
`@stock-bot/stock-config/experiments` owns shared request/result DTOs. POST `/api/v2/experiments/preview` validates a saved canonical template plus bounded parameter grid; POST `/api/v2/experiments` requires its exact preview hash and an idempotency key. GET collection/detail exposes every frozen candidate and scalar result evidence; POST `/:id/cancel` is idempotent. Existing authenticated reads and credential mutations apply. Preview includes retained dataset manifest, current approved built-in package, complete financial/reporting policies and installed build. A template/review/build change before submission invalidates the preview. An accepted receipt is replayed before rechecking eligibility.
All children and outbox rows commit with the immutable experiment in one transaction. The initial bound is 100 trials; it bounds atomic admission and does not introduce a parallel scheduler. Only parameters and new run/account/session identities vary. `experiment_id`/`trial_key`/`trial_index` are immutable and mutually exclusive with new-run reproduction lineage. Child submission receipts are null; the experiment owns the unique principal/key receipt. SQL reconstructs exact trial requests from the manifest and preserves ordinary/reproduction admission guards. No template cloning/edit loop or separate financial engine.
Cancellation latches once, cancels pending children and requests worker acknowledgement for active children, preserving terminal outcomes. Counts are derived from actual children; the frozen candidate count exposes missing rows. Compact summaries validate retained provenance and statistical conventions, preserve null reasons and list inconsistent results as incomparable. No detail-array loading or financial recalculation is needed. Failed-run retry was deferred from this first component to the continuation below.
### Validated component handoff
The retained-input component is implemented and independently reviewed. Full repository, PostgreSQL and Chromium gates passed; exact source hashes and logs are in `manifest.json` → `twenty_seventh_wave_validation`. See the twenty-seventh-wave roadmap handoff. This first component is committed as `6f64ef6`; it did not alone complete the full task or release its downstream dependencies.
## Failed-trial retry continuation — 2026-10-24
The retained-input experiment component is committed as `6f64ef6`. This continuation completes its failed-trial retry acceptance using the same immutable logical run. POST `/api/v2/experiments/:id/trials/:runId/retry` requires a stable idempotency key and both observed attempt/retry counters. GET the corresponding `/retries` path returns append-only snapshots captured by accepted manual retries.
The new receipt retains the prior failure directly from SQL before clearing execution state; PostgreSQL timestamp precision is preserved. Current original-version approval and retained build/data eligibility are rechecked for fresh acceptance, with current approval recorded separately from the immutable original request. Completed/cancelled/result-bearing trials and cancelled experiments cannot be retried. Receipt replay precedes current eligibility checks.
Lock order is parent → experiment → run → strategy family. Atomic acceptance increments `manual_retry_count`, resets execution fields and makes the existing outbox due; `attempt_number` remains monotonic and the worker supplies a fresh UUID. Manual retry does not reset the existing lifetime automatic-recovery budget. History is explicitly previous failure snapshots preserved by manual retries, not invented history of every old automatic attempt. Existing simulator/financial semantics remain unchanged.
### Validated retry handoff
R06's retained-input acceptance is complete and independently reviewed; owner accepted and committed it as `b373410` (`done` / `validated_committed`). Existing bounded expansion/cancellation/compact comparison behavior is preserved. Full repository gates, PostgreSQL (190 tests / 1609 assertions) and Chromium (11 workflows / 285 assertions) passed. Exact source hashes and logs: `manifest.json` → `twenty_eighth_wave_validation`.
The retry suite proves exact failure snapshots, duplicate/stale intent handling, lifetime counter monotonicity, rollback, old-attempt fencing, Redis recovery, current original-version approval and actual Rust completion with one result. SQL23 adds guards only to experiment retry semantics; ordinary run lifecycle behavior remains intact. No engine or dispatcher changes were required. R08 is released from this prerequisite by acceptance/commit; broader R05 cutover is still separate.

View file

@ -1,117 +0,0 @@
# R07 — Deliver sweep configuration and comparable-result views
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product.
Scheduling source of truth: [manifest entry R07](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
- **FIN-07 — Verified:** Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. [apps/stock/engine/src/backtest/simple_results.rs:374](../../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../../apps/stock/engine/src/backtest/simple_results.rs#L542).
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
## Intended behavior and implementation scope
Deliver experiment preview/progress/comparison directly on R06 APIs. Accept an existing frozen dataset ID and show its manifest; R11's picker is optional convenience, not a prerequisite. A project/workspace link is optional; users need not build project metadata before comparing a sweep. Reuse current charts/metrics and R06 summary projection.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- apps/stock/web-app/src/features/experiments/ (new)
- apps/stock/web-app/src/features/backtest/components/
- apps/stock/web-app/src/components/ui/DataTable/
Write locks: web-experiments. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Component implementation may proceed against root-pinned R06 DTOs; activation requires integrated retained-input R06 admission/results. The initial component did not expose retry; the continuation below adds controls against the separately reviewed R06 retry contract.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Feature activation/release gates: [W04](W04.md). These do not block implementing or integrating this component against its own tests.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- User previews bounded trial count, submits, sees all statuses, cancels and opens exact candidate runs.
- Default comparison requires matching data, execution/metrics policy, costs and evaluation windows; mismatches remain visible, not silently ranked.
- No full detail blobs on summary list; failed/incomplete counts and null metrics are explicit.
## Mandatory tests
- sweep_to_compare_browser, mixed_policy_warning, partial_failure_visibility, reopen_experiment.
- Large result table rendering measurement and metric-null tests.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: R06 experiment/trial listing; summary metrics projection from result contracts; pagination where needed.
- Backend/data dependencies: Experiments and canonical provenance; full trade arrays are fetched only on run detail.
- Loading/error/empty behavior: Preview loading; invalid grid errors; empty not-yet-submitted; per-trial failed/cancelled; retryable aggregate errors.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Authorized component — 2026-10-24
Implement same-experiment preview, submission, progress, cancellation, scalar comparison and exact run reopening against the pinned R06 component API. Component coding may proceed in parallel; release requires integrated R06 component. Cross-experiment comparison and table performance measurements remain outstanding, with all performance work paused. Full R07 remains incomplete.
### Pinned web workflow
`/experiments` selects a saved canonical backtest, names a sweep and previews a small parameter grid before submission. `/experiments/:experimentId` shows the frozen inputs, all trial outcomes, comparable scalar metrics with units/null reasons, cancellation state and exact saved-run links. An optional backtest query parameter starts from its detail page. The API is shared with other authorized clients; the browser does not calculate economics or rank incompatible runs.
Ambiguous submission preserves its exact body/key, and only an explicit new intent may replace it. Form edits invalidate previews; route changes and late reads/mutations cannot replace another experiment. Loading, empty, failed, missing and incomparable outcomes remain distinct. Refresh/reopen must retain immutable evidence and cancelled/partial outcomes. The browser acceptance executes real retained native trials, mutates the template after admission, replays the submission receipt, opens results and cancels a separate pending batch.
### Validated component handoff
The retained-input component is implemented and independently reviewed. Full repository, PostgreSQL and Chromium gates passed; exact source hashes and logs are in `manifest.json` → `twenty_seventh_wave_validation`. See the twenty-seventh-wave roadmap handoff. This first component is committed as `6f64ef6`; it did not alone complete the full task or release its downstream dependencies.
## Retry controls continuation — 2026-10-24
The first experiment UI component is committed as `6f64ef6`. Add per-trial failed-retry review/confirmation and lazy immutable failure-history views against the pinned R06 API. Preserve exact unresolved body/key through refresh and guard late responses, cancellation and route changes; a later failure requires a deliberate new intent. Reopening must show saved failure evidence after successful completion. Broader comparison/table measurement remains outside this continuation; performance work stays paused.
### Validated retry controls handoff
The retry/history component is independently reviewed and committed as `b373410`; full R07 remains partial. The actual Chromium workflow retries a failed canonical trial, verifies the original immutable inputs despite template edits, replays the accepted receipt after completion and reopens saved failure history and the native result. Interaction tests cover uncertain responses, stale refresh/route responses, cancellation coordination, null/history/error states and explicit discard/new intent. Exact logs and hashes: `manifest.json` → `twenty_eighth_wave_validation`.
Full R07 remains in progress for broader cross-experiment comparison and table measurements. All performance work stays paused. No new finance, statistics or result-ranking logic was added.
## Cross-experiment comparison continuation — 2026-10-24
Compare two standalone saved parameter/cost experiments from the existing list. The explicitly selected left trial is the reference; omitted key means its frozen index zero even if failed or unavailable. Show every original-order outcome. Match retained dataset/window/capital/effective costs/execution/risk/clock/analytics/seed/build/models, normalizing only specified admission/owner IDs; strategy implementation and parameters may intentionally differ. Separate matching settings from compact saved-summary availability. No ranking, financial recomputation or statistical-validity claim.
The GET API uses one repeatable read-only transaction and existing compact detail reads. Historical reads survive archival/current approval changes. Strict browser decoder verifies pair/reference/ordered row identities; route changes fence late reads, reload retains the reference, and existing editor navigation protection covers comparison links. Actual native browser acceptance plus pure/API/PostgreSQL/UI tests cover cost overrides, incomplete evidence, policy differences, strict errors and snapshot consistency.
Functional acceptance and the explicitly paused large-table measurement are tracked separately. Do not claim the measurement ran. Once this functional component is accepted and committed, downstream R09 can depend on it without waiting for performance work.
### Validated comparison handoff
The functional comparison component is independently accepted and committed as `46a4f13` at owner request. All 17 integrated source/test/config files match reviewed snapshots. Whole repository gates pass (988 integration /150 Rust), final PostgreSQL 228/2013 assertions and Chromium 16/500; all authored tests pass strict types/lint and changed-source formatting. Exact hashes, commands and review corrections: `manifest.json` → `thirty_third_wave_validation`. Historical compact reads share a repeatable read-only transaction; actual native browser acceptance confirms cost references, changed/archived inputs, saved metrics and exact-run reopening.
The large-table measurement remains explicitly paused/unrun; full R07 therefore stays partial. R09 consumes the accepted sweep/comparison/retry UI through the recorded `46a4f13` component prerequisite. No new economic formulas, ranking, statistical certification or performance work was added.
## Completion measurement — 2026-10-24
The owner resumed required measurements with the instruction to finish scheduled tasks. All functional components and the remaining large-table measurement are now accepted. `scripts/benchmark-experiment-tables.ts --measure --samples=5` verified all rows, outcomes, parameters, numeric/null metrics, links and current response revisions across 20 production Chromium samples. Root verified the source archive and reran all 8 harness tests (495 assertions); strict types, lint and formatting pass.
| Compact view | Fresh-context navigation median | Warm refresh median |
| --- | --- | --- |
| 1 trial | 102.5 ms | 48.9 ms |
| 25 trials | 101.1 ms | 48.6 ms |
| 100 trials | 114.6 ms | 47.9 ms |
| 100 + 100 comparison | 148.3 ms | 91.1 ms |
Reference changes measured 74.3/67.9 ms for failed/completed reference trials. These synthetic UI-only measurements use one browser with fresh contexts; they do not measure cold OS caches, finance, database access or research throughput. Five samples cannot establish tail latency. External font requests were blocked and fallback fonts used. Keep existing tables at current limits; virtualization would add complexity without demonstrated need. Exact provenance and summaries: `manifest.json` → `r07_table_validation`.

View file

@ -1,130 +0,0 @@
# R08 — Add bounded chronological and reset-segment validation
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Quantitative research integrity.
Scheduling source of truth: [manifest entry R08](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168).
- **DAT-01 — Verified:** Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. [libs/core/types/src/historical-data.ts:90](../../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L177).
- **FIN-07 — Verified:** Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. [apps/stock/engine/src/backtest/simple_results.rs:374](../../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../../apps/stock/engine/src/backtest/simple_results.rs#L542).
## Intended behavior and implementation scope
First implement bounded chronological parameter selection and nonoverlapping walk-forward recipes for deterministic registered strategies. Explicit warmup and evaluation windows; each validation segment starts from its declared initial capital and empty positions with warmed indicators, not carried money/state. Present ordered segment returns as a labelled reset-segment research series; do not compound, average risk-adjusted metrics or claim one continuous tradable equity curve. Parameter sensitivity reuses the existing bounded grid. Cost sensitivity needs a separate explicit immutable financial-policy admission contract; costs are not strategy parameters and must not mutate saved templates. Reject trainable/overlapping-label models until their fit-artifact and declared horizon/embargo contracts are supplied; do not invent general ML infrastructure for SMA.
Persist the immutable validation manifest/report as experiment-owned JSON on the R06 experiment (or a focused child row if immutability requires it), keyed by experiment/report version and containing every contributing run ID, selection rule and segment policy. This is not R03 research-findings storage. Reopening an experiment must recover the same report; new inputs require a new experiment/report identity.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- apps/stock/web-api/src/services/ (validation recipes)
- apps/stock/orchestrator/src/backtest/
- test/integration/ (research validation tests)
- database/postgres/init/ and reviewed migration registry (only if experiment report persistence needs an additive column/table)
Write locks: validation-contract, sql-migrations. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [R06](R06.md) integrated.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- Training/validation/test inputs and selection rule are frozen before execution. Test values cannot affect earlier parameter selection or fitted inputs.
- Every segment declares capital/reset/warmup policy; warmup has no orders/fills; OOS intervals do not overlap.
- All tried candidates and holdout accesses remain visible. Independent segment cash accounts are not summed/stitched as a continuous portfolio.
- Immutable experiment-owned reports reopen without any project/hypothesis/findings records or R03 API; conflicting attempts cannot overwrite a completed report.
- For a later declared nonzero label horizon require gap/purge >= horizon; unsupported/missing horizon/trainable fit metadata rejects rather than leaking future data.
## Mandatory tests
- chronological_selection, test_suffix_cannot_change_selection, warmup_no_trades, nonoverlapping_windows, reset_segment_accounting.
- experiment_report_without_research_metadata, immutable_report_reopen, conflicting_report_write_rejected.
- reject_uncontracted_trainable_model, horizon_gap_validation, bounded_cost_grid; fixed seeds and retained selected-parameter artifacts.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: Validation recipe and immutable report under the existing experiment API; report includes every contributing run and declared segment/warmup policy.
- Backend/data dependencies: R06 experiments/runs and experiment-owned JSON reports. No R03 analysis_artifacts dependency or separate optimization service.
- Loading/error/empty behavior: Typed invalid-window/insufficient-warmup errors; validation failures are not profitable candidates.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Authorized first component — 2026-10-24
R06 is accepted/committed as `b373410`. Begin with a read-only chronological preflight using the existing approved canonical template, bounded grid and retained source dataset. POST `/api/v2/experiments/validation/preview` prepares explicit train/validation/test slices, availability-aware warmup diagnostics, exact source/phase hashes and reset-account requests. The existing experiment editor exposes this input check without a submit/save control.
The fixed future selection protocol maximizes every candidate's finite comparable training total return, breaking ties by original candidate index. Failed/missing/incomparable/null candidates block later selection. Validation and test assess that same winner; neither retunes. Only deterministic unfitted built-ins and zero label horizon are supported. Warmup can overlap prior phases; evaluation intervals cannot overlap. No financial policy is recalculated; only dataset identity and calendar-derived risk-session clocks change per phase.
This component is explicitly **prepared input, not durable experiment evidence**. It writes no datasets, runs, experiments or reports and performs no selection or holdout execution. Existing SQL22/23 require one dataset per experiment; changing that admission/retry contract belongs to the next coordinated durable slice. Full R08 remains incomplete until frozen recipe, selection gating, reports, reset-segment validation and cost-sensitivity acceptance are met. No findings/regime integration or performance work is included.
### Validated preflight handoff
The first component is independently reviewed and committed as `67ab30c`; full R08 remains `in_progress`. Exact bars and legacy conversion provenance survive slicing; immediate source lineage stays in the outer preview. Warmup diagnostics respect actual availability and retained strategy ordering, including observations at/after the evaluation end. Existing account-clock calculation is reused for each phase without changing financial policy.
Full repository checks passed (786 integration /150 Rust tests), PostgreSQL (194 tests /1655 assertions), Chromium (12 workflows /306 assertions), strict test types, lint and formatting. Native regressions prove independent initial cash/positions/state, no warmup orders/fills and earlier-phase invariance to a changed test suffix. Browser/database tests prove preview makes no retained-data/job/template writes. Hashes and logs: `manifest.json` → `twenty_ninth_wave_validation`.
Next: immutable experiment-owned recipe and guarded staged admission, with all candidate training evidence complete before a write-once winner selection and validation/test admission. Existing ordinary experiment/retry behavior must remain intact. This preflight does not satisfy immutable report reopening, holdout access history, walk-forward aggregation or cost-sensitivity execution; R09 remains blocked.
## Authorized durable single-recipe component — 2026-10-24
Preflight is accepted and committed as `67ab30c`. Extend the training experiment with the immutable preparation manifest and write-once selection/report. Validation and test are ordinary singleton child experiments linked to the root, preserving existing run, outbox and retry contracts. Reuse full `getRunResults` financial/analytics validation before sealing evidence; compact UI summaries are insufficient.
Explicit receipt-bearing submit, select-and-admit and finalize endpoints; GET remains read-only. Retain all three slices atomically with training admission. All training candidates must complete and be comparable before selection. Freeze selection and both same-winner heldout experiments/runs/outbox in one transaction. Each phase resets capital/state as declared. Accepted receipt replay precedes current eligibility checks; current original approval/build gates new execution only. Finalization assembles verified historical evidence even after archival/build changes. Root cancellation propagates through existing cancellation routes and SQL guards.
The web supports saved validations, training admission, selection, heldout progress and report reopen; ambiguous requests retain exact intent/key and exclude conflicting editor actions. Child experiment links reuse existing retry/history UI. SQL guards protect recipe lineage, phase linkage, candidate completeness, selection and report immutability. Test native full lifecycle, prefix independence, all-candidate failures, atomic rollback, concurrent receipts/cancellation, upgrade preservation and browser recovery. No new scheduler, simulator, run schema, AI/candidate activation or performance work. Multi-window walk-forward/reset-series aggregation and cost sensitivity remain outstanding after this component.
### Validated durable handoff
The single-recipe component is independently accepted and committed as `abd1c5b`. Shared Rust economics, ordinary runs/outbox, SQL22/23 retry semantics and original evidence are preserved. All repository gates pass (825 integration /150 Rust tests), PostgreSQL/Redis 205 tests /1773 assertions, Chromium 13 workflows /357 assertions, strict test types and lint. Exact source hashes and review evidence: `manifest.json` → `thirtieth_wave_validation`.
The UI supports the complete staged lifecycle and immutable report reopening. Native regressions prove unchanged training scores/winner after modifying only future test prices; malformed or missing candidate evidence cannot seal selection. Atomicity, SQL tamper, receipt/cancel races, migration preservation and phase retries pass. Full R08 remains incomplete for repeated walk-forward windows/reset-series aggregation and bounded cost sensitivity. R09 remains blocked. No performance or trading/default/AI activation occurred.
## Authorized repeated-window component — 2026-10-24
The durable single-window workflow is accepted and committed as `abd1c5b`. Implement bounded walk-forward series now; cost sensitivity remains separate because it needs an explicit financial-policy admission branch. Freeze 2–10 ordered recipes and common source/build/grid/policies before any member runs. Count every planned training candidate and both future holdouts against the 100-run bound. Training starts cannot decrease, training cutoffs strictly increase, and each test end must be no later than the next validation start. Existing per-window boundary/warmup checks remain authoritative.
A focused series header and immutable train-root memberships preserve existing single-window semantics; SQL22–24 files remain unchanged. Admission of all member roots/slices/runs/outbox is atomic. Reuse per-window actions and ordinary retries; no bulk-select scheduler or general workflow framework. Whole-series cancellation reaches all windows, while local member cancellation only blocks series completion. Historical finalization verifies every sealed report and its canonical result facts, copying ordered validation/test reset segments without new financial or statistical formulas. Receipt replay precedes mutable eligibility.
The web provides explicit windows, preview, submission, member links, report save/reopen and honest missing/failed/cancelled states. Required proofs include total budget/chronology, later-suffix independence, partial-admission rollback, exact immutable membership, receipt/cancel races, old evidence preservation, pool1 transactions and the full two-window native browser lifecycle. Full R08 remains partial for bounded cost scenarios after this component.
### Validated walk-forward handoff
The repeated-window component is independently accepted and committed as `3ed7b98`. Forty-one source/test/config files preserve the existing Rust financial engine, worker/run/outbox model and SQL22–24 behavior. New SQL25 headers and exact train-root membership guards keep all-window admission atomic; full native evidence is checked again before sealing an immutable ordered reset-segment report. Member cancellation stays local; series cancellation prevents new member actions without changing completed evidence.
The web supports explicit 2–10-window recipes, full promised-run counts, synchronous shared submission ownership, member actions through existing pages, and saved report reopen. Native tests prove future-suffix independence, unchanged old migrations/receipts/leases, partial-admission rollback, actual lock contention, finalization receipt races and rejection of corrupted financial/analytics evidence. Repository test gates pass (882 integration /150 Rust), PostgreSQL/Redis 215 tests /1881 assertions, Chromium 14 workflows /412 assertions; final source and authored-test lint/types pass. Exact commands, formatting-only corrections and old fixture lint limitations are recorded in `manifest.json` → `thirty_first_wave_validation`.
Full R08 remains partial for bounded cost sensitivity; R09 remains blocked. Next scope should define supported fee/slippage scenarios as immutable execution-policy inputs and reuse canonical runs/results, without template mutation, strategy-parameter hacks, a second simulator or a window×cost scheduler. No regime/finding integration, performance work or AI/default/trading activation is included.
## Authorized cost-sensitivity component — 2026-10-24
Complete the remaining bounded-cost diagnostic requirement using one existing experiment row with a versioned cost manifest. Its baseline is the current approved saved template and empty parameter grid; trial 0 preserves original costs, while1–99 explicit normalized distinct fee/slippage pairs vary only those two canonical rate fields. Every trial reruns Rust with independent account state. Preserve all other strategy/data/build/risk/execution/analysis inputs. Costs can change fills and funding decisions, so do not subtract estimates from old P&L or assume monotonic returns.
Reuse the existing editor ordinary owner, list/detail/retry/history and receipt APIs; no new header/report/scheduler. Preserve strict v1 validation sources, ordinary parameter keys, old SQL22–25 and all reproduction guards. Add SQL26 version dispatch and one expected-request helper for run/retry insertion. Require native baseline economic parity, controlled fee/slippage/funding fixtures, original-policy retry/reproduction after template edits, direct SQL/atomicity/receipt/cancel races, upgrade preservation and actual browser reopen. This template study makes no heldout/OOS claim; a completed-source selector and joint cost×parameter/window studies are excluded.
### Validated full-task handoff — 2026-10-24
Full supported R08 is independently reviewed and accepted, committed as `397cd0e` at owner request. Waves 29–31 provide frozen chronological input preparation, durable fixed-winner selection, immutable reports and bounded nonoverlapping heldout reset-window series. Wave 32 closes bounded cost diagnostics with one existing experiment type, automatic original-cost baseline and 1–99 explicit fee/slippage pairs. Fixed parameters/data/capital/other risk/build settings and the authoritative Rust engine are preserved; existing retry/reproduction and web workbench flows are reused.
Every repository gate passed (926 integration /150 Rust), final PostgreSQL/Redis 224 tests /1967 assertions and Chromium 15 workflows /457 assertions. Exact sources, independent reviews, controlled native fee/slippage/funding oracles, baseline economic parity, SQL/admission/recovery proofs and root browser evidence: `manifest.json` → `thirty_second_wave_validation`.
The unsupported-model acceptance is implemented as explicit rejection of trained/nonzero/missing-horizon inputs, not general purge/embargo fitting. Template cost diagnostics do not claim heldout/OOS validation or automatic ranking. Completed-source selectors, cost×parameter/window studies and fitted-model infrastructure remain optional future scope. No performance work, AI/candidate or trading/default activation occurred. R09 also depends on partial R07; next non-performance work is cross-experiment comparison, with table measurements still paused.

View file

@ -1,83 +0,0 @@
# R09 — Expose validation, cost and regime evidence in the workbench
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product.
Scheduling source of truth: [manifest entry R09](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
## Evidence and root cause
- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168).
- **WEB-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211).
## Intended behavior and implementation scope
Expose stored chronological/cost validation evidence from R08. Regime panels render only when valid as-of regime annotations exist; otherwise show unavailable, not fake classification. The basic validation UI need not wait for S05; enabling that example's regime comparison requires its artifact contract.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- apps/stock/web-app/src/features/experiments/
- apps/stock/web-app/src/features/research/
- apps/stock/web-app/src/features/backtest/components/
Write locks: web-experiments. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires the accepted functional component of [R07](R07.md) and [R08](R08.md) integrated. R07's explicitly paused table measurement is not a citation prerequisite; the manifest records its accepted component commit.
Architecture decisions: ADR-006. Agents may not independently amend their policies.
Conditional activation: regime comparison requires [S05](S05.md); saving/linking a research finding requires [R03](R03.md). Neither blocks basic validation display.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
## Acceptance criteria
- User can validate and inspect each OOS segment with reset/warmup/cost assumptions visible.
- Regime data missing => explicit unavailable panel; present => sample counts/unclassified bucket and window coverage displayed.
- Validation display works without R03. Enable save/link-finding only when R03 exists; link the exact experiment/report identity and contributing run/metric references through its existing evidence API. Otherwise show the action unavailable.
- No client-side accounting or continuous-equity claim for reset segments.
## Mandatory tests
- walk_forward_browser, train_test_badges, insufficient_sample_warning, regime_slice_reconciliation.
- Loading/empty/failure states for incomplete validation; validation_without_findings_api; save_finding_requires_R03.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## Regression risks and rollback
Schema/API backward compatibility, historical provenance and UI state regression.
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
## Web/API contract and user states
- API: R08 experiment-owned immutable recipes/reports. R03 evidence-linked findings only for the conditionally enabled save action.
- Backend/data dependencies: Canonical returns, as-of regime annotations and sample counts; no client-side financial recomputation.
- Loading/error/empty behavior: Loading each segment; unclassified regime bucket; invalid partition feedback; explicit partial validation.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
## Authorized source-citation continuation — 2026-10-24
R07 functional comparison is accepted as `46a4f13`; its paused measurement does not gate this task. R03/R08 are committed. Existing phase/reset/warmup/cost/sample displays are retained. Add one optional exact experiment/chronological-report/walk-forward-report source to each immutable artifact revision and preserve existing run/metric evidence. All cited runs must belong to that source; sealed reports are verified against full retained native evidence through the same read-only client. Historical source resolution ignores current admission/archive/cancellation gates. Existing create/revise locks and narrative-unvalidated status remain.
Use additive SQL27 and existing findings endpoints/form, not a new store or scheduler. An omitted source on revision preserves the prior source; explicit null detaches only the new revision. Generic experiment details expose a server-derived standalone flag so phase pages cannot masquerade as standalone findings. Save actions lazily load research destinations; report viewing remains independent of R03 availability. Preserve ambiguous-create behavior and original single-run findings.
No persisted as-of regime annotation contract exists: S05's internal volatility flag and current analytics endpoint do not qualify. Show regime counts/coverage unavailable, never zero or inferred classifications. Positive regime reconciliation remains conditional future capability, not a test claimed by this slice. Required gates include exact sources/metrics, forged-report rejection, raw SQL/upgrade preservation, snapshot/pool1/concurrent revisions, archival historical reads, source-preserving edits and actual native browser save/reopen. Performance remains paused.
## Validated handoff — 2026-10-24
Supported scope is independently reviewed and validated on `46a4f13`; status is `review`, new changes uncommitted. Existing OOS/reset/cost displays are retained. All three exact source kinds save through the existing finding API/form, retain canonical contributing run/metric references, survive revision/history and reopen the exact source. SQL27 and historical read verification reject source/metric/report tampering while preserving old findings and archived evidence. Actual native Chromium workflows cover cost, chronological and walk-forward citations without admitting extra runs.
Validation: full repository check passed 1024 integration /150 Rust, plus 93 tooling /43 utility /44 calculation tests; final PostgreSQL/Redis 235/2099 and Chromium 16/569. Strict test types, source/test lint, formatting, diff/source hash/DAG checks passed. The real SQL24 upgrade regression confirms missing role metadata fails closed before migration and ordinary experiments qualify afterward. Four preexisting Rust cases remain ignored. Both temporary test containers were removed.
Positive `regime_slice_reconciliation` remains conditional and unrun because no retained as-of annotation contract exists. The unavailable-state UI is tested; S05 alone does not enable classification. No performance work, financial changes or trading/AI activation. Exact hashes, logs, independent review and limits: [wave34 manifest evidence](../manifest.json), [roadmap handoff](../../ROADMAP.md#thirty-fourth-wave-handoff--2026-10-24).
Accepted by owner continuation and committed as `06039d1` on 2026-10-24. Supported R09 is done; conditional regime-annotation limitations remain unchanged.

Some files were not shown because too many files have changed in this diff Show more